Merge from trunk.
authorPaul Eggert <eggert@cs.ucla.edu>
Fri, 25 May 2012 18:19:24 +0000 (11:19 -0700)
committerPaul Eggert <eggert@cs.ucla.edu>
Fri, 25 May 2012 18:19:24 +0000 (11:19 -0700)
38 files changed:
1  2 
src/ChangeLog
src/alloc.c
src/buffer.c
src/character.h
src/data.c
src/dbusbind.c
src/dispextern.h
src/dispnew.c
src/editfns.c
src/eval.c
src/fileio.c
src/fns.c
src/font.h
src/frame.h
src/gnutls.c
src/gtkutil.c
src/insdel.c
src/intervals.c
src/keyboard.c
src/keymap.c
src/lisp.h
src/lread.c
src/print.c
src/puresize.h
src/search.c
src/sound.c
src/sysdep.c
src/term.c
src/textprop.c
src/undo.c
src/w32fns.c
src/w32menu.c
src/window.c
src/xdisp.c
src/xfns.c
src/xselect.c
src/xterm.c
src/xterm.h

diff --combined src/ChangeLog
- 2012-04-22  Paul Eggert  <eggert@cs.ucla.edu>
++2012-05-25  Paul Eggert  <eggert@cs.ucla.edu>
 +
++      Fix integer width and related bugs (Bug#9874).
 +      * process.h (struct Lisp_Process): Members tick and update_tick
 +      are now of type EMACS_INT, not int.
-       Fix integer width and related bugs (Bug#9874).
 +      * alloc.c (pure_bytes_used_lisp, pure_bytes_used_non_lisp):
 +      (allocate_vectorlike, buffer_memory_full, struct sdata, SDATA_SIZE)
 +      (string_bytes, check_sblock, allocate_string_data):
 +      (compact_small_strings, Fmake_bool_vector, make_string)
 +      (make_unibyte_string, make_multibyte_string)
 +      (make_string_from_bytes, make_specified_string)
 +      (allocate_vectorlike, Fmake_vector, find_string_data_in_pure)
 +      (make_pure_string, make_pure_c_string, make_pure_vector, Fpurecopy)
 +      (mark_vectorlike):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (allocate_pseudovector):
 +      Use int, not EMACS_INT, where int is wide enough.
 +      (inhibit_garbage_collection, Fgarbage_collect):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * bidi.c (bidi_mirror_char): Use EMACS_INT, not int, where
 +      int might not be wide enough.
 +      (bidi_cache_search, bidi_cache_find, bidi_init_it)
 +      (bidi_count_bytes, bidi_char_at_pos, bidi_fetch_char)
 +      (bidi_at_paragraph_end, bidi_find_paragraph_start)
 +      (bidi_paragraph_init, bidi_resolve_explicit, bidi_resolve_weak)
 +      (bidi_level_of_next_char, bidi_move_to_visually_next):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * buffer.c (copy_overlays, Fgenerate_new_buffer_name)
 +      (Fkill_buffer, Fset_buffer_major_mode)
 +      (advance_to_char_boundary, Fbuffer_swap_text)
 +      (Fset_buffer_multibyte, overlays_at, overlays_in)
 +      (overlay_touches_p, struct sortvec, record_overlay_string)
 +      (overlay_strings, recenter_overlay_lists)
 +      (adjust_overlays_for_insert, adjust_overlays_for_delete)
 +      (fix_start_end_in_overlays, fix_overlays_before, modify_overlay)
 +      (Fmove_overlay, Fnext_overlay_change, Fprevious_overlay_change)
 +      (Foverlay_recenter, last_overlay_modification_hooks_used)
 +      (report_overlay_modification, evaporate_overlays, enlarge_buffer_text):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (validate_region): Omit unnecessary test for b <= e,
 +      since that's guaranteed by the previous test.
 +      (adjust_overlays_for_delete): Avoid pos + length overflow.
 +      (Fmove_overlay, Fdelete_overlay, add_overlay_mod_hooklist)
 +      (report_overlay_modification):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Foverlays_at, Fnext_overlay_change, Fprevious_overlay_change):
 +      Omit pointer cast, which isn't needed anyway, and doesn't work
 +      after the EMACS_INT -> ptrdiff_t change.
-       (Fmove_overlay): Delete an evaporating overlay
-       if it becomes empty after its bounds are adjusted to fit within
-       its buffer.  Without this fix, in a nonempty buffer (let ((o
-       (make-overlay 1 2))) (overlay-put o 'evaporate t) (move-overlay o 0 1))
-       yields an empty overlay that has the evaporate property, which is
-       not supposed to happen.  (Bug#9642)
 +      * buffer.h: Adjust decls to match defn changes elsewhere.
 +      (struct buffer_text, struct buffer):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      Use EMACS_INT, not int, where int might not be wide enough.
 +      * bytecode.c (unmark_byte_stack, exec_byte_code): Use ptrdiff_t,
 +      not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (exec_byte_code): Use tighter memory-full test, one that checks
 +      for alloca overflow.  Don't compute the address of the object just
 +      before an array, as that's not portable.  Use EMACS_INT, not
 +      ptrdiff_t or int, where ptrdiff_t or int might not be wide enough.
 +      * callint.c (Fcall_interactively):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * callproc.c (call_process_kill, Fcall_process):
 +      Don't assume pid_t fits into an Emacs fixnum.
 +      (call_process_cleanup, Fcall_process, child_setup):
 +      Don't assume pid_t fits into int.
 +      (call_process_cleanup, Fcall_process, delete_temp_file)
 +      (Fcall_process_region):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fcall_process): Simplify handling of volatile integers.
 +      Use int, not EMACS_INT, where int will do.
 +      * casefiddle.c (casify_object, casify_region, operate_on_word)
 +      (Fupcase_word, Fdowncase_word, Fcapitalize_word):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (casify_object): Avoid integer overflow when overallocating buffer.
 +      * casetab.c (set_identity, shuffle): Prefer int to unsigned when
 +      either works.  Use lint_assume to convince GCC 4.6.1 that it's OK.
 +      * category.c (Fchar_category_set): Don't assume fixnum fits in int.
 +      * category.h (CATEGORYP): Don't assume arg is nonnegative.
 +      * ccl.c (GET_CCL_INT): Remove; no longer needed, since the
 +      integers are now checked earlier.  All uses replaced with XINT.
 +      (ccl_driver):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      For CCL_MapSingle, check that content and value are in int range.
 +      (ccl_driver, Fregister_code_conversion_map):
 +      Check that Vcode_version_map_vector is a vector.
 +      (resolve_symbol_ccl_program): Check that vector header is in range.
 +      Always copy the vector, so that we can check its contents reliably
 +      now rather than having to recheck each instruction as it's being
 +      executed.  Check that vector words fit in 'int'.
 +      (ccl_get_compiled_code, Fregister_ccl_program)
 +      (Fregister_code_conversion_map): Use ptrdiff_t, not int, for
 +      program indexes, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fccl_execute, Fccl_execute_on_string): Check that initial reg
 +      contents are in range.
 +      (Fccl_execute_on_string): Check that status is in range.
 +      * ccl.h (struct ccl_program.idx): Now ptrdiff_t, not int.
 +      * character.c (char_resolve_modifier_mask, Fchar_resolve_modifiers):
 +      Accept and return EMACS_INT, not int, because callers can pass values
 +      out of 'int' range.
 +      (c_string_width, strwidth, lisp_string_width, chars_in_text)
 +      (multibyte_chars_in_text, parse_str_as_multibyte)
 +      (str_as_multibyte, count_size_as_multibyte, str_to_multibyte)
 +      (str_as_unibyte, str_to_unibyte, string_count_byte8)
 +      (string_escape_byte8, Fget_byte):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Funibyte_string): Use CHECK_RANGED_INTEGER, not CHECK_NATNUM, to
 +      avoid mishandling large integers.
 +      * character.h: Adjust decls to match defn changes elsewhere.
 +      * charset.c (load_charset_map_from_file, find_charsets_in_text)
 +      (Ffind_charset_region):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (load_charset_map_from_file): Redo idx calculation to avoid overflow.
 +      (load_charset_map_from_vector, Fdefine_charset_internal):
 +      Don't assume fixnum fits in int.
 +      (load_charset_map_from_vector, Fmap_charset_chars):
 +      Remove now-unnecessary CHECK_NATNUMs.
 +      (Fdefine_charset_internal): Check ranges here, more carefully.
 +      Don't rely on undefined behavior with signed left shift overflow.
 +      Don't assume unsigned int fits into fixnum, or that fixnum fits
 +      into unsigned int.  Don't require max_code to be a valid fixnum;
 +      that's not true for gb10830 4-byte on a 32-bit host.  Allow
 +      invalid_code to be a cons, for the same reason.  Require code_offset
 +      to be a character.  Avoid int overflow if max_char is close
 +      to INT_MAX.
 +      (CODE_POINT_TO_INDEX): On 32-bit hosts, return int, not unsigned;
 +      this is intended anyway and avoids some undefined behavior.
 +      (load_charset_map): Pass unsigned, not int, as 2nd arg of
 +      INDEX_TO_CODE_POINT, as that's what it expects.
 +      (Funify_charset, encode_char): Don't stuff unsigned vals into int vars.
 +      * charset.h (DECODE_CHAR): Return int, not unsigned;
 +      this is what was intended anyway, and it avoids undefined behavior.
 +      (CHARSET_OFFSET): Remove unused macro, instead of fixing its
 +      integer-overflow issues.
 +      (ENCODE_CHAR): Return unsigned on all hosts, not just on 32-bit hosts.
 +      Formerly, it returned EMACS_INT on 64-bit hosts in the common case
 +      where the argument is EMACS_INT, and this behavior is not intended.
 +      * chartab.c (Fmake_char_table, Fset_char_table_range)
 +      (uniprop_get_decoder, uniprop_get_encoder):
 +      Don't assume fixnum fits in int.
 +      * cmds.c (move_point): New function, that does the gist of
 +      Fforward_char and Fbackward_char, but does so while checking
 +      for integer overflow more accurately.
 +      (Fforward_char, Fbackward_char): Use it.
 +      (Fforward_line, Fend_of_line, internal_self_insert)
 +      (internal_self_insert):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      Fix a FIXME, by checking for integer overflow when calculating
 +      target_clm and actual_clm.
 +      * coding.c (detect_coding_XXX, encode_coding_XXX, CODING_DECODE_CHAR)
 +      (CODING_ENCODE_CHAR, CODING_CHAR_CHARSET, CODING_CHAR_CHARSET_P)
 +      (ASSURE_DESTINATION, coding_alloc_by_realloc)
 +      (coding_alloc_by_making_gap, alloc_destination)
 +      (detect_coding_utf_8, encode_coding_utf_8, decode_coding_utf_16)
 +      (encode_coding_utf_16, detect_coding_emacs_mule)
 +      (decode_coding_emacs_mule, encode_coding_emacs_mule)
 +      (detect_coding_iso_2022, decode_coding_iso_2022)
 +      (encode_invocation_designation, encode_designation_at_bol)
 +      (encode_coding_iso_2022, detect_coding_sjis, detect_coding_big5)
 +      (decode_coding_sjis, decode_coding_big5, encode_coding_sjis)
 +      (encode_coding_big5, detect_coding_ccl, decode_coding_ccl)
 +      (encode_coding_ccl, encode_coding_raw_text)
 +      (detect_coding_charset, decode_coding_charset)
 +      (encode_coding_charset, detect_eol, decode_eol, produce_chars)
 +      (produce_composition, produce_charset, produce_annotation)
 +      (decode_coding, handle_composition_annotation)
 +      (handle_charset_annotation, consume_chars, decode_coding_gap)
 +      (decode_coding_object, encode_coding_object, detect_coding_system)
 +      (Ffind_coding_systems_region_internal, Fcheck_coding_systems_region)
 +      (code_convert_region, code_convert_string)
 +      (Fdefine_coding_system_internal)
 +      (coding_set_source, coding_set_destination):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (setup_iso_safe_charsets, consume_chars, Funencodable_char_position)
 +      (Fdefine_coding_system_internal):
 +      Don't assume fixnums fit in int.
 +      (decode_coding_gap, decode_coding_object, encode_coding_object)
 +      (Fread_coding_system, Fdetect_coding_region)
 +      (Funencodable_char_position, Fcheck_coding_systems_region)
 +      (get_translation, handle_composition_annotation, consume_chars):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (consume_chars): Rewrite to not calculate an address outside buffer.
 +      (Ffind_operation_coding_system): NATNUMP can eval its arg twice.
 +      Don't access memory outside of the args array.
 +      (Fdefine_coding_system_internal): Check for charset-id overflow.
 +      (ENCODE_ISO_CHARACTER): Use unsigned, not int, to store the unsigned
 +      result of ENCODE_CHAR.
 +      * coding.h: Adjust decls to match defn changes elsewhere.
 +      (struct coding_system):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * composite.c (get_composition_id, find_composition)
 +      (run_composition_function, update_compositions)
 +      (compose_text, composition_gstring_put_cache)
 +      (composition_gstring_p, composition_gstring_width)
 +      (fill_gstring_header, fill_gstring_body, autocmp_chars)
 +      (composition_compute_stop_pos, composition_reseat_it)
 +      (composition_update_it, struct position_record)
 +      (find_automatic_composition, composition_adjust_point)
 +      (Fcomposition_get_gstring, Ffind_composition_internal):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (update_compositions):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * composite.h: Adjust decls to match defn changes elsewhere.
 +      (struct composition):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * data.c (let_shadows_buffer_binding_p, let_shadows_global_binding_p):
 +      Do not attempt to compute the address of the object just before a
 +      buffer; this is not portable.
 +      (Faref, Faset):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Faset): Use int, not EMACS_INT, where int is wide enough.
 +      (Fstring_to_number): Don't assume fixnums fit in int.
 +      (Frem): Don't assume arg is nonnegative.
 +      * dbusbind.c (xd_append_arg): Check for integers out of range.
 +      (Fdbus_call_method): Don't overflow the timeout int.
++      (extract_signed, extract_unsigned): New functions.
 +      * dired.c (directory_files_internal, file_name_completion, scmp)
 +      (file_name_completion_stat):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (file_name_completion): Don't overflow matchcount.
 +      (file_name_completion_stat): Use SAFE_ALLOCA, not alloca.
 +      * dispextern.h: Adjust decls to match defn changes elsewhere.
 +      (struct text_pos, struct glyph, struct bidi_saved_info)
 +      (struct bidi_string_data, struct bidi_it, struct composition_it)
 +      (struct it):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (struct display_pos, struct composition_it, struct it):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * dispnew.c (increment_matrix_positions)
 +      (increment_row_positions, mode_line_string)
 +      (marginal_area_string):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (change_frame_size_1, Fredisplay, Fframe_or_buffer_changed_p):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (duration_to_sec_usec): New function, to check for overflow better.
 +      (Fsleep_for, sit_for): Use it.
 +      * doc.c (get_doc_string, store_function_docstring):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (get_doc_string, Fsnarf_documentation):
 +      Use int, not EMACS_INT, where int is wide enough.
 +      (get_doc_string):
 +      Use SAFE_ALLOCA, not alloca.
 +      Check for overflow when converting EMACS_INT to off_t.
 +      * doprnt.c (doprnt):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * editfns.c (init_editfns, Fuser_uid, Fuser_real_uid):
 +      Don't assume uid_t fits into fixnum.
 +      (buildmark, Fgoto_char, overlays_around, find_field, Fdelete_field)
 +      (Ffield_string, Ffield_string_no_properties, Ffield_beginning)
 +      (Ffield_end, Fconstrain_to_field, Fline_beginning_position)
 +      (Fline_end_position, Fprevious_char, Fchar_after, Fchar_before)
 +      (general_insert_function)
 +      (Finsert_char, make_buffer_string, make_buffer_string_both)
 +      (update_buffer_properties, Fbuffer_substring)
 +      (Fbuffer_substring_no_properties, Fcompare_buffer_substrings)
 +      (Fsubst_char_in_region, check_translation)
 +      (Ftranslate_region_internal, save_restriction_restore, Fformat)
 +      (transpose_markers, Ftranspose_regions):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (clip_to_bounds): Move to lisp.h as an inline function).
 +      (Fconstrain_to_field): Don't assume integers are nonnegative.
 +      (Fline_beginning_position, Fsave_excursion, Fsave_current_buffer):
 +      (Fsubst_char_in_region, Fsave_restriction):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Femacs_pid): Don't assume pid_t fits into fixnum.
 +      (lo_time): Use int, not EMACS_INT, when int suffices.
 +      (lisp_time_argument): Check for usec out of range.
 +      (Fencode_time): Don't assume fixnum fits in int.
 +      (Fuser_login_name, Fuser_full_name): Signal an error
 +      if a uid argument is out of range, rather than relying on
 +      undefined behavior.
 +      (Fformat_time_string): Remove now-unnecessary check.
 +      lisp_time_argument checks for out-of-range usec now.
 +      * emacs.c (gdb_valbits, gdb_gctypebits): Now int, not EMACS_INT.
 +      (gdb_data_seg_bits): Now uintptr_t, not EMACS_INT.
 +      (PVEC_FLAG, gdb_array_mark_flag): Now ptrdiff_t, not EMACS_INT.
 +      (init_cmdargs, Fdump_emacs):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fkill_emacs): Don't assume fixnum fits in int; instead, take just
 +      the bottom (typically) 32 bits of the fixnum.
 +      * eval.c (specpdl_size, call_debugger):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (when_entered_debugger, Fbacktrace_debug):
 +      Don't assume fixnum can fit in int.
 +      (Fdefvaralias, Fdefvar): Do not attempt to compute the address of
 +      the object just before a buffer; this is not portable.
 +      (FletX, Flet, Funwind_protect, do_autoload, Feval, funcall_lambda)
 +      (grow_specpdl, unbind_to):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fapply, apply_lambda): Don't assume ptrdiff_t can hold fixnum.
 +      (grow_specpdl): Simplify allocation by using xpalloc.
 +      (Fprog1, Fprog2): Don't assume list length fits in int.  Simplify.
 +      * fileio.c (Ffind_file_name_handler, Fcopy_file, Frename_file)
 +      (Finsert_file_contents, Fwrite_region, Fdo_auto_save):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Ffind_file_name_handler, non_regular_inserted, Finsert_file_contents)
 +      (a_write, e_write):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fcopy_file, non_regular_nbytes, read_non_regular)
 +      (Finsert_file_contents):
 +      Use int, not EMACS_INT, where int is wide enough.
 +      (READ_BUF_SIZE): Verify that it fits in int.
 +      (Finsert_file_contents): Check that counts are in proper range,
 +      rather than assuming fixnums fit into ptrdiff_t etc.
 +      Don't assume fixnums fit into int.
 +      * floatfns.c (Fexpt): Avoid undefined signed * signed overflow.
 +      * fns.c (Fcompare_strings, Fstring_lessp, struct textprop_rec, concat)
 +      (string_char_byte_cache_charpos, string_char_byte_cache_bytepos)
 +      (string_char_to_byte, string_byte_to_char)
 +      (string_make_multibyte, string_to_multibyte)
 +      (string_make_unibyte, Fstring_as_unibyte, Fstring_as_multibyte)
 +      (Fstring_to_unibyte, Fsubstring, Fsubstring_no_properties)
 +      (substring_both, Fdelete, internal_equal, Ffillarray)
 +      (Fclear_string, mapcar1)
 +      (Fbase64_encode_region, Fbase64_encode_string, base64_encode_1)
 +      (Fbase64_decode_region, Fbase64_decode_string, base64_decode_1)
 +      (larger_vector, make_hash_table, maybe_resize_hash_table)
 +      (hash_lookup, hash_remove_from_table, hash_clear, sweep_weak_table)
 +      (Fmaphash, secure_hash):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (concat): Check for string index and length overflow.
 +      (Fmapconcat): Don't assume fixnums fit into ptrdiff_t.
 +      (Frequire):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (larger_vector): New API (vec, incr_min, size_max) replaces old
 +      one (vec, new_size, init).  This catches size overflow.
 +      INIT was removed because it was always Qnil.
 +      All callers changed.
 +      (INDEX_SIZE_BOUND): New macro, which calculates more precisely
 +      the upper bound on a hash table index size.
 +      (make_hash_table, maybe_resize_hash_table): Use it.
 +      (secure_hash): Computer start_byte and end_byte only after
 +      they're known to be in ptrdiff_t range.
 +      * font.c (font_intern_prop, font_at, font_range, Ffont_shape_gstring)
 +      (Ffont_get_glyphs, Ffont_at):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (font_style_to_value, font_prop_validate_style, font_expand_wildcards)
 +      (Flist_fonts, Fopen_font):
 +      Don't assume fixnum can fit in int.
 +      (check_gstring): Don't assume index can fit in int.
 +      (font_match_p): Check that fixnum is a character, not a nonnegative
 +      fixnum, since the later code needs to stuff it into an int.
 +      (font_find_for_lface): Use SAFE_ALLOCA_LISP, not alloca.
 +      (font_fill_lglyph_metrics): Use unsigned, not EMACS_INT, to avoid
 +      conversion overflow issues.
 +      (Fopen_font): Check for integer out of  range.
 +      (Ffont_get_glyphs): Don't assume index can fit in int.
 +      * font.h: Adjust decls to match defn changes elsewhere.
 +      * fontset.c (reorder_font_vector): Redo score calculation to avoid
 +      integer overflow.
 +      (num_auto_fontsets, fontset_from_font): Use ptrdiff_t, not
 +      printmax_t, where ptrdiff_t is wide enough.
 +      (Finternal_char_font):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * frame.c (Fset_mouse_position, Fset_mouse_pixel_position)
 +      (Fset_frame_height, Fset_frame_width, Fset_frame_size)
 +      (Fset_frame_position, x_set_frame_parameters)
 +      (x_set_line_spacing, x_set_border_width)
 +      (x_set_internal_border_width, x_set_alpha, x_figure_window_size):
 +      Check that fixnums are in proper range for system types.
 +      (frame_name_fnn_p, Fframe_parameter, Fmodify_frame_parameters):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fmodify_frame_parameters): Don't assume fixnum fits in int.
 +      Use SAFE_ALLOCA_LISP, not alloca.
 +      * frame.h (struct frame): Use intptr_t, not EMACS_INT, where
 +      intptr_t is wide enough.
 +      * fringe.c (lookup_fringe_bitmap, get_logical_fringe_bitmap)
 +      (Fdefine_fringe_bitmap): Don't assume fixnum fits in int.
 +      (Ffringe_bitmaps_at_pos): Don't assume index fits in int.
 +      Check for fixnum out of range.
 +      * ftfont.c (ftfont_list): Don't assume index fits in int.
 +      Check that fixnums are in proper range for system types.
 +      (ftfont_shape_by_flt):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * gnutls.c (emacs_gnutls_write, emacs_gnutls_read):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fgnutls_error_fatalp, Fgnutls_error_string, Fgnutls_boot):
 +      Check that fixnums are in proper range for system types.
 +      * gnutls.h: Adjust decls to match defn changes elsewhere.
 +      * gtkutil.c (xg_dialog_run):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (update_frame_tool_bar):
 +      Check that fixnums are in proper range for system types.
 +      * image.c (parse_image_spec): Redo count calculation to avoid overflow.
 +      (lookup_image): Check that fixnums are in range for system types.
 +      * indent.c (last_known_column, last_known_column_point):
 +      (current_column_bol_cache):
 +      (skip_invisible, current_column, check_display_width):
 +      (check_display_width, scan_for_column, current_column_1)
 +      (Findent_to, Fcurrent_indentation, position_indentation)
 +      (indented_beyond_p, Fmove_to_column, compute_motion):
 +      (Fcompute_motion, Fvertical_motion):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (last_known_column_modified): Use EMACS_INT, not int.
 +      (check_display_width):
 +      (Fcompute_motion):
 +      Check that fixnums and floats are in proper range for system types.
 +      (compute_motion): Don't assume index or fixnum fits in int.
 +      (compute_motion, Fcompute_motion):
 +      Use int, not EMACS_INT, when it is wide enough.
 +      (vmotion): Omit local var start_hpos that is always 0; that way
 +      we don't need to worry about overflow in expressions involving it.
 +      * indent.h: Adjust decls to match defn changes elsewhere.
 +      (struct position):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      Use int, not EMACS_INT, where int is wide enough.
 +      Remove unused members ovstring_chars_done and tab_offset;
 +      all uses removed.
 +      * insdel.c (move_gap, move_gap_both, gap_left, gap_right)
 +      (adjust_markers_for_delete, adjust_markers_for_insert, adjust_point)
 +      (adjust_markers_for_replace, make_gap_larger, make_gap_smaller)
 +      (make_gap, copy_text, insert, insert_and_inherit)
 +      (insert_before_markers, insert_before_markers_and_inherit)
 +      (insert_1, count_combining_before, count_combining_after)
 +      (insert_1_both, insert_from_string)
 +      (insert_from_string_before_markers, insert_from_string_1)
 +      (insert_from_gap, insert_from_buffer, insert_from_buffer_1)
 +      (adjust_after_replace, adjust_after_insert, replace_range)
 +      (replace_range_2, del_range, del_range_1, del_range_byte)
 +      (del_range_both, del_range_2, modify_region)
 +      (prepare_to_modify_buffer, signal_before_change)
 +      (signal_after_change, Fcombine_after_change_execute):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * intervals.c (traverse_intervals, rotate_right, rotate_left)
 +      (balance_an_interval, split_interval_right, split_interval_left)
 +      (find_interval, next_interval, update_interval)
 +      (adjust_intervals_for_insertion, delete_node, delete_interval)
 +      (interval_deletion_adjustment, adjust_intervals_for_deletion)
 +      (static_offset_intervals, offset_intervals)
 +      (merge_interval_right, merge_interval_left, make_new_interval)
 +      (graft_intervals_into_buffer, temp_set_point_both)
 +      (temp_set_point, set_point, adjust_for_invis_intang)
 +      (set_point_both, move_if_not_intangible, get_property_and_range)
 +      (get_local_map, copy_intervals, copy_intervals_to_string)
 +      (compare_string_intervals, set_intervals_multibyte_1):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * intervals.h: Adjust decls to match defn changes elsewhere.
 +      (struct interval):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * keyboard.c (this_command_key_count, this_single_command_key_start)
 +      (before_command_key_count, before_command_echo_length, echo_now)
 +      (echo_length, recursive_edit_1, Frecursive_edit, Ftrack_mouse)
 +      (command_loop_1, safe_run_hooks, read_char, timer_check_2)
 +      (menu_item_eval_property, read_key_sequence, Fread_key_sequence)
 +      (Fread_key_sequence_vector, Fexecute_extended_command, Fsuspend_emacs):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (last_non_minibuf_size, last_point_position, echo_truncate)
 +      (command_loop_1, adjust_point_for_property, read_char, gen_help_event)
 +      (make_lispy_position, make_lispy_event, parse_modifiers_uncached)
 +      (parse_modifiers, modify_event_symbol, Fexecute_extended_command)
 +      (stuff_buffered_input):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (last_auto_save, command_loop_1, read_char):
 +      Use EMACS_INT, not int, to avoid integer overflow.
 +      (record_char): Avoid overflow in total_keys computation.
 +      (parse_modifiers_uncached): Redo index calculation to avoid overflow.
 +      * keyboard.h: Adjust decls to match defn changes elsewhere.
 +      * keymap.c (Fdefine_key, Fcurrent_active_maps, accessible_keymaps_1)
 +      (Fkey_description, Fdescribe_vector, Flookup_key):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (click_position): New function, to check that positions are in range.
 +      (Fcurrent_active_maps):
 +      (describe_command):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Faccessible_keymaps, Fkey_description):
 +      (preferred_sequence_p):
 +      Don't assume fixnum can fit into int.
 +      (Fkey_description): Use SAFE_ALLOCA_LISP, not alloca.
 +      Check for integer overflow in size calculations.
 +      (Ftext_char_description): Use CHECK_CHARACTER, not CHECK_NUMBER, to
 +      avoid mishandling large integers.
 +      * lisp.h: Adjust decls to match defn changes elsewhere.
 +      (ARRAY_MARK_FLAG, PSEUDOVECTOR_FLAG, struct Lisp_String)
 +      (struct vectorlike_header, struct Lisp_Subr, struct Lisp_Hash_Table)
 +      (struct Lisp_Marker):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (clip_to_bounds): Now an inline function, moved here from editfns.c.
 +      (GLYPH_CODE_P): Check for overflow in system types, subsuming the
 +      need for GLYPH_CODE_CHAR_VALID_P and doing proper checking ourselves.
 +      All callers changed.
 +      (GLYPH_CODE_CHAR, GLYPH_CODE_FACE):
 +      Assume the arg has valid form, since it always does.
 +      (TYPE_RANGED_INTEGERP): Avoid bug when checking against a wide
 +      unsigned integer system type.
 +      (CHECK_RANGED_INTEGER, CHECK_TYPE_RANGED_INTEGER): New macros.
 +      (struct catchtag, specpdl_size, SPECPDL_INDEX, USE_SAFE_ALLOCA):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (struct catchtag): Use EMACS_INT, not int, since it may be a fixnum.
 +      (duration_to_sec_usec): New decl.
 +      * lread.c (read_from_string_index, read_from_string_index_byte)
 +      (read_from_string_limit, readchar, unreadchar, openp)
 +      (read_internal_start, read1, oblookup):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fload, readevalloop, Feval_buffer, Feval_region):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (openp): Check for out-of-range argument to 'access'.
 +      (read1): Use int, not EMACS_INT, where int is wide enough.
 +      Don't assume fixnum fits into int.
 +      Fix off-by-one error that can read outside a buffer.
 +      (read_filtered_event): Use duration_to_sec_usec
 +      to do proper overflow checking on durations.
 +      * macros.c (Fstart_kbd_macro): Use xpalloc to check for overflow
 +      in size calculation.
 +      (Fexecute_kbd_macro):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * marker.c (cached_charpos, cached_bytepos, CONSIDER)
 +      (byte_char_debug_check, buf_charpos_to_bytepos, verify_bytepos)
 +      (buf_bytepos_to_charpos, Fset_marker, set_marker_restricted)
 +      (set_marker_both, set_marker_restricted_both, marker_position)
 +      (marker_byte_position, Fbuffer_has_markers_at):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fset_marker, set_marker_restricted): Don't assume fixnum fits in int.
 +      * menu.c (ensure_menu_items): Renamed from grow_menu_items.
 +      It now merely ensures that the menu is large enough, without
 +      necessarily growing it, as this avoids some integer overflow issues.
 +      All callers changed.
 +      (keymap_panes, parse_single_submenu, Fx_popup_menu):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (parse_single_submenu, Fx_popup_menu): Don't assume fixnum fits in int.
 +      Use SAFE_ALLOCA_LISP, not alloca.
 +      (find_and_return_menu_selection): Avoid unnecessary casts of pointers
 +      to EMACS_INT.  Check that fixnums are in proper range for system types.
 +      * minibuf.c (minibuf_prompt_width, string_to_object)
 +      (Fminibuffer_contents, Fminibuffer_contents_no_properties)
 +      (Fminibuffer_completion_contents, Ftry_completion, Fall_completions):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (get_minibuffer, read_minibuf_unwind):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (read_minibuf): Omit unnecessary arg BACKUP_N, which is always nil;
 +      this simplifies overflow checking.  All callers changed.
 +      (read_minibuf, Fread_buffer, Ftry_completion, Fall_completions)
 +      (Ftest_completion):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * nsfns.m (check_ns_display_info): Don't assume fixnum fits in long.
 +      (x_set_menu_bar_lines, x_set_tool_bar_lines, Fx_create_frame):
 +      Check that fixnums are in proper range for system types.
 +      (Fx_create_frame, Fx_show_tip):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * nsfont.m (ns_findfonts, nsfont_list_family):
 +      Don't assume fixnum fits in long.
 +      * nsmenu.m (ns_update_menubar, ns_menu_show, ns_popup_dialog):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (ns_update_menubar): Use intptr_t, not EMACS_INT, when intptr_t is
 +      wide enough.
 +      * nsselect.m (ns_get_local_selection, clean_local_selection_data):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * print.c (print_buffer_size, print_buffer_pos, print_buffer_pos_byte)
 +      (PRINTDECLARE, PRINTPREPARE):
 +      (strout, print_string):
 +      (print, print_preprocess, print_check_string_charset_prop)
 +      (print_object):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (PRINTDECLARE):
 +      (temp_output_buffer_setup, Fprin1_to_string, print_object):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (PRINTPREPARE): Use int, not ptrdiff_t, where int is wide enough.
 +      (printchar, strout): Use xpalloc to catch size calculation overflow.
 +      (Fexternal_debugging_output): Don't overflow EMACS_INT->int conversion.
 +      (print_error_message): Use SAFE_ALLOCA, not alloca.
 +      (print_object): Use int, not EMACS_INT, where int is wide enough.
 +      (print_depth, new_backquote_output, print_number_index):
 +      Use ptrdiff_t, not int, where int might not be wide enough.
 +      * process.c (Fdelete_process): Don't assume pid fits into EMACS_INT.
 +      (Fset_process_window_size, Fformat_network_address)
 +      (get_lisp_to_sockaddr_size, set_socket_option, Fmake_network_process)
 +      (sigchld_handler):
 +      Check that fixnums are in proper range for system types.
 +      (Fsignal_process): Simplify by avoiding a goto.
 +      Check for process-ids out of pid_t range rather than relying on
 +      undefined behavior.
 +      (process_tick, update_tick): Use EMACS_INT, not int.
 +      (Fformat_network_address, read_process_output, send_process)
 +      (Fprocess_send_region, status_notify):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fformat_network_address, Fmake_serial_process, Fmake_network_process)
 +      (wait_reading_process_output, read_process_output, exec_sentinel):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (conv_lisp_to_sockaddr): Don't assume fixnums fit into int.
 +      (Faccept_process_output): Use duration_to_sec_usec to do proper
 +      overflow checking on durations.
 +      (emacs_get_tty_pgrp, Fprocess_running_child_p, process_send_signal):
 +      Don't assume pid_t fits in int.
 +      * puresize.h (PURESIZE_RATIO): Shrink this to 8/6 on 32-bit hosts
 +      configured --with-wide-int.
 +      * scroll.c (calculate_scrolling, calculate_direct_scrolling)
 +      (line_ins_del): Use int, not EMACS_INT, where int is wide enough.
 +      * search.c (looking_at_1, string_match_1):
 +      (fast_string_match, fast_c_string_match_ignore_case)
 +      (fast_string_match_ignore_case, fast_looking_at, scan_buffer)
 +      (scan_newline, find_before_next_newline, search_command)
 +      (trivial_regexp_p, search_buffer, simple_search, boyer_moore)
 +      (set_search_regs, wordify):
 +      (Freplace_match):
 +      (Fmatch_data):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (string_match_1, search_buffer, set_search_regs):
 +      (Fmatch_data):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (wordify): Check for overflow in size calculation.
 +      (Freplace_match): Avoid potential buffer overflow in search_regs.start.
 +      (Fset_match_data): Don't assume fixnum fits in ptrdiff_t.
 +      Check that fixnums are in proper range for system types.
 +      * sound.c (struct sound_device)
 +      (wav_play, au_play, vox_write, alsa_period_size, alsa_write):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fplay_sound_internal):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * syntax.c (struct lisp_parse_state, find_start_modiff)
 +      (Finternal_describe_syntax_value, scan_lists, scan_sexps_forward):
 +      (Fparse_partial_sexp):
 +      Don't assume fixnums can fit in int.
 +      (struct lisp_parse_state, find_start_pos, find_start_value)
 +      (find_start_value_byte, find_start_begv)
 +      (update_syntax_table, char_quoted, dec_bytepos)
 +      (find_defun_start, prev_char_comend_first, back_comment):
 +      (scan_words, skip_chars, skip_syntaxes, forw_comment, Fforward_comment)
 +      (scan_lists, Fbackward_prefix_chars, scan_sexps_forward):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Finternal_describe_syntax_value): Check that match_lisp is a
 +      character, not an integer, since the code stuffs it into int.
 +      (scan_words, scan_sexps_forward):
 +      Check that fixnums are in proper range for system types.
 +      (Fforward_word):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (scan_sexps_forward):
 +      Use CHARACTERP, not INTEGERP, since the value must fit into int.
 +      (Fparse_partial_sexp): Fix doc; element 8 is not ignored.
 +      * syntax.h: Adjust decls to match defn changes elsewhere.
 +      (struct gl_state_s):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (SETUP_SYNTAX_TABLE_FOR_OBJECT): Use PTRDIFF_MAX, not
 +      MOST_POSITIVE_FIXNUM.
 +      * sysdep.c (wait_for_termination_1, wait_for_termination)
 +      (interruptible_wait_for_termination, mkdir):
 +      Don't assume pid_t fits in int; on 64-bit AIX pid_t is 64-bit.
 +      (emacs_read, emacs_write):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (system_process_attributes): Don't assume uid_t, gid_t, EMACS_INT,
 +      and double all fit in int.
 +      * term.c (set_tty_color_mode):
 +      Check that fixnums are in proper range for system types.
 +      * termhooks.h (struct input_event):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * textprop.c (validate_interval_range, interval_of)
 +      (Fadd_text_properties, set_text_properties_1)
 +      (Fremove_text_properties, Fremove_list_of_text_properties)
 +      (Ftext_property_any, Ftext_property_not_all)
 +      (copy_text_properties, text_property_list, extend_property_ranges)
 +      (verify_interval_modification):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fnext_single_char_property_change)
 +      (Fprevious_single_char_property_change):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (copy_text_properties):
 +      Check for integer overflow in index calculation.
 +      * undo.c (last_boundary_position, record_point, record_insert)
 +      (record_delete, record_marker_adjustment, record_change)
 +      (record_property_change):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (truncate_undo_list, Fprimitive_undo): Don't assume fixnum fits in int.
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * w32fns.c (Fx_create_frame, x_create_tip_frame, Fx_show_tip)
 +      (Fx_hide_tip, Fx_file_dialog):
 +      * w32menu.c (set_frame_menubar):
 +      Use ptrdiff_t, not int, for consistency with rest of code.
 +      * window.c (window_scroll_preserve_hpos, window_scroll_preserve_vpos)
 +      (select_window, Fdelete_other_windows_internal)
 +      (window_scroll_pixel_based, window_scroll_line_based)
 +      (Frecenter, Fset_window_configuration):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (Fset_window_hscroll, run_window_configuration_change_hook)
 +      (set_window_buffer, temp_output_buffer_show, scroll_command)
 +      (Fscroll_other_window, Frecenter):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fwindow_line_height, window_scroll, Fscroll_left, Fscroll_right):
 +      Don't assume fixnum fits in int.
 +      (Fset_window_scroll_bars):
 +      Check that fixnums are in proper range for system types.
 +      * xdisp.c (help_echo_pos, pos_visible_p, string_pos_nchars_ahead)
 +      (string_pos, c_string_pos, number_of_chars, init_iterator)
 +      (in_ellipses_for_invisible_text_p, init_from_display_pos)
 +      (compute_stop_pos, next_overlay_change, compute_display_string_pos)
 +      (compute_display_string_end, handle_face_prop)
 +      (face_before_or_after_it_pos, handle_invisible_prop)
 +      (handle_display_prop, handle_display_spec, handle_single_display_spec)
 +      (display_prop_intangible_p, string_buffer_position_lim)
 +      (string_buffer_position, handle_composition_prop, load_overlay_strings)
 +      (get_overlay_strings_1, get_overlay_strings)
 +      (iterate_out_of_display_property, forward_to_next_line_start)
 +      (back_to_previous_visible_line_start, reseat, reseat_to_string)
 +      (get_next_display_element, set_iterator_to_next)
 +      (get_visually_first_element, compute_stop_pos_backwards)
 +      (handle_stop_backwards, next_element_from_buffer)
 +      (move_it_in_display_line_to, move_it_in_display_line)
 +      (move_it_to, move_it_vertically_backward, move_it_by_lines)
 +      (add_to_log, message_dolog, message_log_check_duplicate)
 +      (message2, message2_nolog, message3, message3_nolog
 +      (with_echo_area_buffer, display_echo_area_1, resize_mini_window_1)
 +      (current_message_1, truncate_echo_area, truncate_message_1)
 +      (set_message, set_message_1, store_mode_line_noprop)
 +      (hscroll_window_tree, debug_delta, debug_delta_bytes, debug_end_vpos)
 +      (text_outside_line_unchanged_p, check_point_in_composition)
 +      (reconsider_clip_changes)
 +      (redisplay_internal, set_cursor_from_row, try_scrolling)
 +      (try_cursor_movement, set_vertical_scroll_bar, redisplay_window)
 +      (redisplay_window, find_last_unchanged_at_beg_row)
 +      (find_first_unchanged_at_end_row, row_containing_pos, try_window_id)
 +      (trailing_whitespace_p, find_row_edges, display_line)
 +      (RECORD_MAX_MIN_POS, Fcurrent_bidi_paragraph_direction)
 +      (display_mode_element, store_mode_line_string)
 +      (pint2str, pint2hrstr, decode_mode_spec)
 +      (display_count_lines, display_string, draw_glyphs)
 +      (x_produce_glyphs, x_insert_glyphs)
 +      (rows_from_pos_range, mouse_face_from_buffer_pos)
 +      (fast_find_string_pos, mouse_face_from_string_pos)
 +      (note_mode_line_or_margin_highlight, note_mouse_highlight):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (safe_call, init_from_display_pos, handle_fontified_prop)
 +      (handle_single_display_spec, load_overlay_strings)
 +      (with_echo_area_buffer, setup_echo_area_for_printing)
 +      (display_echo_area, echo_area_display)
 +      (x_consider_frame_title, prepare_menu_bars, update_menu_bar)
 +      (update_tool_bar, hscroll_window_tree, redisplay_internal)
 +      (redisplay_window, dump_glyph_row, display_mode_line)
 +      (Fformat_mode_line, decode_mode_spec, on_hot_spot_p):
 +      (handle_display_spec, display_prop_string_p):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (handle_single_display_spec, build_desired_tool_bar_string)
 +      (redisplay_tool_bar, scroll_window_tree, Fdump_glyph_matrix)
 +      (get_specified_cursor_type):
 +      Check that fixnums are in proper range for system types.
 +      (struct overlay_entry, resize_mini_window, Fdump_glyph_row)
 +      (Flookup_image_map):
 +      Don't assume fixnums fit in int.
 +      (compare_overlay_entries):
 +      Avoid mishandling comparisons due to subtraction overflow.
 +      (load_overlay_strings): Use SAFE_NALLOCA, not alloca.
 +      (last_escape_glyph_face_id, last_glyphless_glyph_face_id):
 +      (handle_tool_bar_click):
 +      Use int, not unsigned, since we prefer signed and the signedness
 +      doesn't matter here.
 +      (get_next_display_element, next_element_from_display_vector):
 +      Use int, not EMACS_INT, when int is wide enough.
 +      (start_hourglass): Use duration_to_sec_usec to do proper
 +      overflow checking on durations.
 +      * xfaces.c (Fbitmap_spec_p):
 +      Check that fixnums are in proper range for system types.
 +      (compare_fonts_by_sort_order):
 +      Avoid mishandling comparisons due to subtraction overflow.
 +      (Fx_family_fonts, realize_basic_faces):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fx_family_fonts):
 +      Don't assume fixnum fits in int.
 +      Use SAFE_ALLOCA_LISP, not alloca.
 +      (merge_face_heights): Remove unnecessary cast to EMACS_INT.
 +      (Finternal_make_lisp_face): Don't allocate more than MAX_FACE_ID.
 +      (face_at_buffer_position, face_for_overlay_string)
 +      (face_at_string_position):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      (merge_faces): Use int, not EMACS_INT, where int is wide enough.
 +      * xfns.c (x_set_menu_bar_lines, x_set_tool_bar_lines, x_icon_verify)
 +      (Fx_show_tip):
 +      Check that fixnums are in proper range for system types.
 +      (Fx_create_frame, x_create_tip_frame, Fx_show_tip)
 +      (Fx_hide_tip, Fx_file_dialog, Fx_select_font):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (Fx_change_window_property): Don't assume fixnums fit in int.
 +      * xfont.c (xfont_chars_supported):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * xmenu.c (Fx_popup_dialog, set_frame_menubar)
 +      (create_and_show_popup_menu, create_and_show_dialog, xmenu_show):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * xml.c (parse_region):
 +      * xrdb.c (magic_file_p):
 +      Use ptrdiff_t, not EMACS_INT, where ptrdiff_t is wide enough.
 +      * xselect.c (TRACE1): Don't assume pid_t promotes to int.
 +      (x_get_local_selection, x_reply_selection_request)
 +      (x_handle_selection_request, wait_for_property_change):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      (selection_data_to_lisp_data): Use short, not EMACS_INT, where
 +      short is wide enough.
 +      (x_send_client_event): Don't assume fixnum fits in int.
 +      * xterm.c (x_x_to_emacs_modifiers):
 +      Don't assume EMACS_INT overflows nicely into int.
 +      (x_emacs_to_x_modifiers): Use EMACS_INT, not int, because values
 +      may come from Lisp.
 +      (handle_one_xevent): NATNUMP can eval its arg twice.
 +      (x_connection_closed):
 +      Use ptrdiff_t, not int, to avoid needless 32-bit limit on 64-bit hosts.
 +      * xterm.h: Adjust decls to match defn changes elsewhere.
 +      (struct scroll_bar): Use struct vectorlike_header
 +      rather than rolling our own approximation.
 +      (SCROLL_BAR_VEC_SIZE): Remove; not used.
 +
+ 2012-05-25  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * fileio.c, character.h: Minor style tweaks.
+ 2012-05-24  Dmitry Antipov  <dmantipov@yandex.ru>
+       * window.h (clip_changed): Remove useless declaration.
+ 2012-05-22  Juanma Barranquero  <lekktu@gmail.com>
+       * makefile.w32-in: Follow-up to 2012-05-22T16:20:27Z!eggert@cs.ucla.edu.
+       (TAGS, TAGS-gmake, CONFIG_H): Remove further references to m/intel386.h.
+ 2012-05-22  Paul Eggert  <eggert@cs.ucla.edu>
+       Remove src/m/*.
+       This directory predates autoconf and is no longer needed nowadays.
+       Move its few remaining bits of functionality to where they're needed.
+       * m/README, m/alpha.h, m/amdx86-64.h, m/ia64.h, m/ibmrs6000.h:
+       * m/ibms390x.h, m/intel386.h, m/m68k.h, m/macppc.h, m/sparc.h:
+       * m/template.h: Remove.
+       * Makefile.in (M_FILE): Remove.  All uses removed.
+       * alloc.c (POINTERS_MIGHT_HIDE_IN_OBJECTS):
+       * lisp.h (USE_LSB_TAG):
+       * mem-limits.h (EXCEEDS_LISP_PTR):
+       Use VAL_MAX, not VALBITS, in #if.
+       * lisp.h (EMACS_INT_MAX): New macro, useful in #if.
+       (EMACS_UINT): Define unconditionally now.
+       (BITS_PER_CHAR, BITS_PER_SHORT, BITS_PER_INT, BITS_PER_LONG)
+       (BITS_PER_EMACS_INT): New constants, replacing
+       what used to be in config.h, but not useful in #if.
+       (GCTYPEBITS, VALBITS): Define unconditionally, since m/* files don't
+       define them any more.
+       (VAL_MAX): New macro.
+       (VALMASK): Use it.
+       * puresize.h (PURESIZE_RATIO): Use EMACS_INT_MAX, not
+       BITS_PER_EMACS_INT, in #if.
+       * s/aix4-2.h (BROKEN_FIONREAD, BROKEN_SIGAIO, BROKEN_SIGPTY)
+       (BROKEN_SIGPOLL): Move here from m/ibmrs6000.h, which was removed.
+       * s/gnu-linux.h (ULIMIT_BREAK_VALUE) [__i386__]:
+       * s/ms-w32.h (DATA_START):
+       Move here from removed file m/intel386.h.
+       * s/gnu.h (NLIST_STRUCT): Remove undef; 'configure' does this.
+       * s/irix6-5.h (_LP64): Remove; lisp.h no longer needs this.
+ 2012-05-21  Paul Eggert  <eggert@cs.ucla.edu>
+       Assume C89 or later.
+       * alloc.c, buffer.c, lisp.h: Replace POINTER_TYPE with void.
+       * alloc.c (overrun_check_malloc, overrun_check_realloc, xmalloc)
+       (xrealloc):
+       * buffer.c (mmap_free_1, mmap_enlarge): Omit needless casts.
+       * editfns.c, fns.c, gmalloc.c, insdel.c, sysdep.c, termcap.c (NULL):
+       * textprop.c, tparam.c (NULL): Remove.
+       * ralloc.c, vm-limit.c (POINTER): Assume void * works.
+       * regex.c (SIGN_EXTEND_CHAR): Assume signed char works.
+       * regex.h (_RE_ARGS): Remove.  All uses rewritten to use prototypes.
+       * unexelf.c (ElfBitsW): Assume c89 preprocessor or better.
+       * xterm.c (input_signal_count): Assume volatile works.
+ 2012-05-21  Ken Brown  <kbrown@cornell.edu>
+       * xgselect.c (xg_select): Fix first argument in call to 'select'
+       (bug#11508).
+ 2012-05-20  Ken Brown  <kbrown@cornell.edu>
+       * gmalloc.c (_free_internal_nolock, _realloc_internal_nolock)
+       [CYGWIN]: Cast ptr to (char *) before comparing to _heapbase.
+ 2012-05-19  Ken Brown  <kbrown@cornell.edu>
+       * xfns.c (x_in_use): Remove `static' qualifier.
+       * xterm.h (x_in_use): Declare.
+       * xgselect.c: Include xterm.h.
+       (xg_select): Test `x_in_use' instead of `inhibit_window_system'
+       and `display_arg' (bug#9754).
+ 2012-05-19  Paul Eggert  <eggert@cs.ucla.edu>
+       * s/ms-w32.h (HAVE_GETDOMAINNAME): Remove; not needed.
+       * m/vax.h: Remove; no longer needed since HAVE_FTIME is being removed.
+       * s/ms-w32.h (HAVE_FTIME): Remove; not needed.
+ 2012-05-18  Eli Zaretskii  <eliz@gnu.org>
+       Fix compilation with -DGLYPH_DEBUG=1 on MS-Windows.
+       * w32term.c [GLYPH_DEBUG]: Add prototype for x_check_font.
+       (x_check_font) [GLYPH_DEBUG]: New function, copied from xterm.c
+       * w32fns.c (unwind_create_frame) [GLYPH_DEBUG]: Fix broken
+       reference to image_cache->refcount.
+       (x_create_tip_frame): Fix broken use of FRAME_IMAGE_CACHE.
+ 2012-05-17  Juri Linkov  <juri@jurta.org>
+       * search.c (Fword_search_regexp, Fword_search_backward)
+       (Fword_search_forward, Fword_search_backward_lax)
+       (Fword_search_forward_lax): Move functions to isearch.el
+       (bug#10145, bug#11381).
+ 2012-05-16  Paul Eggert  <eggert@cs.ucla.edu>
+       * xgselect.c (xg_select): Just invoke 'select' if -nw (Bug#9754).
+ 2012-05-15  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * lread.c (init_obarray): Declare Qt and Qnil as special.
+ 2012-05-14  Glenn Morris  <rgm@gnu.org>
+       * nsterm.m (ns_init_paths): Fix typo ("libexec" not "lib-exec").
+       Put "libexec" before "bin", for the sake of init_callproc_1.
+ 2012-05-14  Paul Eggert  <eggert@cs.ucla.edu>
+       * keyboard.c (kbd_buffer_get_event) [!HAVE_DBUS]: Omit unused local.
+       * unexaix.c: Port to more-recent AIX compilers.
+       (report_error, report_error_1, make_hdr, copy_sym)
+       (mark_x, adjust_lnnoptrs, unrelocate_symbols):
+       Make arguments const char *, not char *, to avoid violations of C
+       standard and to fix some AIX warnings reported by Gilles Pion.
+ 2012-05-14  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (handle_stop): Don't call get_overlay_strings_1 if we
+       already have overlays loaded.
+       (handle_single_display_spec): Before returning without displaying
+       fringe bitmap, synchronize the bidi iterator with the main display
+       iterator, by calling iterate_out_of_display_property.
+       (iterate_out_of_display_property): Detect buffer iteration by
+       testing that it->string is a Lisp string.
+       (get_next_display_element): When the current object is exhausted,
+       and there's something on it->stack, call set_iterator_to_next to
+       proceed with what's on the stack, instead of returning zero.
+       (set_iterator_to_next): If called at the end of a Lisp string,
+       proceed to consider_string_end without incrementing string
+       position.  Don't increment display vector index past the end of
+       the display vector.  (Bug#11417)
+       (pos_visible_p): Don't report a position visible when move_it_to
+       stopped at the last line of window, which happens to be scanned
+       backwards by the bidi iteration.  (Bug#11464)
+ 2012-05-14  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (handle_single_display_spec): Return 1 for left-margin
+       and right-margin display specs even if the spec is invalid or we
+       are on a TTY, and thus unable to display on the fringes.  That's
+       because the text with the property will not be displayed anyway,
+       so we need to signal to the caller that this is a "replacing"
+       display spec.  This fixes display when the spec is invalid or we
+       are on a TTY.
+ 2012-05-14  Paul Eggert  <eggert@cs.ucla.edu>
+       * unexaix.c (make_hdr): Fix typo in prototype.
+       This bug broke the build on AIX.  Problem reported by Gilles Pion.
+ 2012-05-14  Michael Albinus  <michael.albinus@gmx.de>
+       * keyboard.c (kbd_buffer_get_event): Read special events also in
+       batch mode.  (Bug#11415)
+ 2012-05-12  Glenn Morris  <rgm@gnu.org>
+       * ns.mk: Update for ns_appbindir no longer having trailing "/".
+ 2012-05-12  Eli Zaretskii  <eliz@gnu.org>
+       * lisp.mk (lisp): Add newcomment.elc.
+ 2012-05-12  Glenn Morris  <rgm@gnu.org>
+       * Makefile.in (MKDIR_P): New, set by configure.
+       * ns.mk (${ns_appdir}, ${ns_appbindir}Emacs): Use $MKDIR_P.
+ 2012-05-11  Paul Eggert  <eggert@cs.ucla.edu>
+       Remove unused function hourglass_started.
+       * dispextern.h (hourglass_started):
+       * w32fns.c (hourglass_started):
+       * xdisp.c (hourglass_started): Remove.
+ 2012-05-10  Juanma Barranquero  <lekktu@gmail.com>
+       * makefile.w32-in ($(BLD)/gmalloc.$(O), $(BLD)/w32menu.$(O)):
+       Update dependencies.
+ 2012-05-10  Paul Eggert  <eggert@cs.ucla.edu>
+       * xgselect.c (xg_select): Put maxfds+1 into a var.
+       This is slightly clearer, and pacifies Ubuntu 12.04 gcc.
+       * sound.c (DEFAULT_ALSA_SOUND_DEVICE): Define only if HAVE_ALSA.
+ 2012-05-10  Dave Abrahams  <dave@boostpro.com>
+       * filelock.c (syms_of_filelock): New boolean create-lockfiles.
+       (lock_file): If create_lockfiles is 0, do nothing.  (Bug#11227)
+ 2012-05-09  Michael Albinus  <michael.albinus@gmx.de>
+       * dbusbind.c (xd_registered_buses): New internal Lisp object.
+       Rename all occurences of Vdbus_registered_buses to xd_registered_buses.
+       (syms_of_dbusbind): Remove declaration of Vdbus_registered_buses.
+       Initialize xd_registered_buses.
+ 2012-05-09  Paul Eggert  <eggert@cs.ucla.edu>
+       Untag more efficiently if USE_LSB_TAG.
+       This is based on a proposal by YAMAMOTO Mitsuharu in
+       <http://lists.gnu.org/archive/html/emacs-devel/2008-01/msg01876.html>.
+       For an admittedly artificial (nth 8000 longlist) benchmark on
+       Fedora 15 x86-64, this yields a 25% CPU speedup.  Also, it shrinks
+       Emacs's overall text size by 1%.
+       * lisp.h (XUNTAG): New macro.
+       (XCONS, XVECTOR, XSTRING, XSYMBOL, XFLOAT, XMISC, XPROCESS, XWINDOW)
+       (XTERMINAL, XSUBR, XBUFFER, XCHAR_TABLE, XSUB_CHAR_TABLE, XBOOL_VECTOR)
+       (XSETTYPED_PSEUDOVECTOR, XHASH_TABLE, TYPED_PSEUDOVECTORP): Use it.
+       * eval.c (Fautoload):
+       * font.h (XFONT_SPEC, XFONT_ENTITY, XFONT_OBJECT):
+       * frame.h (XFRAME): Use XUNTAG.
+       Port recent dbusbind.c changes to 32-bit --with-wide-int.
+       * dbusbind.c (xd_append_arg, xd_retrieve_arg, Fdbus_message_internal):
+       Remove unportable assumptions about print widths of types like
+       dbus_uint32_t.
+       (xd_get_connection_address, Fdbus_init_bus): Cast Emacs integer to
+       intptr_t when converting between pointer and integer, to avoid GCC
+       warnings about wrong width.
+ 2012-05-09  Eli Zaretskii  <eliz@gnu.org>
+       * w32proc.c (new_child): Force Windows to reserve only 64KB of
+       stack for each reader_thread, instead of defaulting to 8MB
+       determined by the linker.  This avoids failures in creating
+       subprocesses on Windows 7, see the discussion in this thread:
+       http://lists.gnu.org/archive/html/emacs-devel/2012-03/msg00119.html.
+ 2012-05-07  Jérémy Compostella  <jeremy.compostella@gmail.com>
+       Fix up display of the *Minibuf-0* buffer in the mini window.
+       * keyboard.c (read_char): Don't clear the echo area if there's no
+       message to clear.
+       * xdisp.c (redisplay_internal): Redisplay the mini window (with the
+       contents of *Minibuf-0*) if there's no message displayed in its stead.
+ 2012-05-07  Michael Albinus  <michael.albinus@gmx.de>
+       * dbusbind.c (XD_DEBUG_MESSAGE): Don't print message twice in
+       batch mode.
+ 2012-05-06  Chong Yidong  <cyd@gnu.org>
+       * lisp.mk (lisp): Update.
+ 2012-05-05  Jim Meyering  <meyering@redhat.com>
+       * w32font.c (fill_in_logfont): NUL-terminate a string (Bug#11372).
+ 2012-05-04  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * data.c (PUT_ERROR): New macro.
+       (syms_of_data): Use it.  Add new error type `user-error'.
+       * undo.c (user_error): New function.
+       (Fprimitive_undo): Use it.
+       * print.c (print_error_message): Adjust print style for `user-error'.
+       * keyboard.c (user_error): New function.
+       (Fexit_recursive_edit, Fabort_recursive_edit): Use it.
+ 2012-05-03  Paul Eggert  <eggert@cs.ucla.edu>
+       Do not limit current-time-string to years 1000..9999.
+       * editfns.c (TM_YEAR_IN_ASCTIME_RANGE): Remove.
+       (Fcurrent_time_string): Support any year that is supported by the
+       underlying localtime representation.  Don't use asctime, as it
+       has undefined behavior for years outside the range -999..9999.
+ 2012-05-02  Paul Eggert  <eggert@cs.ucla.edu>
+       Fix race conditions involving setenv, gmtime, localtime, asctime.
+       Without this fix, interrupts could mess up code that uses these
+       nonreentrant functions, since setting TZ invalidates existing
+       tm_zone or tzname values, and since most of these functions return
+       pointers to static storage.
+       * editfns.c (format_time_string, Fdecode_time, Fencode_time)
+       (Fcurrent_time_string, Fcurrent_time_zone, Fset_time_zone_rule):
+       Grow the critical sections to include not just invoking
+       localtime/gmtime, but also accessing these functions' results
+       including their tm_zone values if any, and any related TZ setting.
+       (format_time_string): Last arg is now struct tm *, not struct tm **,
+       so that the struct tm is saved in the critical section.
+       All callers changed.  Simplify allocation of initial buffer, partly
+       motivated by the fact that memory allocation needs to be outside
+       the critical section.
+ 2012-05-02  Dmitry Antipov  <dmantipov@yandex.ru>
+       * intervals.c (adjust_intervals_for_insertion): Initialize `newi'
+       with RESET_INTERVAL.
+       * buffer.c (Fget_buffer_create, Fmake_indirect_buffer):
+       Remove duplicated buffer name initialization.
+ 2012-05-02  Jim Meyering  <jim@meyering.net>
+       * xterm.c (x_term_init): Use memcpy instead of strncpy (Bug#11373).
+       * xfns.c (x_window): Use xstrdup (Bug#11375).
+ 2012-05-02  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (pos_visible_p): If already at a newline from the
+       display string before the 'while' loop, don't walk back the glyphs
+       from it3.glyph_row.  Solves assertion violation when the display
+       string begins with a newline (egg.el).  (Bug#11367)
+ 2012-05-01  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * keyboard.c (Fexecute_extended_command, Vsuggest_key_bindings):
+       Move to simple.el.
+ 2012-05-01  Glenn Morris  <rgm@gnu.org>
+       * syssignal.h: Remove reference to BROKEN_SIGINFO (last used in
+       s/ptx4.h), BROKEN_SIGTSTP (last used in m/ustation.h, m/dpx2.h),
+       and BROKEN_SIGURG (was in s/gnu-linux.h prior to 2008-02-10).
+       All were removed before 23.1.
+       * dispnew.c: Remove HAVE_LIBNCURSES test;
+       it is always true on relevant platforms.
+       * Makefile.in (LD_SWITCH_X_SITE_RPATH):
+       Rename from LD_SWITCH_X_SITE_AUX_RPATH.
+       * Makefile.in (LD_SWITCH_X_SITE_AUX): Remove; no longer used.
+ 2012-04-30  Andreas Schwab  <schwab@linux-m68k.org>
+       * .gdbinit (xpr): Remove checks for no longer existing misc types.
+       (xintfwd, xboolfwd, xobjfwd, xbufobjfwd, xkbobjfwd, xbuflocal):
+       Remove.
+ 2012-04-28  Paul Eggert  <eggert@cs.ucla.edu>
+       Do not avoid creating empty evaporating overlays (Bug#9642).
+       * buffer.c (Fmove_overlay): Revert the change of 2012-04-23.
+       That is, do not delete an evaporating overlay if it becomes
+       empty after its bounds are adjusted to fit within its buffer.
+       This fix caused other problems, and I'm reverting it until we get
+       to the bottom of them.
+ 2012-04-27  Chong Yidong  <cyd@gnu.org>
+       * xselect.c (x_convert_selection): Initialize a pointer (Bug#11315).
+ 2012-04-27  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (pos_visible_p): If the window start position is beyond
+       ZV, start the display from buffer beginning.  Prevents assertion
+       violation in init_iterator when the minibuffer window is scrolled
+       via the scroll bar.
+       * window.c (window_scroll_pixel_based): Likewise.
+ 2012-04-27  Chong Yidong  <cyd@gnu.org>
+       * keymap.c (where_is_internal): Doc fix (Bug#10872).
+ 2012-04-27  Glenn Morris  <rgm@gnu.org>
+       * fileio.c (Fcopy_file, Fset_file_selinux_context):
+       Ignore ENOTSUP failures from setfilecon functions.  (Bug#11245)
+ 2012-04-27  Eli Zaretskii  <eliz@gnu.org>
+       * dispnew.c (swap_glyph_pointers, copy_row_except_pointers):
+       Don't overrun array limits of glyph row's used[] array.  (Bug#11288)
+ 2012-04-26  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (IT_DISPLAYING_WHITESPACE): In addition to the loaded
+       display element, check also the underlying string or buffer
+       character.  (Bug#11341)
+       * w32menu.c: Include w32heap.h.
+       (add_menu_item): If the call to AppendMenuW (via
+       unicode_append_menu) fails, disable Unicode menus only if we are
+       running on Windows 9X/Me.
+ 2012-04-24  Andreas Schwab  <schwab@linux-m68k.org>
+       * .gdbinit (xpr): Handle USE_2_TAGS_FOR_INTS.
+       (xgetint): Add missing shift for LSB tags.
+ 2012-04-24  Martin Rudalics  <rudalics@gmx.at>
+       * keyboard.c (read_char): Don't wipe echo area for select window
+       events: These might get delayed via `mouse-autoselect-window'
+       (Bug#11304).
+ 2012-04-24  Juanma Barranquero  <lekktu@gmail.com>
+       * gnutls.c (init_gnutls_functions): Protect against (unlikely)
+       manipulation of :loaded-from data.
+ 2012-04-23  Juanma Barranquero  <lekktu@gmail.com>
+       * gnutls.c (init_gnutls_functions): The value of :loaded-from is
+       now a cons (bug#11311).
+ 2012-04-23  Paul Eggert  <eggert@cs.ucla.edu>
+       Do not create empty overlays with the evaporate property (Bug#9642).
+       * buffer.c (Fmove_overlay): Delete an evaporating overlay
+       if it becomes empty after its bounds are adjusted to fit within
+       its buffer.  Without this fix, in a nonempty buffer (let ((o
+       (make-overlay 1 2))) (overlay-put o 'evaporate t) (move-overlay o 0 1))
+       yields an empty overlay that has the evaporate property, which is
+       not supposed to happen.
+       Fix minor GTK3 problems found by static checking.
+       * emacsgtkfixed.c (EMACS_TYPE_FIXED, EMACS_FIXED, EmacsFixed)
+       (EmacsFixedPrivate, EmacsFixedClass, struct _EmacsFixed)
+       (struct _EmacsFixedClass, emacs_fixed_get_type):
+       Move decls here from emacsgtkfixed.h, since they needn't be public.
+       (emacs_fixed_get_type): Now static.
+       (emacs_fixed_class_init): Omit unused local.
+       (emacs_fixed_child_type): Remove; unused.
+       * emacsgtkfixed.h (EMACS_TYPE_FIXED, EMACS_FIXED, EmacsFixed)
+       (EmacsFixedPrivate, EmacsFixedClass, struct _EmacsFixed)
+       (struct _EmacsFixedClass): Move to emacsgtkfixed.c.
+       (EMACS_FIXED_CLASS, EMACS_IS_FIXED, EMACS_IS_FIXED_CLASS)
+       (EMACS_FIXED_GET_CLASS): Remove; unused.
+       * gtkutil.c (xg_create_frame_widgets) [!HAVE_GTK3]: Omit unused local.
+       * keyboard.c (handle_async_input): Define only if SYNC_INPUT || SIGIO.
+       Problem reported by Juanma Barranquero for Windows -Wunused-function.
+ 2012-04-22  Paul Eggert  <eggert@cs.ucla.edu>
+       Modernize and clean up gmalloc.c to assume C89 (Bug#9119).
+       * gmalloc.c (_MALLOC_INTERNAL, _MALLOC_H, _PP, __ptr_t)
+       (__malloc_size_t, __malloc_ptrdiff_t):
+       Remove.  All uses removed, replaced by the definiens if needed,
+       since we can assume C89 or better now.
+       Include <stdint.h>, for PTRDIFF_MAX, uintptr_t.
+       (protect_malloc_state, align, get_contiguous_space)
+       (malloc_atfork_handler_prepare, malloc_atfork_handler_parent)
+       (malloc_atfork_handler_child, malloc_enable_thread)
+       (malloc_initialize_1, __malloc_initialize, morecore_nolock)
+       (_malloc_internal_nolock, _malloc_internal, malloc, _malloc)
+       (_free, _realloc, _free_internal_nolock, _free_internal, free, cfree)
+       (special_realloc, _realloc_internal_nolock, _realloc_internal)
+       (realloc, calloc, __default_morecore, memalign, valloc, checkhdr)
+       (freehook, mallochook, reallochook, mabort, mcheck, mprobe):
+       Define using prototypes, not old style.
+       (align, _malloc_internal_nolock, _free_internal_nolock, memalign):
+       Don't assume ptrdiff_t and uintptr_t are no wider than unsigned long.
+       (align): Don't assume that signed integer overflow wraps around.
+       Omit unused local var.
+       (malloc_initialize_1, morecore_nolock, _malloc_internal_nolock)
+       (_free_internal_nolock, memalign, mallochook, reallochook):
+       Omit no-longer-needed casts.
+       (valloc): Use getpagesize, not __getpagesize.
+       (MAGICWORD, MAGICFREE): Now randomish size_t values, not 32-bit.
+       (struct hdr): The 'magic' member is now size_t, not unsigned long.
+       * dbusbind.c (XD_DBUS_VALIDATE_OBJECT): Define only if needed.
+ 2012-04-22  Michael Albinus  <michael.albinus@gmx.de>
+       Move functions from C to Lisp.  Make non-blocking method calls
+       the default.  Implement further D-Bus standard interfaces.
+       * dbusbind.c (DBUS_NUM_MESSAGE_TYPES): Declare.
+       (QCdbus_request_name_allow_replacement)
+       (QCdbus_request_name_replace_existing)
+       (QCdbus_request_name_do_not_queue)
+       (QCdbus_request_name_reply_primary_owner)
+       (QCdbus_request_name_reply_in_queue)
+       (QCdbus_request_name_reply_exists)
+       (QCdbus_request_name_reply_already_owner): Move to dbus.el.
+       (QCdbus_registered_serial, QCdbus_registered_method)
+       (QCdbus_registered_signal): New Lisp objects.
+       (XD_DEBUG_MESSAGE): Use sizeof.
+       (XD_MESSAGE_TYPE_TO_STRING, XD_OBJECT_TO_STRING)
+       (XD_DBUS_VALIDATE_BUS_ADDRESS, XD_DBUS_VALIDATE_OBJECT)
+       (XD_DBUS_VALIDATE_BUS_NAME, XD_DBUS_VALIDATE_PATH)
+       (XD_DBUS_VALIDATE_INTERFACE, XD_DBUS_VALIDATE_MEMBER): New macros.
+       (XD_CHECK_DBUS_SERIAL): Rename from CHECK_DBUS_SERIAL_GET_SERIAL.
+       (xd_signature, xd_append_arg): Allow float for integer types.
+       (xd_get_connection_references): New function.
+       (xd_get_connection_address): Rename from xd_initialize.
+       Return cached address.
+       (xd_remove_watch): Do not unset $DBUS_SESSION_BUS_ADDRESS.
+       (xd_close_bus): Rename from Fdbus_close_bus.  Not needed on Lisp
+       level.
+       (Fdbus_init_bus): New optional arg PRIVATE.  Cache address.
+       Return number of refcounts.
+       (Fdbus_get_unique_name): Make stronger parameter check.
+       (Fdbus_message_internal): New defun.
+       (Fdbus_call_method, Fdbus_call_method_asynchronously)
+       (Fdbus_method_return_internal, Fdbus_method_error_internal)
+       (Fdbus_send_signal, Fdbus_register_service)
+       (Fdbus_register_signal, Fdbus_register_method): Move to dbus.el.
+       (xd_read_message_1): Obey new structure of Vdbus_registered_objects.
+       (xd_read_queued_messages): Obey new structure of Vdbus_registered_buses.
+       (Vdbus_compiled_version, Vdbus_runtime_version)
+       (Vdbus_message_type_invalid, Vdbus_message_type_method_call)
+       (Vdbus_message_type_method_return, Vdbus_message_type_error)
+       (Vdbus_message_type_signal): New defvars.
+       (Vdbus_registered_buses, Vdbus_registered_objects_table):
+       Adapt docstring.
+ 2012-04-22  Paul Eggert  <eggert@cs.ucla.edu>
+       Fix GC_MALLOC_CHECK debugging output on 64-bit hosts.
+       * alloc.c (emacs_blocked_malloc) [GC_MALLOC_CHECK]:
+       Do not assume ptrdiff_t is the same width as 'int'.
+       * alloc.c: Handle unusual debugging option combinations.
+       (GC_CHECK_MARKED_OBJECTS): Undef if ! GC_MARK_STACK,
+       since the two debugging options are incompatible.
+       (GC_MALLOC_CHECK): Similarly, undef if GC_CHECK_MARKED_OBJECTS
+       is defined.
+       (mem_init, mem_insert, mem_insert_fixup):
+       Define if GC_MARK_STACK || GC_MALLOC_CHECK.
+       (NEED_MEM_INSERT): Remove; no longer needed.
  2012-04-22  Leo Liu  <sdl.web@gmail.com>
  
        * sysdep.c (list_system_processes): Support Darwin (Bug#5725).
  
  2012-04-21  Eduard Wiebe  <usenet@pusto.de>
  
-       * sysdep.c (list_system_processes, system_process_attributes): Add
-       implementation for FreeBSD (Bug#5243).
+       * sysdep.c (list_system_processes, system_process_attributes):
+       Add implementation for FreeBSD (Bug#5243).
  
  2012-04-21  Andreas Schwab  <schwab@linux-m68k.org>
  
diff --combined src/alloc.c
@@@ -49,16 -49,24 +49,24 @@@ along with GNU Emacs.  If not, see <htt
  #include <setjmp.h>
  #include <verify.h>
  
+ /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
+    Doable only if GC_MARK_STACK.  */
+ #if ! GC_MARK_STACK
+ # undef GC_CHECK_MARKED_OBJECTS
+ #endif
  /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
-    memory.  Can do this only if using gmalloc.c.  */
+    memory.  Can do this only if using gmalloc.c and if not checking
+    marked objects.  */
  
- #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
+ #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
+      || defined GC_CHECK_MARKED_OBJECTS)
  #undef GC_MALLOC_CHECK
  #endif
  
  #include <unistd.h>
  #ifndef HAVE_UNISTD_H
- extern POINTER_TYPE *sbrk ();
+ extern void *sbrk ();
  #endif
  
  #include <fcntl.h>
@@@ -226,11 -234,11 +234,11 @@@ static ptrdiff_t pure_bytes_used_before
  
  /* Index in pure at which next pure Lisp object will be allocated.. */
  
 -static EMACS_INT pure_bytes_used_lisp;
 +static ptrdiff_t pure_bytes_used_lisp;
  
  /* Number of bytes allocated for non-Lisp objects in pure storage.  */
  
 -static EMACS_INT pure_bytes_used_non_lisp;
 +static ptrdiff_t pure_bytes_used_non_lisp;
  
  /* If nonzero, this is a warning delivered by malloc and not yet
     displayed.  */
@@@ -298,7 -306,7 +306,7 @@@ enum mem_typ
    MEM_TYPE_VECTORLIKE
  };
  
- static POINTER_TYPE *lisp_malloc (size_t, enum mem_type);
+ static void *lisp_malloc (size_t, enum mem_type);
  
  
  #if GC_MARK_STACK || defined GC_MALLOC_CHECK
@@@ -379,8 -387,8 +387,8 @@@ static void *min_heap_address, *max_hea
  static struct mem_node mem_z;
  #define MEM_NIL &mem_z
  
 -static struct Lisp_Vector *allocate_vectorlike (EMACS_INT);
 +static struct Lisp_Vector *allocate_vectorlike (ptrdiff_t);
- static void lisp_free (POINTER_TYPE *);
+ static void lisp_free (void *);
  static void mark_stack (void);
  static int live_vector_p (struct mem_node *, void *);
  static int live_buffer_p (struct mem_node *, void *);
@@@ -391,11 -399,8 +399,8 @@@ static int live_float_p (struct mem_nod
  static int live_misc_p (struct mem_node *, void *);
  static void mark_maybe_object (Lisp_Object);
  static void mark_memory (void *, void *);
+ #if GC_MARK_STACK || defined GC_MALLOC_CHECK
  static void mem_init (void);
- #if (defined GC_MALLOC_CHECK                       \
-      ? !defined SYSTEM_MALLOC && !defined SYNC_INPUT \
-      : GC_MARK_STACK)
- # define NEED_MEM_INSERT
  static struct mem_node *mem_insert (void *, void *, enum mem_type);
  static void mem_insert_fixup (struct mem_node *);
  #endif
@@@ -430,15 -435,15 +435,15 @@@ static Lisp_Object *staticvec[NSTATICS
  
  static int staticidx = 0;
  
- static POINTER_TYPE *pure_alloc (size_t, int);
+ static void *pure_alloc (size_t, int);
  
  
  /* Value is SZ rounded up to the next multiple of ALIGNMENT.
     ALIGNMENT must be a power of 2.  */
  
  #define ALIGN(ptr, ALIGNMENT) \
-   ((POINTER_TYPE *) ((((uintptr_t) (ptr)) + (ALIGNMENT) - 1) \
-                    & ~((ALIGNMENT) - 1)))
+   ((void *) (((uintptr_t) (ptr) + (ALIGNMENT) - 1) \
+            & ~ ((ALIGNMENT) - 1)))
  
  
  \f
@@@ -470,7 -475,7 +475,7 @@@ display_malloc_warning (void
  /* Called if we can't allocate relocatable space for a buffer.  */
  
  void
 -buffer_memory_full (EMACS_INT nbytes)
 +buffer_memory_full (ptrdiff_t nbytes)
  {
    /* If buffers use the relocating allocator, no need to free
       spare_memory, because we may have plenty of malloc space left
@@@ -599,7 -604,7 +604,7 @@@ static ptrdiff_t check_depth
  
  /* Like malloc, but wraps allocated block with header and trailer.  */
  
- static POINTER_TYPE *
+ static void *
  overrun_check_malloc (size_t size)
  {
    register unsigned char *val;
              XMALLOC_OVERRUN_CHECK_SIZE);
      }
    --check_depth;
-   return (POINTER_TYPE *)val;
+   return val;
  }
  
  
  /* Like realloc, but checks old block for overrun, and wraps new block
     with header and trailer.  */
  
- static POINTER_TYPE *
- overrun_check_realloc (POINTER_TYPE *block, size_t size)
+ static void *
+ overrun_check_realloc (void *block, size_t size)
  {
    register unsigned char *val = (unsigned char *) block;
    int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
        memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
      }
  
-   val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
+   val = realloc (val, size + overhead);
  
    if (val && check_depth == 1)
      {
              XMALLOC_OVERRUN_CHECK_SIZE);
      }
    --check_depth;
-   return (POINTER_TYPE *)val;
+   return val;
  }
  
  /* Like free, but checks block for overrun.  */
  
  static void
- overrun_check_free (POINTER_TYPE *block)
+ overrun_check_free (void *block)
  {
    unsigned char *val = (unsigned char *) block;
  
  
  /* Like malloc but check for no memory and block interrupt input..  */
  
POINTER_TYPE *
void *
  xmalloc (size_t size)
  {
-   register POINTER_TYPE *val;
+   void *val;
  
    MALLOC_BLOCK_INPUT;
-   val = (POINTER_TYPE *) malloc (size);
+   val = malloc (size);
    MALLOC_UNBLOCK_INPUT;
  
    if (!val && size)
  
  /* Like realloc but check for no memory and block interrupt input..  */
  
POINTER_TYPE *
- xrealloc (POINTER_TYPE *block, size_t size)
void *
+ xrealloc (void *block, size_t size)
  {
-   register POINTER_TYPE *val;
+   void *val;
  
    MALLOC_BLOCK_INPUT;
    /* We must call malloc explicitly when BLOCK is 0, since some
       reallocs don't do this.  */
    if (! block)
-     val = (POINTER_TYPE *) malloc (size);
+     val = malloc (size);
    else
-     val = (POINTER_TYPE *) realloc (block, size);
+     val = realloc (block, size);
    MALLOC_UNBLOCK_INPUT;
  
    if (!val && size)
  /* Like free but block interrupt input.  */
  
  void
- xfree (POINTER_TYPE *block)
+ xfree (void *block)
  {
    if (!block)
      return;
@@@ -888,7 -893,7 +893,7 @@@ safe_alloca_unwind (Lisp_Object arg
  static void *lisp_malloc_loser;
  #endif
  
- static POINTER_TYPE *
+ static void *
  lisp_malloc (size_t nbytes, enum mem_type type)
  {
    register void *val;
     call to lisp_malloc.  */
  
  static void
- lisp_free (POINTER_TYPE *block)
+ lisp_free (void *block)
  {
    MALLOC_BLOCK_INPUT;
    free (block);
@@@ -1029,7 -1034,7 +1034,7 @@@ static struct ablock *free_ablock
  /* Allocate an aligned block of nbytes.
     Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
     smaller or equal to BLOCK_BYTES.  */
- static POINTER_TYPE *
+ static void *
  lisp_align_malloc (size_t nbytes, enum mem_type type)
  {
    void *base, *val;
  }
  
  static void
- lisp_align_free (POINTER_TYPE *block)
+ lisp_align_free (void *block)
  {
    struct ablock *ablock = block;
    struct ablocks *abase = ABLOCK_ABASE (ablock);
@@@ -1309,7 -1314,7 +1314,7 @@@ emacs_blocked_malloc (size_t size, cons
        {
        fprintf (stderr, "Malloc returned %p which is already in use\n",
                 value);
-       fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
+       fprintf (stderr, "Region in use is %p...%p, %td bytes, type %d\n",
                 m->start, m->end, (char *) m->end - (char *) m->start,
                 m->type);
        abort ();
@@@ -1657,7 -1662,7 +1662,7 @@@ struct sdat
  
  #ifdef GC_CHECK_STRING_BYTES
  
 -  EMACS_INT nbytes;
 +  ptrdiff_t nbytes;
    unsigned char data[1];
  
  #define SDATA_NBYTES(S)       (S)->nbytes
      unsigned char data[1];
  
      /* When STRING is null.  */
 -    EMACS_INT nbytes;
 +    ptrdiff_t nbytes;
    } u;
  
  #define SDATA_NBYTES(S)       (S)->u.nbytes
@@@ -1782,24 -1787,24 +1787,24 @@@ static char const string_overrun_cookie
  #define SDATA_SIZE(NBYTES)                    \
       ((SDATA_DATA_OFFSET                      \
         + (NBYTES) + 1                         \
 -       + sizeof (EMACS_INT) - 1)              \
 -      & ~(sizeof (EMACS_INT) - 1))
 +       + sizeof (ptrdiff_t) - 1)              \
 +      & ~(sizeof (ptrdiff_t) - 1))
  
  #else /* not GC_CHECK_STRING_BYTES */
  
  /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
     less than the size of that member.  The 'max' is not needed when
 -   SDATA_DATA_OFFSET is a multiple of sizeof (EMACS_INT), because then the
 +   SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
     alignment code reserves enough space.  */
  
  #define SDATA_SIZE(NBYTES)                                  \
       ((SDATA_DATA_OFFSET                                    \
 -       + (SDATA_DATA_OFFSET % sizeof (EMACS_INT) == 0       \
 +       + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0       \
          ? NBYTES                                            \
 -        : max (NBYTES, sizeof (EMACS_INT) - 1))             \
 +        : max (NBYTES, sizeof (ptrdiff_t) - 1))             \
         + 1                                                  \
 -       + sizeof (EMACS_INT) - 1)                            \
 -      & ~(sizeof (EMACS_INT) - 1))
 +       + sizeof (ptrdiff_t) - 1)                            \
 +      & ~(sizeof (ptrdiff_t) - 1))
  
  #endif /* not GC_CHECK_STRING_BYTES */
  
@@@ -1843,10 -1848,10 +1848,10 @@@ static int check_string_bytes_count
  
  /* Like GC_STRING_BYTES, but with debugging check.  */
  
 -EMACS_INT
 +ptrdiff_t
  string_bytes (struct Lisp_String *s)
  {
 -  EMACS_INT nbytes =
 +  ptrdiff_t nbytes =
      (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
  
    if (!PURE_POINTER_P (s)
@@@ -1869,7 -1874,7 +1874,7 @@@ check_sblock (struct sblock *b
      {
        /* Compute the next FROM here because copying below may
         overwrite data we need to compute it.  */
 -      EMACS_INT nbytes;
 +      ptrdiff_t nbytes;
  
        /* Check that the string size recorded in the string is the
         same as the one recorded in the sdata structure. */
@@@ -2015,7 -2020,7 +2020,7 @@@ allocate_string_data (struct Lisp_Strin
  {
    struct sdata *data, *old_data;
    struct sblock *b;
 -  EMACS_INT needed, old_nbytes;
 +  ptrdiff_t needed, old_nbytes;
  
    if (STRING_BYTES_MAX < nbytes)
      string_overflow ();
@@@ -2260,7 -2265,7 +2265,7 @@@ compact_small_strings (void
        {
          /* Compute the next FROM here because copying below may
             overwrite data we need to compute it.  */
 -        EMACS_INT nbytes;
 +        ptrdiff_t nbytes;
  
  #ifdef GC_CHECK_STRING_BYTES
          /* Check that the string size recorded in the string is the
@@@ -2390,8 -2395,7 +2395,8 @@@ LENGTH must be a number.  INIT matters 
  {
    register Lisp_Object val;
    struct Lisp_Bool_Vector *p;
 -  EMACS_INT length_in_chars, length_in_elts;
 +  ptrdiff_t length_in_chars;
 +  EMACS_INT length_in_elts;
    int bits_per_value;
  
    CHECK_NATNUM (length);
    bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
  
    length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
 -  length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
 -                   / BOOL_VECTOR_BITS_PER_CHAR);
  
    /* We must allocate one more elements than LENGTH_IN_ELTS for the
       slot `size' of the struct Lisp_Bool_Vector.  */
    p = XBOOL_VECTOR (val);
    p->size = XFASTINT (length);
  
 +  length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
 +                   / BOOL_VECTOR_BITS_PER_CHAR);
    if (length_in_chars)
      {
        memset (p->data, ! NILP (init) ? -1 : 0, length_in_chars);
     multibyte, depending on the contents.  */
  
  Lisp_Object
 -make_string (const char *contents, EMACS_INT nbytes)
 +make_string (const char *contents, ptrdiff_t nbytes)
  {
    register Lisp_Object val;
 -  EMACS_INT nchars, multibyte_nbytes;
 +  ptrdiff_t nchars, multibyte_nbytes;
  
    parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
                          &nchars, &multibyte_nbytes);
  /* Make an unibyte string from LENGTH bytes at CONTENTS.  */
  
  Lisp_Object
 -make_unibyte_string (const char *contents, EMACS_INT length)
 +make_unibyte_string (const char *contents, ptrdiff_t length)
  {
    register Lisp_Object val;
    val = make_uninit_string (length);
  
  Lisp_Object
  make_multibyte_string (const char *contents,
 -                     EMACS_INT nchars, EMACS_INT nbytes)
 +                     ptrdiff_t nchars, ptrdiff_t nbytes)
  {
    register Lisp_Object val;
    val = make_uninit_multibyte_string (nchars, nbytes);
  
  Lisp_Object
  make_string_from_bytes (const char *contents,
 -                      EMACS_INT nchars, EMACS_INT nbytes)
 +                      ptrdiff_t nchars, ptrdiff_t nbytes)
  {
    register Lisp_Object val;
    val = make_uninit_multibyte_string (nchars, nbytes);
  
  Lisp_Object
  make_specified_string (const char *contents,
 -                     EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
 +                     ptrdiff_t nchars, ptrdiff_t nbytes, int multibyte)
  {
    register Lisp_Object val;
  
@@@ -2935,7 -2939,7 +2940,7 @@@ enu
     with room for LEN Lisp_Objects.  */
  
  static struct Lisp_Vector *
 -allocate_vectorlike (EMACS_INT len)
 +allocate_vectorlike (ptrdiff_t len)
  {
    struct Lisp_Vector *p;
    size_t nbytes;
@@@ -2991,7 -2995,7 +2996,7 @@@ allocate_vector (EMACS_INT len
  /* Allocate other vector-like structures.  */
  
  struct Lisp_Vector *
 -allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag)
 +allocate_pseudovector (int memlen, int lisplen, int tag)
  {
    struct Lisp_Vector *v = allocate_vectorlike (memlen);
    int i;
@@@ -3055,14 -3059,14 +3060,14 @@@ See also the function `vector'.  */
    (register Lisp_Object length, Lisp_Object init)
  {
    Lisp_Object vector;
 -  register EMACS_INT sizei;
 -  register EMACS_INT i;
 +  register ptrdiff_t sizei;
 +  register ptrdiff_t i;
    register struct Lisp_Vector *p;
  
    CHECK_NATNUM (length);
 -  sizei = XFASTINT (length);
  
 -  p = allocate_vector (sizei);
 +  p = allocate_vector (XFASTINT (length));
 +  sizei = XFASTINT (length);
    for (i = 0; i < sizei; i++)
      p->contents[i] = init;
  
@@@ -3579,8 -3583,6 +3584,6 @@@ mem_find (void *start
  }
  
  
- #ifdef NEED_MEM_INSERT
  /* Insert a new node into the tree for a block of memory with start
     address START, end address END, and type TYPE.  Value is a
     pointer to the node that was inserted.  */
@@@ -3728,8 -3730,6 +3731,6 @@@ mem_insert_fixup (struct mem_node *x
    mem_root->color = MEM_BLACK;
  }
  
- #endif /* NEED_MEM_INSERT */
  
  /*   (x)                   (y)
       / \                   / \
@@@ -4297,8 -4297,8 +4298,8 @@@ mark_maybe_pointer (void *p
     wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
     If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
     suffice to widen it to to a Lisp_Object and check it that way.  */
- #if defined USE_LSB_TAG || UINTPTR_MAX >> VALBITS != 0
- # if !defined USE_LSB_TAG && UINTPTR_MAX >> VALBITS >> GCTYPEBITS != 0
+ #if defined USE_LSB_TAG || VAL_MAX < UINTPTR_MAX
+ # if !defined USE_LSB_TAG && VAL_MAX < UINTPTR_MAX >> GCTYPEBITS
    /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
       nor mark_maybe_object can follow the pointers.  This should not occur on
       any practical porting target.  */
@@@ -4722,10 -4722,10 +4723,10 @@@ valid_lisp_object_p (Lisp_Object obj
     pointer to it.  TYPE is the Lisp type for which the memory is
     allocated.  TYPE < 0 means it's not used for a Lisp object.  */
  
- static POINTER_TYPE *
+ static void *
  pure_alloc (size_t size, int type)
  {
-   POINTER_TYPE *result;
+   void *result;
  #ifdef USE_LSB_TAG
    size_t alignment = (1 << GCTYPEBITS);
  #else
@@@ -4791,14 -4791,14 +4792,14 @@@ check_pure_size (void
     address.  Return NULL if not found.  */
  
  static char *
 -find_string_data_in_pure (const char *data, EMACS_INT nbytes)
 +find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
  {
    int i;
 -  EMACS_INT skip, bm_skip[256], last_char_skip, infinity, start, start_max;
 +  ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
    const unsigned char *p;
    char *non_lisp_beg;
  
 -  if (pure_bytes_used_non_lisp < nbytes + 1)
 +  if (pure_bytes_used_non_lisp <= nbytes)
      return NULL;
  
    /* Set up the Boyer-Moore table.  */
  
  Lisp_Object
  make_pure_string (const char *data,
 -                EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
 +                ptrdiff_t nchars, ptrdiff_t nbytes, int multibyte)
  {
    Lisp_Object string;
    struct Lisp_String *s;
@@@ -4890,7 -4890,7 +4891,7 @@@ make_pure_c_string (const char *data
  {
    Lisp_Object string;
    struct Lisp_String *s;
 -  EMACS_INT nchars = strlen (data);
 +  ptrdiff_t nchars = strlen (data);
  
    s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
    s->size = nchars;
@@@ -4937,7 -4937,7 +4938,7 @@@ make_pure_float (double num
     pure space.  */
  
  Lisp_Object
 -make_pure_vector (EMACS_INT len)
 +make_pure_vector (ptrdiff_t len)
  {
    Lisp_Object new;
    struct Lisp_Vector *p;
@@@ -4981,8 -4981,8 +4982,8 @@@ Does not copy symbols.  Copies strings 
    else if (COMPILEDP (obj) || VECTORP (obj))
      {
        register struct Lisp_Vector *vec;
 -      register EMACS_INT i;
 -      EMACS_INT size;
 +      register ptrdiff_t i;
 +      ptrdiff_t size;
  
        size = ASIZE (obj);
        if (size & PSEUDOVECTOR_FLAG)
@@@ -5034,10 -5034,10 +5035,10 @@@ staticpro (Lisp_Object *varaddress
  
  /* Temporarily prevent garbage collection.  */
  
 -int
 +ptrdiff_t
  inhibit_garbage_collection (void)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
    return count;
@@@ -5063,7 -5063,7 +5064,7 @@@ See Info node `(elisp)Garbage Collectio
    ptrdiff_t i;
    int message_p;
    Lisp_Object total[8];
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    EMACS_TIME t1, t2, t3;
  
    if (abort_on_gc)
  
    if (!NILP (Vpost_gc_hook))
      {
 -      int gc_count = inhibit_garbage_collection ();
 +      ptrdiff_t gc_count = inhibit_garbage_collection ();
        safe_run_hooks (Qpost_gc_hook);
        unbind_to (gc_count, Qnil);
      }
@@@ -5443,8 -5443,8 +5444,8 @@@ ptrdiff_t mark_object_loop_halt EXTERNA
  static void
  mark_vectorlike (struct Lisp_Vector *ptr)
  {
 -  EMACS_INT size = ptr->header.size;
 -  EMACS_INT i;
 +  ptrdiff_t size = ptr->header.size;
 +  ptrdiff_t i;
  
    eassert (!VECTOR_MARKED_P (ptr));
    VECTOR_MARK (ptr);          /* Else mark it */
@@@ -5838,7 -5838,7 +5839,7 @@@ mark_buffer (Lisp_Object buf
  }
  
  /* Mark the Lisp pointers in the terminal objects.
-    Called by the Fgarbage_collector.  */
+    Called by Fgarbage_collect.  */
  
  static void
  mark_terminals (void)
@@@ -6325,7 -6325,7 +6326,7 @@@ Lisp_Objec
  which_symbols (Lisp_Object obj, EMACS_INT find_max)
  {
     struct symbol_block *sblk;
 -   int gc_count = inhibit_garbage_collection ();
 +   ptrdiff_t gc_count = inhibit_garbage_collection ();
     Lisp_Object found = Qnil;
  
     if (! DEADP (obj))
diff --combined src/buffer.c
@@@ -154,7 -154,7 +154,7 @@@ Lisp_Object Qinsert_behind_hooks
  static void alloc_buffer_text (struct buffer *, ptrdiff_t);
  static void free_buffer_text (struct buffer *b);
  static struct Lisp_Overlay * copy_overlays (struct buffer *, struct Lisp_Overlay *);
 -static void modify_overlay (struct buffer *, EMACS_INT, EMACS_INT);
 +static void modify_overlay (struct buffer *, ptrdiff_t, ptrdiff_t);
  static Lisp_Object buffer_lisp_local_variables (struct buffer *);
  
  /* For debugging; temporary.  See set_buffer_internal.  */
@@@ -392,7 -392,6 +392,6 @@@ even if it is dead.  The return value i
  
    BVAR (b, mark) = Fmake_marker ();
    BUF_MARKERS (b) = NULL;
-   BVAR (b, name) = name;
  
    /* Put this in the alist of all live buffers.  */
    XSETBUFFER (buffer, b);
@@@ -419,7 -418,7 +418,7 @@@ copy_overlays (struct buffer *b, struc
    for (; list; list = list->next)
      {
        Lisp_Object overlay, start, end, old_overlay;
 -      EMACS_INT charpos;
 +      ptrdiff_t charpos;
  
        XSETMISC (old_overlay, list);
        charpos = marker_position (OVERLAY_START (old_overlay));
@@@ -612,7 -611,6 +611,6 @@@ CLONE nil means the indirect buffer's s
    Vbuffer_alist = nconc2 (Vbuffer_alist, Fcons (Fcons (name, buf), Qnil));
  
    BVAR (b, mark) = Fmake_marker ();
-   BVAR (b, name) = name;
  
    /* The multibyte status belongs to the base buffer.  */
    BVAR (b, enable_multibyte_characters) = BVAR (b->base_buffer, enable_multibyte_characters);
@@@ -854,8 -852,8 +852,8 @@@ it is in the sequence to be tried) eve
    (register Lisp_Object name, Lisp_Object ignore)
  {
    register Lisp_Object gentemp, tem;
 -  EMACS_INT count;
 -  char number[INT_BUFSIZE_BOUND (EMACS_INT) + sizeof "<>"];
 +  ptrdiff_t count;
 +  char number[INT_BUFSIZE_BOUND (ptrdiff_t) + sizeof "<>"];
  
    CHECK_STRING (name);
  
    count = 1;
    while (1)
      {
 -      sprintf (number, "<%"pI"d>", ++count);
 +      sprintf (number, "<%"pD"d>", ++count);
        gentemp = concat2 (name, build_string (number));
        tem = Fstring_equal (gentemp, ignore);
        if (!NILP (tem))
@@@ -1477,7 -1475,7 +1475,7 @@@ with SIGHUP.  */
  
    /* Run hooks with the buffer to be killed the current buffer.  */
    {
 -    int count = SPECPDL_INDEX ();
 +    ptrdiff_t count = SPECPDL_INDEX ();
      Lisp_Object arglist[1];
  
      record_unwind_protect (save_excursion_restore, save_excursion_save ());
@@@ -1753,7 -1751,7 +1751,7 @@@ Use this function before selecting the 
  the current buffer's major mode.  */)
    (Lisp_Object buffer)
  {
 -  int count;
 +  ptrdiff_t count;
    Lisp_Object function;
  
    CHECK_BUFFER (buffer);
@@@ -1965,15 -1963,16 +1963,15 @@@ validate_region (register Lisp_Object *
        tem = *b;  *b = *e;  *e = tem;
      }
  
 -  if (!(BEGV <= XINT (*b) && XINT (*b) <= XINT (*e)
 -        && XINT (*e) <= ZV))
 +  if (! (BEGV <= XINT (*b) && XINT (*e) <= ZV))
      args_out_of_range (*b, *e);
  }
  \f
  /* Advance BYTE_POS up to a character boundary
     and return the adjusted position.  */
  
 -static EMACS_INT
 -advance_to_char_boundary (EMACS_INT byte_pos)
 +static ptrdiff_t
 +advance_to_char_boundary (ptrdiff_t byte_pos)
  {
    int c;
  
      {
        /* We should advance BYTE_POS only when C is a constituent of a
           multibyte sequence.  */
 -      EMACS_INT orig_byte_pos = byte_pos;
 +      ptrdiff_t orig_byte_pos = byte_pos;
  
        do
        {
@@@ -2052,18 -2051,18 +2050,18 @@@ DEFUN ("buffer-swap-text", Fbuffer_swap
    eassert (current_buffer->text == &current_buffer->own_text);
    eassert (other_buffer->text == &other_buffer->own_text);
  #ifdef REL_ALLOC
-   r_alloc_reset_variable ((POINTER_TYPE **) &current_buffer->own_text.beg,
-                         (POINTER_TYPE **) &other_buffer->own_text.beg);
-   r_alloc_reset_variable ((POINTER_TYPE **) &other_buffer->own_text.beg,
-                         (POINTER_TYPE **) &current_buffer->own_text.beg);
+   r_alloc_reset_variable ((void **) &current_buffer->own_text.beg,
+                         (void **) &other_buffer->own_text.beg);
+   r_alloc_reset_variable ((void **) &other_buffer->own_text.beg,
+                         (void **) &current_buffer->own_text.beg);
  #endif /* REL_ALLOC */
  
 -  swapfield (pt, EMACS_INT);
 -  swapfield (pt_byte, EMACS_INT);
 -  swapfield (begv, EMACS_INT);
 -  swapfield (begv_byte, EMACS_INT);
 -  swapfield (zv, EMACS_INT);
 -  swapfield (zv_byte, EMACS_INT);
 +  swapfield (pt, ptrdiff_t);
 +  swapfield (pt_byte, ptrdiff_t);
 +  swapfield (begv, ptrdiff_t);
 +  swapfield (begv_byte, ptrdiff_t);
 +  swapfield (zv, ptrdiff_t);
 +  swapfield (zv_byte, ptrdiff_t);
    eassert (!current_buffer->base_buffer);
    eassert (!other_buffer->base_buffer);
    current_buffer->clip_changed = 1;   other_buffer->clip_changed = 1;
    other_buffer->prevent_redisplay_optimizations_p = 1;
    swapfield (overlays_before, struct Lisp_Overlay *);
    swapfield (overlays_after, struct Lisp_Overlay *);
 -  swapfield (overlay_center, EMACS_INT);
 +  swapfield (overlay_center, ptrdiff_t);
    swapfield_ (undo_list, Lisp_Object);
    swapfield_ (mark, Lisp_Object);
    swapfield_ (enable_multibyte_characters, Lisp_Object);
@@@ -2156,7 -2155,7 +2154,7 @@@ current buffer is cleared.  */
  {
    struct Lisp_Marker *tail, *markers;
    struct buffer *other;
 -  EMACS_INT begv, zv;
 +  ptrdiff_t begv, zv;
    int narrowed = (BEG != BEGV || Z != ZV);
    int modified_p = !NILP (Fbuffer_modified_p (Qnil));
    Lisp_Object old_undo = BVAR (current_buffer, undo_list);
  
    if (NILP (flag))
      {
 -      EMACS_INT pos, stop;
 +      ptrdiff_t pos, stop;
        unsigned char *p;
  
        /* Do this first, so it can use CHAR_TO_BYTE
      }
    else
      {
 -      EMACS_INT pt = PT;
 -      EMACS_INT pos, stop;
 +      ptrdiff_t pt = PT;
 +      ptrdiff_t pos, stop;
        unsigned char *p, *pend;
  
        /* Be sure not to have a multibyte sequence striding over the GAP.
          while (! CHAR_HEAD_P (*q) && q > BEG_ADDR) q--;
          if (LEADING_CODE_P (*q))
            {
 -            EMACS_INT new_gpt = GPT_BYTE - (GPT_ADDR - q);
 +            ptrdiff_t new_gpt = GPT_BYTE - (GPT_ADDR - q);
  
              move_gap_both (new_gpt, new_gpt);
            }
        ZV = chars_in_text (BEG_ADDR, ZV_BYTE - BEG_BYTE) + BEG;
  
        {
 -      EMACS_INT byte = advance_to_char_boundary (PT_BYTE);
 -      EMACS_INT position;
 +      ptrdiff_t byte = advance_to_char_boundary (PT_BYTE);
 +      ptrdiff_t position;
  
        if (byte > GPT_BYTE)
          position = chars_in_text (GAP_END_ADDR, byte - GPT_BYTE) + GPT;
@@@ -2518,20 -2517,20 +2516,20 @@@ swap_out_buffer_local_variables (struc
  ptrdiff_t
  overlays_at (EMACS_INT pos, int extend, Lisp_Object **vec_ptr,
             ptrdiff_t *len_ptr,
 -           EMACS_INT *next_ptr, EMACS_INT *prev_ptr, int change_req)
 +           ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr, int change_req)
  {
    Lisp_Object overlay, start, end;
    struct Lisp_Overlay *tail;
    ptrdiff_t idx = 0;
    ptrdiff_t len = *len_ptr;
    Lisp_Object *vec = *vec_ptr;
 -  EMACS_INT next = ZV;
 -  EMACS_INT prev = BEGV;
 +  ptrdiff_t next = ZV;
 +  ptrdiff_t prev = BEGV;
    int inhibit_storing = 0;
  
    for (tail = current_buffer->overlays_before; tail; tail = tail->next)
      {
 -      EMACS_INT startpos, endpos;
 +      ptrdiff_t startpos, endpos;
  
        XSETMISC (overlay, tail);
  
  
    for (tail = current_buffer->overlays_after; tail; tail = tail->next)
      {
 -      EMACS_INT startpos, endpos;
 +      ptrdiff_t startpos, endpos;
  
        XSETMISC (overlay, tail);
  
  static ptrdiff_t
  overlays_in (EMACS_INT beg, EMACS_INT end, int extend,
             Lisp_Object **vec_ptr, ptrdiff_t *len_ptr,
 -           EMACS_INT *next_ptr, EMACS_INT *prev_ptr)
 +           ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr)
  {
    Lisp_Object overlay, ostart, oend;
    struct Lisp_Overlay *tail;
    ptrdiff_t idx = 0;
    ptrdiff_t len = *len_ptr;
    Lisp_Object *vec = *vec_ptr;
 -  EMACS_INT next = ZV;
 -  EMACS_INT prev = BEGV;
 +  ptrdiff_t next = ZV;
 +  ptrdiff_t prev = BEGV;
    int inhibit_storing = 0;
    int end_is_Z = end == Z;
  
    for (tail = current_buffer->overlays_before; tail; tail = tail->next)
      {
 -      EMACS_INT startpos, endpos;
 +      ptrdiff_t startpos, endpos;
  
        XSETMISC (overlay, tail);
  
  
    for (tail = current_buffer->overlays_after; tail; tail = tail->next)
      {
 -      EMACS_INT startpos, endpos;
 +      ptrdiff_t startpos, endpos;
  
        XSETMISC (overlay, tail);
  
  int
  mouse_face_overlay_overlaps (Lisp_Object overlay)
  {
 -  EMACS_INT start = OVERLAY_POSITION (OVERLAY_START (overlay));
 -  EMACS_INT end = OVERLAY_POSITION (OVERLAY_END (overlay));
 +  ptrdiff_t start = OVERLAY_POSITION (OVERLAY_START (overlay));
 +  ptrdiff_t end = OVERLAY_POSITION (OVERLAY_END (overlay));
    ptrdiff_t n, i, size;
    Lisp_Object *v, tem;
  
  \f
  /* Fast function to just test if we're at an overlay boundary.  */
  int
 -overlay_touches_p (EMACS_INT pos)
 +overlay_touches_p (ptrdiff_t pos)
  {
    Lisp_Object overlay;
    struct Lisp_Overlay *tail;
  
    for (tail = current_buffer->overlays_before; tail; tail = tail->next)
      {
 -      EMACS_INT endpos;
 +      ptrdiff_t endpos;
  
        XSETMISC (overlay ,tail);
        if (!OVERLAYP (overlay))
  
    for (tail = current_buffer->overlays_after; tail; tail = tail->next)
      {
 -      EMACS_INT startpos;
 +      ptrdiff_t startpos;
  
        XSETMISC (overlay, tail);
        if (!OVERLAYP (overlay))
  struct sortvec
  {
    Lisp_Object overlay;
 -  EMACS_INT beg, end;
 +  ptrdiff_t beg, end;
    EMACS_INT priority;
  };
  
@@@ -2959,7 -2958,7 +2957,7 @@@ static voi
  record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
                       Lisp_Object str2, Lisp_Object pri, ptrdiff_t size)
  {
 -  EMACS_INT nbytes;
 +  ptrdiff_t nbytes;
  
    if (ssl->used == ssl->size)
      ssl->buf = xpalloc (ssl->buf, &ssl->size, 5, -1, sizeof *ssl->buf);
     PSTR, if that variable is non-null.  The string may be overwritten by
     subsequent calls.  */
  
 -EMACS_INT
 -overlay_strings (EMACS_INT pos, struct window *w, unsigned char **pstr)
 +ptrdiff_t
 +overlay_strings (ptrdiff_t pos, struct window *w, unsigned char **pstr)
  {
    Lisp_Object overlay, window, str;
    struct Lisp_Overlay *ov;
 -  EMACS_INT startpos, endpos;
 +  ptrdiff_t startpos, endpos;
    int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
  
    overlay_heads.used = overlay_heads.bytes = 0;
    if (overlay_heads.bytes || overlay_tails.bytes)
      {
        Lisp_Object tem;
 -      EMACS_INT i;
 +      ptrdiff_t i;
        unsigned char *p;
        ptrdiff_t total;
  
        p = overlay_str_buf;
        for (i = overlay_tails.used; --i >= 0;)
        {
 -        EMACS_INT nbytes;
 +        ptrdiff_t nbytes;
          tem = overlay_tails.buf[i].string;
          nbytes = copy_text (SDATA (tem), p,
                              SBYTES (tem),
        }
        for (i = 0; i < overlay_heads.used; ++i)
        {
 -        EMACS_INT nbytes;
 +        ptrdiff_t nbytes;
          tem = overlay_heads.buf[i].string;
          nbytes = copy_text (SDATA (tem), p,
                              SBYTES (tem),
  /* Shift overlays in BUF's overlay lists, to center the lists at POS.  */
  
  void
 -recenter_overlay_lists (struct buffer *buf, EMACS_INT pos)
 +recenter_overlay_lists (struct buffer *buf, ptrdiff_t pos)
  {
    Lisp_Object overlay, beg, end;
    struct Lisp_Overlay *prev, *tail, *next;
        if (OVERLAY_POSITION (end) > pos)
        {
          /* OVERLAY needs to be moved.  */
 -        EMACS_INT where = OVERLAY_POSITION (beg);
 +        ptrdiff_t where = OVERLAY_POSITION (beg);
          struct Lisp_Overlay *other, *other_prev;
  
          /* Splice the cons cell TAIL out of overlays_before.  */
        if (OVERLAY_POSITION (end) <= pos)
        {
          /* OVERLAY needs to be moved.  */
 -        EMACS_INT where = OVERLAY_POSITION (end);
 +        ptrdiff_t where = OVERLAY_POSITION (end);
          struct Lisp_Overlay *other, *other_prev;
  
          /* Splice the cons cell TAIL out of overlays_after.  */
  }
  
  void
 -adjust_overlays_for_insert (EMACS_INT pos, EMACS_INT length)
 +adjust_overlays_for_insert (ptrdiff_t pos, ptrdiff_t length)
  {
    /* After an insertion, the lists are still sorted properly,
       but we may need to update the value of the overlay center.  */
  }
  
  void
 -adjust_overlays_for_delete (EMACS_INT pos, EMACS_INT length)
 +adjust_overlays_for_delete (ptrdiff_t pos, ptrdiff_t length)
  {
    if (current_buffer->overlay_center < pos)
      /* The deletion was to our right.  No change needed; the before- and
         after-lists are still consistent.  */
      ;
 -  else if (current_buffer->overlay_center > pos + length)
 +  else if (current_buffer->overlay_center - pos > length)
      /* The deletion was to our left.  We need to adjust the center value
         to account for the change in position, but the lists are consistent
         given the new value.  */
     Such an overlay might even have negative size at this point.
     If so, we'll make the overlay empty. */
  void
 -fix_start_end_in_overlays (register EMACS_INT start, register EMACS_INT end)
 +fix_start_end_in_overlays (register ptrdiff_t start, register ptrdiff_t end)
  {
    Lisp_Object overlay;
    struct Lisp_Overlay *before_list IF_LINT (= NULL);
       current_buffer->overlays_before or overlays_after, depending
       which loop we're in.  */
    struct Lisp_Overlay *tail, *parent;
 -  EMACS_INT startpos, endpos;
 +  ptrdiff_t startpos, endpos;
  
    /* This algorithm shifts links around instead of consing and GCing.
       The loop invariant is that before_list (resp. after_list) is a
     was at PREV, and now is at POS.  */
  
  void
 -fix_overlays_before (struct buffer *bp, EMACS_INT prev, EMACS_INT pos)
 +fix_overlays_before (struct buffer *bp, ptrdiff_t prev, ptrdiff_t pos)
  {
    /* If parent is nil, replace overlays_before; otherwise, parent->next.  */
    struct Lisp_Overlay *tail = bp->overlays_before, *parent = NULL, *right_pair;
    Lisp_Object tem;
 -  EMACS_INT end IF_LINT (= 0);
 +  ptrdiff_t end IF_LINT (= 0);
  
    /* After the insertion, the several overlays may be in incorrect
       order.  The possibility is that, in the list `overlays_before',
@@@ -3627,11 -3626,11 +3625,11 @@@ for the rear of the overlay advance whe
  /* Mark a section of BUF as needing redisplay because of overlays changes.  */
  
  static void
 -modify_overlay (struct buffer *buf, EMACS_INT start, EMACS_INT end)
 +modify_overlay (struct buffer *buf, ptrdiff_t start, ptrdiff_t end)
  {
    if (start > end)
      {
 -      EMACS_INT temp = start;
 +      ptrdiff_t temp = start;
        start = end;
        end = temp;
      }
@@@ -3680,8 -3679,7 +3678,8 @@@ buffer.  */
  {
    struct buffer *b, *ob;
    Lisp_Object obuffer;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
 +  ptrdiff_t n_beg, n_end;
  
    CHECK_OVERLAY (overlay);
    if (NILP (buffer))
    CHECK_NUMBER_COERCE_MARKER (beg);
    CHECK_NUMBER_COERCE_MARKER (end);
  
 -  if (XINT (beg) == XINT (end) && ! NILP (Foverlay_get (overlay, Qevaporate)))
 -    return Fdelete_overlay (overlay);
 -
    if (XINT (beg) > XINT (end))
      {
        Lisp_Object temp;
        temp = beg; beg = end; end = temp;
      }
  
 +  Fset_marker (OVERLAY_START (overlay), beg, buffer);
 +  Fset_marker (OVERLAY_END (overlay), end, buffer);
 +  n_beg = marker_position (OVERLAY_START (overlay));
 +  n_end = marker_position (OVERLAY_END (overlay));
 +
 +  if (n_beg == n_end && ! NILP (Foverlay_get (overlay, Qevaporate)))
 +    return Fdelete_overlay (overlay);
 +
    specbind (Qinhibit_quit, Qt);
  
    obuffer = Fmarker_buffer (OVERLAY_START (overlay));
        /* Redisplay where the overlay was.  */
        if (!NILP (obuffer))
        {
 -        EMACS_INT o_beg;
 -        EMACS_INT o_end;
 +        ptrdiff_t o_beg;
 +        ptrdiff_t o_end;
  
          o_beg = OVERLAY_POSITION (OVERLAY_START (overlay));
          o_end = OVERLAY_POSITION (OVERLAY_END (overlay));
        }
  
        /* Redisplay where the overlay is going to be.  */
 -      modify_overlay (b, XINT (beg), XINT (end));
 +      modify_overlay (b, n_beg, n_end);
      }
    else
      /* Redisplay the area the overlay has just left, or just enclosed.  */
      {
 -      EMACS_INT o_beg, o_end;
 +      ptrdiff_t o_beg, o_end;
  
        o_beg = OVERLAY_POSITION (OVERLAY_START (overlay));
        o_end = OVERLAY_POSITION (OVERLAY_END (overlay));
  
 -      if (o_beg == XINT (beg))
 -      modify_overlay (b, o_end, XINT (end));
 -      else if (o_end == XINT (end))
 -      modify_overlay (b, o_beg, XINT (beg));
 +      if (o_beg == n_beg)
 +      modify_overlay (b, o_end, n_end);
 +      else if (o_end == n_end)
 +      modify_overlay (b, o_beg, n_beg);
        else
 -      {
 -        if (XINT (beg) < o_beg) o_beg = XINT (beg);
 -        if (XINT (end) > o_end) o_end = XINT (end);
 -        modify_overlay (b, o_beg, o_end);
 -      }
 +      modify_overlay (b, min (o_beg, n_beg), max (o_end, n_end));
      }
  
    if (!NILP (obuffer))
        eassert (XOVERLAY (overlay)->next == NULL);
      }
  
 -  Fset_marker (OVERLAY_START (overlay), beg, buffer);
 -  Fset_marker (OVERLAY_END   (overlay), end, buffer);
 -
    /* Put the overlay on the wrong list.  */
 -  end = OVERLAY_END (overlay);
 -  if (OVERLAY_POSITION (end) < b->overlay_center)
 +  if (n_end < b->overlay_center)
      {
        XOVERLAY (overlay)->next = b->overlays_after;
        b->overlays_after = XOVERLAY (overlay);
@@@ -3787,7 -3788,7 +3785,7 @@@ DEFUN ("delete-overlay", Fdelete_overla
  {
    Lisp_Object buffer;
    struct buffer *b;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    CHECK_OVERLAY (overlay);
  
@@@ -3878,7 -3879,7 +3876,7 @@@ DEFUN ("overlays-at", Foverlays_at, Sov
    /* Put all the overlays we want in a vector in overlay_vec.
       Store the length in len.  */
    noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
 -                         (EMACS_INT *) 0, (EMACS_INT *) 0, 0);
 +                         0, 0, 0);
  
    /* Make a list of them all.  */
    result = Flist (noverlays, overlay_vec);
@@@ -3926,7 -3927,7 +3924,7 @@@ the value is (point-max).  */
    (Lisp_Object pos)
  {
    ptrdiff_t i, len, noverlays;
 -  EMACS_INT endpos;
 +  ptrdiff_t endpos;
    Lisp_Object *overlay_vec;
  
    CHECK_NUMBER_COERCE_MARKER (pos);
       Store the length in len.
       endpos gets the position where the next overlay starts.  */
    noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
 -                         &endpos, (EMACS_INT *) 0, 1);
 +                         &endpos, 0, 1);
  
    /* If any of these overlays ends before endpos,
       use its ending point instead.  */
    for (i = 0; i < noverlays; i++)
      {
        Lisp_Object oend;
 -      EMACS_INT oendpos;
 +      ptrdiff_t oendpos;
  
        oend = OVERLAY_END (overlay_vec[i]);
        oendpos = OVERLAY_POSITION (oend);
@@@ -3964,7 -3965,7 +3962,7 @@@ If there are no overlay boundaries fro
  the value is (point-min).  */)
    (Lisp_Object pos)
  {
 -  EMACS_INT prevpos;
 +  ptrdiff_t prevpos;
    Lisp_Object *overlay_vec;
    ptrdiff_t len;
  
       Store the length in len.
       prevpos gets the position of the previous change.  */
    overlays_at (XINT (pos), 1, &overlay_vec, &len,
 -             (EMACS_INT *) 0, &prevpos, 1);
 +             0, &prevpos, 1);
  
    xfree (overlay_vec);
    return make_number (prevpos);
@@@ -4020,11 -4021,9 +4018,11 @@@ That makes overlay lookup faster for po
  for positions far away from POS).  */)
    (Lisp_Object pos)
  {
 +  ptrdiff_t p;
    CHECK_NUMBER_COERCE_MARKER (pos);
  
 -  recenter_overlay_lists (current_buffer, XINT (pos));
 +  p = clip_to_bounds (PTRDIFF_MIN, XINT (pos), PTRDIFF_MAX);
 +  recenter_overlay_lists (current_buffer, p);
    return Qnil;
  }
  \f
@@@ -4091,7 -4090,7 +4089,7 @@@ VALUE will be returned.*/
  static Lisp_Object last_overlay_modification_hooks;
  
  /* Number of elements actually used in last_overlay_modification_hooks.  */
 -static int last_overlay_modification_hooks_used;
 +static ptrdiff_t last_overlay_modification_hooks_used;
  
  /* Add one functionlist/overlay pair
     to the end of last_overlay_modification_hooks.  */
  static void
  add_overlay_mod_hooklist (Lisp_Object functionlist, Lisp_Object overlay)
  {
 -  int oldsize = ASIZE (last_overlay_modification_hooks);
 +  ptrdiff_t oldsize = ASIZE (last_overlay_modification_hooks);
  
 -  if (last_overlay_modification_hooks_used == oldsize)
 -    last_overlay_modification_hooks = larger_vector
 -      (last_overlay_modification_hooks, oldsize * 2, Qnil);
 +  if (oldsize - 1 <= last_overlay_modification_hooks_used)
 +    last_overlay_modification_hooks =
 +      larger_vector (last_overlay_modification_hooks, 2, -1);
    ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
        functionlist); last_overlay_modification_hooks_used++;
    ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
@@@ -4152,7 -4151,7 +4150,7 @@@ report_overlay_modification (Lisp_Objec
        last_overlay_modification_hooks_used = 0;
        for (tail = current_buffer->overlays_before; tail; tail = tail->next)
        {
 -        EMACS_INT startpos, endpos;
 +        ptrdiff_t startpos, endpos;
          Lisp_Object ostart, oend;
  
          XSETMISC (overlay, tail);
  
        for (tail = current_buffer->overlays_after; tail; tail = tail->next)
        {
 -        EMACS_INT startpos, endpos;
 +        ptrdiff_t startpos, endpos;
          Lisp_Object ostart, oend;
  
          XSETMISC (overlay, tail);
      /* Call the functions recorded in last_overlay_modification_hooks.
         First copy the vector contents, in case some of these hooks
         do subsequent modification of the buffer.  */
 -    int size = last_overlay_modification_hooks_used;
 +    ptrdiff_t size = last_overlay_modification_hooks_used;
      Lisp_Object *copy = (Lisp_Object *) alloca (size * sizeof (Lisp_Object));
 -    int i;
 +    ptrdiff_t i;
  
      memcpy (copy, XVECTOR (last_overlay_modification_hooks)->contents,
            size * sizeof (Lisp_Object));
@@@ -4272,7 -4271,7 +4270,7 @@@ call_overlay_mod_hooks (Lisp_Object lis
  /* Delete any zero-sized overlays at position POS, if the `evaporate'
     property is set.  */
  void
 -evaporate_overlays (EMACS_INT pos)
 +evaporate_overlays (ptrdiff_t pos)
  {
    Lisp_Object overlay, hit_list;
    struct Lisp_Overlay *tail;
    if (pos <= current_buffer->overlay_center)
      for (tail = current_buffer->overlays_before; tail; tail = tail->next)
        {
 -      EMACS_INT endpos;
 +      ptrdiff_t endpos;
        XSETMISC (overlay, tail);
        endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
        if (endpos < pos)
    else
      for (tail = current_buffer->overlays_after; tail; tail = tail->next)
        {
 -      EMACS_INT startpos;
 +      ptrdiff_t startpos;
        XSETMISC (overlay, tail);
        startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
        if (startpos > pos)
@@@ -4384,7 -4383,7 +4382,7 @@@ struct mmap_regio
    /* Pointer to the location holding the address of the memory
       allocated with the mmap'd block.  The variable actually points
       after this structure.  */
-   POINTER_TYPE **var;
+   void **var;
  
    /* Next and previous in list of all mmap'd regions.  */
    struct mmap_region *next, *prev;
@@@ -4431,7 -4430,7 +4429,7 @@@ static int mmap_initialized_p
     to the start of the user-visible part of the region.  */
  
  #define MMAP_USER_AREA(P) \
-      ((POINTER_TYPE *) ((char *) (P) + MMAP_REGION_STRUCT_SIZE))
+      ((void *) ((char *) (P) + MMAP_REGION_STRUCT_SIZE))
  
  #define MEM_ALIGN     sizeof (double)
  
@@@ -4480,7 -4479,7 +4478,7 @@@ mmap_init (void
     is at END - 1.  */
  
  static struct mmap_region *
- mmap_find (POINTER_TYPE *start, POINTER_TYPE *end)
+ mmap_find (void *start, void *end)
  {
    struct mmap_region *r;
    char *s = (char *) start, *e = (char *) end;
@@@ -4518,7 -4517,7 +4516,7 @@@ mmap_free_1 (struct mmap_region *r
    else
      mmap_regions = r->next;
  
-   if (munmap ((POINTER_TYPE *) r, r->nbytes_mapped) == -1)
+   if (munmap (r, r->nbytes_mapped) == -1)
      {
        fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
        return 0;
@@@ -4560,13 -4559,13 +4558,13 @@@ mmap_enlarge (struct mmap_region *r, in
         I'm not sure this is worth doing, let's see.  */
        if (!MMAP_ALLOCATED_P (region_end, region_end + nbytes))
        {
-         POINTER_TYPE *p;
+         void *p;
  
          p = mmap (region_end, nbytes, PROT_READ | PROT_WRITE,
                    MAP_ANON | MAP_PRIVATE | MAP_FIXED, mmap_fd, 0);
          if (p == MAP_FAILED)
            ; /* fprintf (stderr, "mmap: %s\n", emacs_strerror (errno)); */
-         else if (p != (POINTER_TYPE *) region_end)
+         else if (p != region_end)
            {
              /* Kernels are free to choose a different address.  In
                 that case, unmap what we've mapped above; we have
@@@ -4628,8 -4627,8 +4626,8 @@@ mmap_set_vars (int restore_p
     If we can't allocate the necessary memory, set *VAR to null, and
     return null.  */
  
- static POINTER_TYPE *
- mmap_alloc (POINTER_TYPE **var, size_t nbytes)
+ static void *
+ mmap_alloc (void **var, size_t nbytes)
  {
    void *p;
    size_t map;
     PTR.  Store 0 in *PTR to show there's no block allocated.  */
  
  static void
- mmap_free (POINTER_TYPE **var)
+ mmap_free (void **var)
  {
    mmap_init ();
  
     and return this value.  If more memory cannot be allocated, then
     leave *VAR unchanged, and return null.  */
  
- static POINTER_TYPE *
- mmap_realloc (POINTER_TYPE **var, size_t nbytes)
+ static void *
+ mmap_realloc (void **var, size_t nbytes)
  {
-   POINTER_TYPE *result;
+   void *result;
  
    mmap_init ();
  
        if (room < nbytes)
        {
          /* Must enlarge.  */
-         POINTER_TYPE *old_ptr = *var;
+         void *old_ptr = *var;
  
          /* Try to map additional pages at the end of the region.
             If that fails, allocate a new region,  copy data
  static void
  alloc_buffer_text (struct buffer *b, ptrdiff_t nbytes)
  {
-   POINTER_TYPE *p;
+   void *p;
  
    BLOCK_INPUT;
  #if defined USE_MMAP_FOR_BUFFERS
-   p = mmap_alloc ((POINTER_TYPE **) &b->text->beg, nbytes);
+   p = mmap_alloc ((void **) &b->text->beg, nbytes);
  #elif defined REL_ALLOC
-   p = r_alloc ((POINTER_TYPE **) &b->text->beg, nbytes);
+   p = r_alloc ((void **) &b->text->beg, nbytes);
  #else
    p = xmalloc (nbytes);
  #endif
     shrink it.  */
  
  void
 -enlarge_buffer_text (struct buffer *b, EMACS_INT delta)
 +enlarge_buffer_text (struct buffer *b, ptrdiff_t delta)
  {
-   POINTER_TYPE *p;
+   void *p;
    ptrdiff_t nbytes = (BUF_Z_BYTE (b) - BUF_BEG_BYTE (b) + BUF_GAP_SIZE (b) + 1
                      + delta);
    BLOCK_INPUT;
  #if defined USE_MMAP_FOR_BUFFERS
-   p = mmap_realloc ((POINTER_TYPE **) &b->text->beg, nbytes);
+   p = mmap_realloc ((void **) &b->text->beg, nbytes);
  #elif defined REL_ALLOC
-   p = r_re_alloc ((POINTER_TYPE **) &b->text->beg, nbytes);
+   p = r_re_alloc ((void **) &b->text->beg, nbytes);
  #else
    p = xrealloc (b->text->beg, nbytes);
  #endif
@@@ -4829,9 -4828,9 +4827,9 @@@ free_buffer_text (struct buffer *b
    BLOCK_INPUT;
  
  #if defined USE_MMAP_FOR_BUFFERS
-   mmap_free ((POINTER_TYPE **) &b->text->beg);
+   mmap_free ((void **) &b->text->beg);
  #elif defined REL_ALLOC
-   r_alloc_free ((POINTER_TYPE **) &b->text->beg);
+   r_alloc_free ((void **) &b->text->beg);
  #else
    xfree (b->text->beg);
  #endif
diff --combined src/character.h
@@@ -434,7 -434,7 +434,7 @@@ along with GNU Emacs.  If not, see <htt
          unsigned char *chp = BYTE_POS_ADDR (BYTEIDX);         \
          int chlen;                                            \
                                                                \
-         OUTPUT= STRING_CHAR_AND_LENGTH (chp, chlen);          \
+         OUTPUT = STRING_CHAR_AND_LENGTH (chp, chlen);         \
          BYTEIDX += chlen;                                     \
        }                                                       \
        else                                                    \
@@@ -665,7 -665,7 +665,7 @@@ typedef enum 
    UNICODE_CATEGORY_Cn
  } unicode_category_t;
  
 -extern int char_resolve_modifier_mask (int);
 +extern EMACS_INT char_resolve_modifier_mask (EMACS_INT);
  extern int char_string (unsigned, unsigned char *);
  extern int string_char (const unsigned char *,
                          const unsigned char **, int *);
  extern int translate_char (Lisp_Object, int c);
  extern int char_printable_p (int c);
  extern void parse_str_as_multibyte (const unsigned char *,
 -                                  EMACS_INT, EMACS_INT *, EMACS_INT *);
 -extern EMACS_INT count_size_as_multibyte (const unsigned char *, EMACS_INT);
 -extern EMACS_INT str_as_multibyte (unsigned char *, EMACS_INT, EMACS_INT,
 -                           EMACS_INT *);
 -extern EMACS_INT str_to_multibyte (unsigned char *, EMACS_INT, EMACS_INT);
 -extern EMACS_INT str_as_unibyte (unsigned char *, EMACS_INT);
 -extern EMACS_INT str_to_unibyte (const unsigned char *, unsigned char *,
 -                                 EMACS_INT, int);
 -extern EMACS_INT strwidth (const char *, EMACS_INT);
 -extern EMACS_INT c_string_width (const unsigned char *, EMACS_INT, int,
 -                               EMACS_INT *, EMACS_INT *);
 -extern EMACS_INT lisp_string_width (Lisp_Object, EMACS_INT,
 -                                  EMACS_INT *, EMACS_INT *);
 +                                  ptrdiff_t, ptrdiff_t *, ptrdiff_t *);
 +extern ptrdiff_t count_size_as_multibyte (const unsigned char *, ptrdiff_t);
 +extern ptrdiff_t str_as_multibyte (unsigned char *, ptrdiff_t, ptrdiff_t,
 +                                 ptrdiff_t *);
 +extern ptrdiff_t str_to_multibyte (unsigned char *, ptrdiff_t, ptrdiff_t);
 +extern ptrdiff_t str_as_unibyte (unsigned char *, ptrdiff_t);
 +extern ptrdiff_t str_to_unibyte (const unsigned char *, unsigned char *,
 +                                 ptrdiff_t, int);
 +extern ptrdiff_t strwidth (const char *, ptrdiff_t);
 +extern ptrdiff_t c_string_width (const unsigned char *, ptrdiff_t, int,
 +                               ptrdiff_t *, ptrdiff_t *);
 +extern ptrdiff_t lisp_string_width (Lisp_Object, ptrdiff_t,
 +                                  ptrdiff_t *, ptrdiff_t *);
  
  extern Lisp_Object Qcharacterp;
  extern Lisp_Object Vchar_unify_table;
diff --combined src/data.c
@@@ -51,7 -51,7 +51,7 @@@ along with GNU Emacs.  If not, see <htt
  Lisp_Object Qnil, Qt, Qquote, Qlambda, Qunbound;
  static Lisp_Object Qsubr;
  Lisp_Object Qerror_conditions, Qerror_message, Qtop_level;
- Lisp_Object Qerror, Qquit, Qargs_out_of_range;
+ Lisp_Object Qerror, Quser_error, Qquit, Qargs_out_of_range;
  static Lisp_Object Qwrong_type_argument;
  Lisp_Object Qvoid_variable, Qvoid_function;
  static Lisp_Object Qcyclic_function_indirection;
@@@ -1075,18 -1075,18 +1075,18 @@@ let_shadows_buffer_binding_p (struct Li
  {
    struct specbinding *p;
  
 -  for (p = specpdl_ptr - 1; p >= specpdl; p--)
 -    if (p->func == NULL
 +  for (p = specpdl_ptr; p > specpdl; )
 +    if ((--p)->func == NULL
        && CONSP (p->symbol))
        {
        struct Lisp_Symbol *let_bound_symbol = XSYMBOL (XCAR (p->symbol));
        eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
        if (symbol == let_bound_symbol
            && XBUFFER (XCDR (XCDR (p->symbol))) == current_buffer)
 -        break;
 +        return 1;
        }
  
 -  return p >= specpdl;
 +  return 0;
  }
  
  static int
@@@ -1094,11 -1094,11 +1094,11 @@@ let_shadows_global_binding_p (Lisp_Obje
  {
    struct specbinding *p;
  
 -  for (p = specpdl_ptr - 1; p >= specpdl; p--)
 -    if (p->func == NULL && EQ (p->symbol, symbol))
 -      break;
 +  for (p = specpdl_ptr; p > specpdl; )
 +    if ((--p)->func == NULL && EQ (p->symbol, symbol))
 +      return 1;
  
 -  return p >= specpdl;
 +  return 0;
  }
  
  /* Store the value NEWVAL into SYMBOL.
@@@ -2064,7 -2064,7 +2064,7 @@@ or a byte-code object.  IDX starts at 0
    if (STRINGP (array))
      {
        int c;
 -      EMACS_INT idxval_byte;
 +      ptrdiff_t idxval_byte;
  
        if (idxval < 0 || idxval >= SCHARS (array))
        args_out_of_range (array, idx);
      }
    else
      {
 -      int size = 0;
 +      ptrdiff_t size = 0;
        if (VECTORP (array))
        size = ASIZE (array);
        else if (COMPILEDP (array))
@@@ -2156,8 -2156,7 +2156,8 @@@ bool-vector.  IDX starts at 0.  */
  
        if (STRING_MULTIBYTE (array))
        {
 -        EMACS_INT idxval_byte, prev_bytes, new_bytes, nbytes;
 +        ptrdiff_t idxval_byte, nbytes;
 +        int prev_bytes, new_bytes;
          unsigned char workbuf[MAX_MULTIBYTE_LENGTH], *p0 = workbuf, *p1;
  
          nbytes = SBYTES (array);
          if (prev_bytes != new_bytes)
            {
              /* We must relocate the string data.  */
 -            EMACS_INT nchars = SCHARS (array);
 +            ptrdiff_t nchars = SCHARS (array);
              unsigned char *str;
              USE_SAFE_ALLOCA;
  
@@@ -2475,9 -2474,9 +2475,9 @@@ If the base used is not 10, STRING is a
    else
      {
        CHECK_NUMBER (base);
 -      b = XINT (base);
 -      if (b < 2 || b > 16)
 +      if (! (2 <= XINT (base) && XINT (base) <= 16))
        xsignal1 (Qargs_out_of_range, base);
 +      b = XINT (base);
      }
  
    p = SSDATA (string);
@@@ -2725,7 -2724,7 +2725,7 @@@ Both must be integers or markers.  */
    CHECK_NUMBER_COERCE_MARKER (x);
    CHECK_NUMBER_COERCE_MARKER (y);
  
 -  if (XFASTINT (y) == 0)
 +  if (XINT (y) == 0)
      xsignal0 (Qarith_error);
  
    XSETINT (val, XINT (x) % XINT (y));
@@@ -2938,6 -2937,7 +2938,7 @@@ syms_of_data (void
    DEFSYM (Qtop_level, "top-level");
  
    DEFSYM (Qerror, "error");
+   DEFSYM (Quser_error, "user-error");
    DEFSYM (Qquit, "quit");
    DEFSYM (Qwrong_type_argument, "wrong-type-argument");
    DEFSYM (Qargs_out_of_range, "args-out-of-range");
    Fput (Qerror, Qerror_message,
        make_pure_c_string ("error"));
  
-   Fput (Qquit, Qerror_conditions,
-       pure_cons (Qquit, Qnil));
-   Fput (Qquit, Qerror_message,
-       make_pure_c_string ("Quit"));
-   Fput (Qwrong_type_argument, Qerror_conditions,
-       pure_cons (Qwrong_type_argument, error_tail));
-   Fput (Qwrong_type_argument, Qerror_message,
-       make_pure_c_string ("Wrong type argument"));
-   Fput (Qargs_out_of_range, Qerror_conditions,
-       pure_cons (Qargs_out_of_range, error_tail));
-   Fput (Qargs_out_of_range, Qerror_message,
-       make_pure_c_string ("Args out of range"));
-   Fput (Qvoid_function, Qerror_conditions,
-       pure_cons (Qvoid_function, error_tail));
-   Fput (Qvoid_function, Qerror_message,
-       make_pure_c_string ("Symbol's function definition is void"));
-   Fput (Qcyclic_function_indirection, Qerror_conditions,
-       pure_cons (Qcyclic_function_indirection, error_tail));
-   Fput (Qcyclic_function_indirection, Qerror_message,
-       make_pure_c_string ("Symbol's chain of function indirections contains a loop"));
-   Fput (Qcyclic_variable_indirection, Qerror_conditions,
-       pure_cons (Qcyclic_variable_indirection, error_tail));
-   Fput (Qcyclic_variable_indirection, Qerror_message,
-       make_pure_c_string ("Symbol's chain of variable indirections contains a loop"));
+ #define PUT_ERROR(sym, tail, msg)                     \
+   Fput (sym, Qerror_conditions, pure_cons (sym, tail)); \
+   Fput (sym, Qerror_message, make_pure_c_string (msg))
+   PUT_ERROR (Qquit, Qnil, "Quit");
+   PUT_ERROR (Quser_error, error_tail, "");
+   PUT_ERROR (Qwrong_type_argument, error_tail, "Wrong type argument");
+   PUT_ERROR (Qargs_out_of_range, error_tail, "Args out of range");
+   PUT_ERROR (Qvoid_function, error_tail,
+            "Symbol's function definition is void");
+   PUT_ERROR (Qcyclic_function_indirection, error_tail,
+            "Symbol's chain of function indirections contains a loop");
+   PUT_ERROR (Qcyclic_variable_indirection, error_tail,
+            "Symbol's chain of variable indirections contains a loop");
    DEFSYM (Qcircular_list, "circular-list");
-   Fput (Qcircular_list, Qerror_conditions,
-       pure_cons (Qcircular_list, error_tail));
-   Fput (Qcircular_list, Qerror_message,
-       make_pure_c_string ("List contains a loop"));
-   Fput (Qvoid_variable, Qerror_conditions,
-       pure_cons (Qvoid_variable, error_tail));
-   Fput (Qvoid_variable, Qerror_message,
-       make_pure_c_string ("Symbol's value as variable is void"));
-   Fput (Qsetting_constant, Qerror_conditions,
-       pure_cons (Qsetting_constant, error_tail));
-   Fput (Qsetting_constant, Qerror_message,
-       make_pure_c_string ("Attempt to set a constant symbol"));
-   Fput (Qinvalid_read_syntax, Qerror_conditions,
-       pure_cons (Qinvalid_read_syntax, error_tail));
-   Fput (Qinvalid_read_syntax, Qerror_message,
-       make_pure_c_string ("Invalid read syntax"));
-   Fput (Qinvalid_function, Qerror_conditions,
-       pure_cons (Qinvalid_function, error_tail));
-   Fput (Qinvalid_function, Qerror_message,
-       make_pure_c_string ("Invalid function"));
-   Fput (Qwrong_number_of_arguments, Qerror_conditions,
-       pure_cons (Qwrong_number_of_arguments, error_tail));
-   Fput (Qwrong_number_of_arguments, Qerror_message,
-       make_pure_c_string ("Wrong number of arguments"));
-   Fput (Qno_catch, Qerror_conditions,
-       pure_cons (Qno_catch, error_tail));
-   Fput (Qno_catch, Qerror_message,
-       make_pure_c_string ("No catch for tag"));
-   Fput (Qend_of_file, Qerror_conditions,
-       pure_cons (Qend_of_file, error_tail));
-   Fput (Qend_of_file, Qerror_message,
-       make_pure_c_string ("End of file during parsing"));
+   PUT_ERROR (Qcircular_list, error_tail, "List contains a loop");
+   PUT_ERROR (Qvoid_variable, error_tail, "Symbol's value as variable is void");
+   PUT_ERROR (Qsetting_constant, error_tail,
+            "Attempt to set a constant symbol");
+   PUT_ERROR (Qinvalid_read_syntax, error_tail, "Invalid read syntax");
+   PUT_ERROR (Qinvalid_function, error_tail, "Invalid function");
+   PUT_ERROR (Qwrong_number_of_arguments, error_tail,
+            "Wrong number of arguments");
+   PUT_ERROR (Qno_catch, error_tail, "No catch for tag");
+   PUT_ERROR (Qend_of_file, error_tail, "End of file during parsing");
  
    arith_tail = pure_cons (Qarith_error, error_tail);
-   Fput (Qarith_error, Qerror_conditions,
-       arith_tail);
-   Fput (Qarith_error, Qerror_message,
-       make_pure_c_string ("Arithmetic error"));
-   Fput (Qbeginning_of_buffer, Qerror_conditions,
-       pure_cons (Qbeginning_of_buffer, error_tail));
-   Fput (Qbeginning_of_buffer, Qerror_message,
-       make_pure_c_string ("Beginning of buffer"));
-   Fput (Qend_of_buffer, Qerror_conditions,
-       pure_cons (Qend_of_buffer, error_tail));
-   Fput (Qend_of_buffer, Qerror_message,
-       make_pure_c_string ("End of buffer"));
-   Fput (Qbuffer_read_only, Qerror_conditions,
-       pure_cons (Qbuffer_read_only, error_tail));
-   Fput (Qbuffer_read_only, Qerror_message,
-       make_pure_c_string ("Buffer is read-only"));
-   Fput (Qtext_read_only, Qerror_conditions,
-       pure_cons (Qtext_read_only, error_tail));
-   Fput (Qtext_read_only, Qerror_message,
-       make_pure_c_string ("Text is read-only"));
+   Fput (Qarith_error, Qerror_conditions, arith_tail);
+   Fput (Qarith_error, Qerror_message, make_pure_c_string ("Arithmetic error"));
+   PUT_ERROR (Qbeginning_of_buffer, error_tail, "Beginning of buffer");
+   PUT_ERROR (Qend_of_buffer, error_tail, "End of buffer");
+   PUT_ERROR (Qbuffer_read_only, error_tail, "Buffer is read-only");
+   PUT_ERROR (Qtext_read_only, pure_cons (Qbuffer_read_only, error_tail),
+            "Text is read-only");
  
    DEFSYM (Qrange_error, "range-error");
    DEFSYM (Qdomain_error, "domain-error");
    DEFSYM (Qoverflow_error, "overflow-error");
    DEFSYM (Qunderflow_error, "underflow-error");
  
-   Fput (Qdomain_error, Qerror_conditions,
-       pure_cons (Qdomain_error, arith_tail));
-   Fput (Qdomain_error, Qerror_message,
-       make_pure_c_string ("Arithmetic domain error"));
-   Fput (Qrange_error, Qerror_conditions,
-       pure_cons (Qrange_error, arith_tail));
-   Fput (Qrange_error, Qerror_message,
-       make_pure_c_string ("Arithmetic range error"));
-   Fput (Qsingularity_error, Qerror_conditions,
-       pure_cons (Qsingularity_error, Fcons (Qdomain_error, arith_tail)));
-   Fput (Qsingularity_error, Qerror_message,
-       make_pure_c_string ("Arithmetic singularity error"));
-   Fput (Qoverflow_error, Qerror_conditions,
-       pure_cons (Qoverflow_error, Fcons (Qdomain_error, arith_tail)));
-   Fput (Qoverflow_error, Qerror_message,
-       make_pure_c_string ("Arithmetic overflow error"));
-   Fput (Qunderflow_error, Qerror_conditions,
-       pure_cons (Qunderflow_error, Fcons (Qdomain_error, arith_tail)));
-   Fput (Qunderflow_error, Qerror_message,
-       make_pure_c_string ("Arithmetic underflow error"));
+   PUT_ERROR (Qdomain_error, arith_tail, "Arithmetic domain error");
+   PUT_ERROR (Qrange_error, arith_tail, "Arithmetic range error");
+   PUT_ERROR (Qsingularity_error, Fcons (Qdomain_error, arith_tail),
+            "Arithmetic singularity error");
+   PUT_ERROR (Qoverflow_error, Fcons (Qdomain_error, arith_tail),
+            "Arithmetic overflow error");
+   PUT_ERROR (Qunderflow_error, Fcons (Qdomain_error, arith_tail),
+            "Arithmetic underflow error");
  
    staticpro (&Qnil);
    staticpro (&Qt);
diff --combined src/dbusbind.c
@@@ -28,19 -28,15 +28,15 @@@ along with GNU Emacs.  If not, see <htt
  #include "keyboard.h"
  #include "process.h"
  
+ #ifndef DBUS_NUM_MESSAGE_TYPES
+ #define DBUS_NUM_MESSAGE_TYPES 5
+ #endif
  \f
  /* Subroutines.  */
  static Lisp_Object Qdbus_init_bus;
- static Lisp_Object Qdbus_close_bus;
  static Lisp_Object Qdbus_get_unique_name;
- static Lisp_Object Qdbus_call_method;
- static Lisp_Object Qdbus_call_method_asynchronously;
- static Lisp_Object Qdbus_method_return_internal;
- static Lisp_Object Qdbus_method_error_internal;
- static Lisp_Object Qdbus_send_signal;
- static Lisp_Object Qdbus_register_service;
- static Lisp_Object Qdbus_register_signal;
- static Lisp_Object Qdbus_register_method;
+ static Lisp_Object Qdbus_message_internal;
  
  /* D-Bus error symbol.  */
  static Lisp_Object Qdbus_error;
@@@ -51,17 -47,6 +47,6 @@@ static Lisp_Object QCdbus_system_bus, Q
  /* Lisp symbol for method call timeout.  */
  static Lisp_Object QCdbus_timeout;
  
- /* Lisp symbols for name request flags.  */
- static Lisp_Object QCdbus_request_name_allow_replacement;
- static Lisp_Object QCdbus_request_name_replace_existing;
- static Lisp_Object QCdbus_request_name_do_not_queue;
- /* Lisp symbols for name request replies.  */
- static Lisp_Object QCdbus_request_name_reply_primary_owner;
- static Lisp_Object QCdbus_request_name_reply_in_queue;
- static Lisp_Object QCdbus_request_name_reply_exists;
- static Lisp_Object QCdbus_request_name_reply_already_owner;
  /* Lisp symbols of D-Bus types.  */
  static Lisp_Object QCdbus_type_byte, QCdbus_type_boolean;
  static Lisp_Object QCdbus_type_int16, QCdbus_type_uint16;
@@@ -75,6 -60,15 +60,15 @@@ static Lisp_Object QCdbus_type_unix_fd
  static Lisp_Object QCdbus_type_array, QCdbus_type_variant;
  static Lisp_Object QCdbus_type_struct, QCdbus_type_dict_entry;
  
+ /* Lisp symbols of objects in `dbus-registered-objects-table'.  */
+ static Lisp_Object QCdbus_registered_serial, QCdbus_registered_method;
+ static Lisp_Object QCdbus_registered_signal;
+ /* Alist of D-Bus buses we are polling for messages.
+    The key is the symbol or string of the bus, and the value is the
+    connection address.  */
+ static Lisp_Object xd_registered_buses;
  /* Whether we are reading a D-Bus event.  */
  static int xd_in_read_queued_messages = 0;
  
    } while (0)
  
  /* Macros for debugging.  In order to enable them, build with
-    "MYCPPFLAGS='-DDBUS_DEBUG -Wall' make".  */
+    "env MYCPPFLAGS='-DDBUS_DEBUG -Wall' make".  */
  #ifdef DBUS_DEBUG
- #define XD_DEBUG_MESSAGE(...)         \
-   do {                                        \
-     char s[1024];                     \
-     snprintf (s, sizeof s, __VA_ARGS__); \
-     printf ("%s: %s\n", __func__, s); \
-     message ("%s: %s", __func__, s);  \
+ #define XD_DEBUG_MESSAGE(...)                                         \
+   do {                                                                        \
+     char s[1024];                                                     \
+     snprintf (s, sizeof s, __VA_ARGS__);                              \
+     if (!noninteractive)                                              \
+       printf ("%s: %s\n", __func__, s);                                       \
+     message ("%s: %s", __func__, s);                                  \
    } while (0)
  #define XD_DEBUG_VALID_LISP_OBJECT_P(object)                          \
    do {                                                                        \
      if (!NILP (Vdbus_debug))                                          \
        {                                                                       \
        char s[1024];                                                   \
-       snprintf (s, 1023, __VA_ARGS__);                                \
+       snprintf (s, sizeof s, __VA_ARGS__);                            \
        message ("%s: %s", __func__, s);                                \
        }                                                                       \
    } while (0)
@@@ -241,23 -236,115 +236,115 @@@ xd_symbol_to_dbus_type (Lisp_Object obj
  #define XD_NEXT_VALUE(object)                                         \
    ((XD_DBUS_TYPE_P (CAR_SAFE (object))) ? CDR_SAFE (object) : object)
  
+ /* Transform the message type to its string representation for debug
+    messages.  */
+ #define XD_MESSAGE_TYPE_TO_STRING(mtype)                              \
+   ((mtype == DBUS_MESSAGE_TYPE_INVALID)                                       \
+   ? "DBUS_MESSAGE_TYPE_INVALID"                                               \
+   : (mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)                          \
+   ? "DBUS_MESSAGE_TYPE_METHOD_CALL"                                   \
+   : (mtype == DBUS_MESSAGE_TYPE_METHOD_RETURN)                                \
+   ? "DBUS_MESSAGE_TYPE_METHOD_RETURN"                                 \
+   : (mtype == DBUS_MESSAGE_TYPE_ERROR)                                        \
+    ? "DBUS_MESSAGE_TYPE_ERROR"                                                \
+    : "DBUS_MESSAGE_TYPE_SIGNAL")
+ /* Transform the object to its string representation for debug
+    messages.  */
+ #define XD_OBJECT_TO_STRING(object)                                   \
+   SDATA (format2 ("%s", object, Qnil))
  /* Check whether X is a valid dbus serial number.  If valid, set
     SERIAL to its value.  Otherwise, signal an error. */
- #define CHECK_DBUS_SERIAL_GET_SERIAL(x, serial)                               \
-   do                                                                  \
-     {                                                                 \
-       dbus_uint32_t DBUS_SERIAL_MAX = -1;                             \
-       if (NATNUMP (x) && XINT (x) <= DBUS_SERIAL_MAX)                 \
-       serial = XINT (x);                                              \
-       else if (MOST_POSITIVE_FIXNUM < DBUS_SERIAL_MAX                 \
-              && FLOATP (x)                                            \
-              && 0 <= XFLOAT_DATA (x)                                  \
-              && XFLOAT_DATA (x) <= DBUS_SERIAL_MAX)                   \
-       serial = XFLOAT_DATA (x);                                       \
-       else                                                            \
-       XD_SIGNAL2 (build_string ("Invalid dbus serial"), x);           \
-     }                                                                 \
-   while (0)
+ #define XD_CHECK_DBUS_SERIAL(x, serial)                                       \
+   do {                                                                        \
+     dbus_uint32_t DBUS_SERIAL_MAX = -1;                                       \
+     if (NATNUMP (x) && XINT (x) <= DBUS_SERIAL_MAX)                   \
+       serial = XINT (x);                                              \
+     else if (MOST_POSITIVE_FIXNUM < DBUS_SERIAL_MAX                   \
+            && FLOATP (x)                                              \
+            && 0 <= XFLOAT_DATA (x)                                    \
+            && XFLOAT_DATA (x) <= DBUS_SERIAL_MAX)                     \
+       serial = XFLOAT_DATA (x);                                               \
+     else                                                              \
+       XD_SIGNAL2 (build_string ("Invalid dbus serial"), x);           \
+   } while (0)
+ #define XD_DBUS_VALIDATE_BUS_ADDRESS(bus)                             \
+   do {                                                                        \
+     if (STRINGP (bus))                                                        \
+       {                                                                       \
+       DBusAddressEntry **entries;                                     \
+       int len;                                                        \
+       DBusError derror;                                               \
+       dbus_error_init (&derror);                                      \
+       if (!dbus_parse_address (SSDATA (bus), &entries, &len, &derror)) \
+         XD_ERROR (derror);                                            \
+       /* Cleanup.  */                                                 \
+       dbus_error_free (&derror);                                      \
+       dbus_address_entries_free (entries);                            \
+       }                                                                       \
+                                                                       \
+     else                                                              \
+       {                                                                       \
+       CHECK_SYMBOL (bus);                                             \
+       if (!(EQ (bus, QCdbus_system_bus) || EQ (bus, QCdbus_session_bus))) \
+         XD_SIGNAL2 (build_string ("Wrong bus name"), bus);            \
+       /* We do not want to have an autolaunch for the session bus.  */ \
+       if (EQ (bus, QCdbus_session_bus)                                \
+           && getenv ("DBUS_SESSION_BUS_ADDRESS") == NULL)             \
+         XD_SIGNAL2 (build_string ("No connection to bus"), bus);      \
+       }                                                                       \
+   } while (0)
+ #if (HAVE_DBUS_VALIDATE_BUS_NAME || HAVE_DBUS_VALIDATE_PATH \
+      || XD_DBUS_VALIDATE_OBJECT || HAVE_DBUS_VALIDATE_MEMBER)
+ #define XD_DBUS_VALIDATE_OBJECT(object, func)                         \
+   do {                                                                        \
+     if (!NILP (object))                                                       \
+       {                                                                       \
+       DBusError derror;                                               \
+       CHECK_STRING (object);                                          \
+       dbus_error_init (&derror);                                      \
+       if (!func (SSDATA (object), &derror))                           \
+         XD_ERROR (derror);                                            \
+       /* Cleanup.  */                                                 \
+       dbus_error_free (&derror);                                      \
+       }                                                                       \
+   } while (0)
+ #endif
+ #if HAVE_DBUS_VALIDATE_BUS_NAME
+ #define XD_DBUS_VALIDATE_BUS_NAME(bus_name)                           \
+   XD_DBUS_VALIDATE_OBJECT(bus_name, dbus_validate_bus_name);
+ #else
+ #define XD_DBUS_VALIDATE_BUS_NAME(bus_name)                           \
+   if (!NILP (bus_name)) CHECK_STRING (bus_name);
+ #endif
+ #if HAVE_DBUS_VALIDATE_PATH
+ #define XD_DBUS_VALIDATE_PATH(path)                                   \
+   XD_DBUS_VALIDATE_OBJECT(path, dbus_validate_path);
+ #else
+ #define XD_DBUS_VALIDATE_PATH(path)                                   \
+   if (!NILP (path)) CHECK_STRING (path);
+ #endif
+ #if HAVE_DBUS_VALIDATE_INTERFACE
+ #define XD_DBUS_VALIDATE_INTERFACE(interface)                         \
+   XD_DBUS_VALIDATE_OBJECT(interface, dbus_validate_interface);
+ #else
+ #define XD_DBUS_VALIDATE_INTERFACE(interface)                         \
+   if (!NILP (interface)) CHECK_STRING (interface);
+ #endif
+ #if HAVE_DBUS_VALIDATE_MEMBER
+ #define XD_DBUS_VALIDATE_MEMBER(member)                                       \
+   XD_DBUS_VALIDATE_OBJECT(member, dbus_validate_member);
+ #else
+ #define XD_DBUS_VALIDATE_MEMBER(member)                                       \
+   if (!NILP (member)) CHECK_STRING (member);
+ #endif
  
  /* Append to SIGNATURE a copy of X, making sure SIGNATURE does
     not become too long.  */
@@@ -293,11 -380,6 +380,6 @@@ xd_signature (char *signature, unsigne
      {
      case DBUS_TYPE_BYTE:
      case DBUS_TYPE_UINT16:
-     case DBUS_TYPE_UINT32:
-     case DBUS_TYPE_UINT64:
- #ifdef DBUS_TYPE_UNIX_FD
-     case DBUS_TYPE_UNIX_FD:
- #endif
        CHECK_NATNUM (object);
        sprintf (signature, "%c", dtype);
        break;
        break;
  
      case DBUS_TYPE_INT16:
-     case DBUS_TYPE_INT32:
-     case DBUS_TYPE_INT64:
        CHECK_NUMBER (object);
        sprintf (signature, "%c", dtype);
        break;
  
+     case DBUS_TYPE_UINT32:
+     case DBUS_TYPE_UINT64:
+ #ifdef DBUS_TYPE_UNIX_FD
+     case DBUS_TYPE_UNIX_FD:
+ #endif
+     case DBUS_TYPE_INT32:
+     case DBUS_TYPE_INT64:
      case DBUS_TYPE_DOUBLE:
-       CHECK_FLOAT (object);
+       CHECK_NUMBER_OR_FLOAT (object);
        sprintf (signature, "%c", dtype);
        break;
  
        }
  
        /* If the element type is DBUS_TYPE_SIGNATURE, and this is the
-        only element, the value of this element is used as he array's
-        element signature.  */
+        only element, the value of this element is used as the
+        array's element signature.  */
        if ((subtype == DBUS_TYPE_SIGNATURE)
          && STRINGP (CAR_SAFE (XD_NEXT_VALUE (elt)))
          && NILP (CDR_SAFE (XD_NEXT_VALUE (elt))))
    XD_DEBUG_MESSAGE ("%s", signature);
  }
  
++/* Convert X to a signed integer with bounds LO and HI.  */
++static intmax_t
++extract_signed (Lisp_Object x, intmax_t lo, intmax_t hi)
++{
++  CHECK_NUMBER_OR_FLOAT (x);
++  if (INTEGERP (x))
++    {
++      if (lo <= XINT (x) && XINT (x) <= hi)
++      return XINT (x);
++    }
++  else
++    {
++      double d = XFLOAT_DATA (x);
++      if (lo <= d && d <= hi)
++      {
++        intmax_t n = d;
++        if (n == d)
++          return n;
++      }
++    }
++  args_out_of_range_3 (x,
++                     make_fixnum_or_float (lo),
++                     make_fixnum_or_float (hi));
++}
++
++/* Convert X to an unsigned integer with bounds 0 and HI.  */
++static uintmax_t
++extract_unsigned (Lisp_Object x, uintmax_t hi)
++{
++  CHECK_NUMBER_OR_FLOAT (x);
++  if (INTEGERP (x))
++    {
++      if (0 <= XINT (x) && XINT (x) <= hi)
++      return XINT (x);
++    }
++  else
++    {
++      double d = XFLOAT_DATA (x);
++      if (0 <= d && d <= hi)
++      {
++        uintmax_t n = d;
++        if (n == d)
++          return n;
++      }
++    }
++  args_out_of_range_2 (x, make_fixnum_or_float (hi));
++}
++
  /* Append C value, extracted from Lisp OBJECT, to iteration ITER.
     DTYPE must be a valid DBusType.  It is used to convert Lisp
     objects, being arguments of `dbus-call-method' or
@@@ -469,7 -556,7 +604,7 @@@ xd_append_arg (unsigned int dtype, Lisp
        CHECK_NATNUM (object);
        {
          unsigned char val = XFASTINT (object) & 0xFF;
-         XD_DEBUG_MESSAGE ("%c %d", dtype, val);
+         XD_DEBUG_MESSAGE ("%c %u", dtype, val);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
        }
  
        case DBUS_TYPE_INT16:
 -      CHECK_NUMBER (object);
 +      CHECK_TYPE_RANGED_INTEGER (dbus_int16_t, object);
        {
          dbus_int16_t val = XINT (object);
-         XD_DEBUG_MESSAGE ("%c %d", dtype, (int) val);
+         int pval = val;
+         XD_DEBUG_MESSAGE ("%c %d", dtype, pval);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
        }
  
        case DBUS_TYPE_UINT16:
 -      CHECK_NATNUM (object);
 +      CHECK_TYPE_RANGED_INTEGER (dbus_uint16_t, object);
        {
          dbus_uint16_t val = XFASTINT (object);
-         XD_DEBUG_MESSAGE ("%c %u", dtype, (unsigned int) val);
+         unsigned int pval = val;
+         XD_DEBUG_MESSAGE ("%c %u", dtype, pval);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
        }
  
        case DBUS_TYPE_INT32:
-       CHECK_TYPE_RANGED_INTEGER (dbus_int32_t, object);
        {
-         dbus_int32_t val = XINT (object);
-         XD_DEBUG_MESSAGE ("%c %d", dtype, val);
 -        dbus_int32_t val = extract_float (object);
++        dbus_int32_t val = extract_signed (object,
++                                           TYPE_MINIMUM (dbus_int32_t),
++                                           TYPE_MAXIMUM (dbus_int32_t));
+         int pval = val;
+         XD_DEBUG_MESSAGE ("%c %d", dtype, pval);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
  #ifdef DBUS_TYPE_UNIX_FD
        case DBUS_TYPE_UNIX_FD:
  #endif
-       CHECK_TYPE_RANGED_INTEGER (dbus_uint32_t, object);
        {
-         dbus_uint32_t val = XFASTINT (object);
-         XD_DEBUG_MESSAGE ("%c %u", dtype, val);
 -        dbus_uint32_t val = extract_float (object);
++        dbus_uint32_t val = extract_unsigned (object,
++                                              TYPE_MAXIMUM (dbus_uint32_t));
+         unsigned int pval = val;
+         XD_DEBUG_MESSAGE ("%c %u", dtype, pval);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
        }
  
        case DBUS_TYPE_INT64:
-       CHECK_NUMBER (object);
++      CHECK_TYPE_RANGED_INTEGER_OR_FLOAT (dbus_int64_t, object);
        {
-         dbus_int64_t val = XINT (object);
-         XD_DEBUG_MESSAGE ("%c %d", dtype, (int) val);
 -        dbus_int64_t val = extract_float (object);
++        dbus_int64_t val = extract_signed (object,
++                                           TYPE_MINIMUM (dbus_int64_t),
++                                           TYPE_MAXIMUM (dbus_int64_t));
+         printmax_t pval = val;
+         XD_DEBUG_MESSAGE ("%c %"pMd, dtype, pval);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
        }
  
        case DBUS_TYPE_UINT64:
-       CHECK_TYPE_RANGED_INTEGER (dbus_uint64_t, object);
        {
-         dbus_uint64_t val = XFASTINT (object);
-         XD_DEBUG_MESSAGE ("%c %"pI"d", dtype, XFASTINT (object));
 -        dbus_uint64_t val = extract_float (object);
++        dbus_uint64_t val = extract_unsigned (object,
++                                              TYPE_MAXIMUM (dbus_uint64_t));
+         uprintmax_t pval = val;
+         XD_DEBUG_MESSAGE ("%c %"pMu, dtype, pval);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
          return;
        }
  
        case DBUS_TYPE_DOUBLE:
-       CHECK_FLOAT (object);
        {
-         double val = XFLOAT_DATA (object);
+         double val = extract_float (object);
          XD_DEBUG_MESSAGE ("%c %f", dtype, val);
          if (!dbus_message_iter_append_basic (iter, dtype, &val))
            XD_SIGNAL2 (build_string ("Unable to append argument"), object);
                            dtype, CAR_SAFE (XD_NEXT_VALUE (object)));
  
          XD_DEBUG_MESSAGE ("%c %s %s", dtype, signature,
-                           SDATA (format2 ("%s", object, Qnil)));
+                           XD_OBJECT_TO_STRING (object));
          if (!dbus_message_iter_open_container (iter, dtype,
                                                 signature, &subiter))
            XD_SIGNAL3 (build_string ("Cannot open container"),
                        dtype, CAR_SAFE (XD_NEXT_VALUE (object)));
  
          XD_DEBUG_MESSAGE ("%c %s %s", dtype, signature,
-                           SDATA (format2 ("%s", object, Qnil)));
+                           XD_OBJECT_TO_STRING (object));
          if (!dbus_message_iter_open_container (iter, dtype,
                                                 signature, &subiter))
            XD_SIGNAL3 (build_string ("Cannot open container"),
        case DBUS_TYPE_STRUCT:
        case DBUS_TYPE_DICT_ENTRY:
          /* These containers do not require a signature.  */
-         XD_DEBUG_MESSAGE ("%c %s", dtype,
-                           SDATA (format2 ("%s", object, Qnil)));
+         XD_DEBUG_MESSAGE ("%c %s", dtype, XD_OBJECT_TO_STRING (object));
          if (!dbus_message_iter_open_container (iter, dtype, NULL, &subiter))
            XD_SIGNAL2 (build_string ("Cannot open container"),
                        make_number (dtype));
@@@ -678,7 -765,7 +820,7 @@@ xd_retrieve_arg (unsigned int dtype, DB
        unsigned int val;
        dbus_message_iter_get_basic (iter, &val);
        val = val & 0xFF;
-       XD_DEBUG_MESSAGE ("%c %d", dtype, val);
+       XD_DEBUG_MESSAGE ("%c %u", dtype, val);
        return make_number (val);
        }
  
      case DBUS_TYPE_INT16:
        {
        dbus_int16_t val;
+       int pval;
        dbus_message_iter_get_basic (iter, &val);
-       XD_DEBUG_MESSAGE ("%c %d", dtype, val);
+       pval = val;
+       XD_DEBUG_MESSAGE ("%c %d", dtype, pval);
        return make_number (val);
        }
  
      case DBUS_TYPE_UINT16:
        {
        dbus_uint16_t val;
+       int pval;
        dbus_message_iter_get_basic (iter, &val);
-       XD_DEBUG_MESSAGE ("%c %d", dtype, val);
+       pval = val;
+       XD_DEBUG_MESSAGE ("%c %d", dtype, pval);
        return make_number (val);
        }
  
      case DBUS_TYPE_INT32:
        {
        dbus_int32_t val;
+       int pval;
        dbus_message_iter_get_basic (iter, &val);
-       XD_DEBUG_MESSAGE ("%c %d", dtype, val);
+       pval = val;
+       XD_DEBUG_MESSAGE ("%c %d", dtype, pval);
        return make_fixnum_or_float (val);
        }
  
  #endif
        {
        dbus_uint32_t val;
+       unsigned int pval = val;
        dbus_message_iter_get_basic (iter, &val);
-       XD_DEBUG_MESSAGE ("%c %d", dtype, val);
+       pval = val;
+       XD_DEBUG_MESSAGE ("%c %u", dtype, pval);
        return make_fixnum_or_float (val);
        }
  
      case DBUS_TYPE_INT64:
        {
        dbus_int64_t val;
+       printmax_t pval;
        dbus_message_iter_get_basic (iter, &val);
-       XD_DEBUG_MESSAGE ("%c %d", dtype, (int) val);
+       pval = val;
+       XD_DEBUG_MESSAGE ("%c %"pMd, dtype, pval);
        return make_fixnum_or_float (val);
        }
  
      case DBUS_TYPE_UINT64:
        {
        dbus_uint64_t val;
+       uprintmax_t pval;
        dbus_message_iter_get_basic (iter, &val);
-       XD_DEBUG_MESSAGE ("%c %d", dtype, (int) val);
+       pval = val;
+       XD_DEBUG_MESSAGE ("%c %"pMd, dtype, pval);
        return make_fixnum_or_float (val);
        }
  
            result = Fcons (xd_retrieve_arg (subtype, &subiter), result);
            dbus_message_iter_next (&subiter);
          }
-       XD_DEBUG_MESSAGE ("%c %s", dtype, SDATA (format2 ("%s", result, Qnil)));
+       XD_DEBUG_MESSAGE ("%c %s", dtype, XD_OBJECT_TO_STRING (result));
        RETURN_UNGCPRO (Fnreverse (result));
        }
  
      }
  }
  
- /* Initialize D-Bus connection.  BUS is either a Lisp symbol, :system
-    or :session, or a string denoting the bus address.  It tells which
-    D-Bus to initialize.  If RAISE_ERROR is non-zero, signal an error
-    when the connection cannot be initialized.  */
+ /* Return the number of references of the shared CONNECTION.  */
+ static int
+ xd_get_connection_references (DBusConnection *connection)
+ {
+   ptrdiff_t *refcount;
+   /* We cannot access the DBusConnection structure, it is not public.
+      But we know, that the reference counter is the first field in
+      that structure.  */
+   refcount = (void *) &connection;
+   refcount =  (void *) *refcount;
+   return *refcount;
+ }
+ /* Return D-Bus connection address.  BUS is either a Lisp symbol,
+    :system or :session, or a string denoting the bus address.  */
  static DBusConnection *
- xd_initialize (Lisp_Object bus, int raise_error)
+ xd_get_connection_address (Lisp_Object bus)
  {
    DBusConnection *connection;
-   DBusError derror;
+   Lisp_Object val;
  
-   /* Parameter check.  */
-   if (!STRINGP (bus))
-     {
-       CHECK_SYMBOL (bus);
-       if (!(EQ (bus, QCdbus_system_bus) || EQ (bus, QCdbus_session_bus)))
-       {
-         if (raise_error)
-           XD_SIGNAL2 (build_string ("Wrong bus name"), bus);
-         else
-           return NULL;
-       }
-       /* We do not want to have an autolaunch for the session bus.  */
-       if (EQ (bus, QCdbus_session_bus)
-         && getenv ("DBUS_SESSION_BUS_ADDRESS") == NULL)
-       {
-         if (raise_error)
-           XD_SIGNAL2 (build_string ("No connection to bus"), bus);
-         else
-           return NULL;
-       }
-     }
-   /* Open a connection to the bus.  */
-   dbus_error_init (&derror);
-   if (STRINGP (bus))
-       connection = dbus_connection_open (SSDATA (bus), &derror);
+   val = CDR_SAFE (Fassoc (bus, xd_registered_buses));
+   if (NILP (val))
+     XD_SIGNAL2 (build_string ("No connection to bus"), bus);
    else
-     if (EQ (bus, QCdbus_system_bus))
-       connection = dbus_bus_get (DBUS_BUS_SYSTEM, &derror);
-     else
-       connection = dbus_bus_get (DBUS_BUS_SESSION, &derror);
+     connection = (DBusConnection *) (intptr_t) XFASTINT (val);
  
-   if (dbus_error_is_set (&derror))
-     {
-       if (raise_error)
-       XD_ERROR (derror);
-       else
-       connection = NULL;
-     }
-   /* If it is not the system or session bus, we must register
-      ourselves.  Otherwise, we have called dbus_bus_get, which has
-      configured us to exit if the connection closes - we undo this
-      setting.  */
-   if (connection != NULL)
-     {
-       if (STRINGP (bus))
-       dbus_bus_register (connection, &derror);
-       else
-       dbus_connection_set_exit_on_disconnect (connection, FALSE);
-     }
-   if (dbus_error_is_set (&derror))
-     {
-       if (raise_error)
-       XD_ERROR (derror);
-       else
-       connection = NULL;
-     }
-   if (connection == NULL && raise_error)
+   if (!dbus_connection_get_is_connected (connection))
      XD_SIGNAL2 (build_string ("No connection to bus"), bus);
  
-   /* Cleanup.  */
-   dbus_error_free (&derror);
-   /* Return the result.  */
    return connection;
  }
  
@@@ -896,8 -947,8 +1002,8 @@@ xd_add_watch (DBusWatch *watch, void *d
    int fd = xd_find_watch_fd (watch);
  
    XD_DEBUG_MESSAGE ("fd %d, write %d, enabled %d",
-                     fd, flags & DBUS_WATCH_WRITABLE,
-                     dbus_watch_get_enabled (watch));
+                   fd, flags & DBUS_WATCH_WRITABLE,
+                   dbus_watch_get_enabled (watch));
  
    if (fd == -1)
      return FALSE;
@@@ -929,8 -980,8 +1035,8 @@@ xd_remove_watch (DBusWatch *watch, voi
    /* Unset session environment.  */
    if (XSYMBOL (QCdbus_session_bus) == data)
      {
-       XD_DEBUG_MESSAGE ("unsetenv DBUS_SESSION_BUS_ADDRESS");
-       unsetenv ("DBUS_SESSION_BUS_ADDRESS");
+       //      XD_DEBUG_MESSAGE ("unsetenv DBUS_SESSION_BUS_ADDRESS");
+       //      unsetenv ("DBUS_SESSION_BUS_ADDRESS");
      }
  
    if (flags & DBUS_WATCH_WRITABLE)
@@@ -949,23 -1000,111 +1055,111 @@@ xd_toggle_watch (DBusWatch *watch, voi
      xd_remove_watch (watch, data);
  }
  
- DEFUN ("dbus-init-bus", Fdbus_init_bus, Sdbus_init_bus, 1, 1, 0,
-        doc: /* Initialize connection to D-Bus BUS.  */)
-   (Lisp_Object bus)
+ /* Close connection to D-Bus BUS.  */
+ static void
+ xd_close_bus (Lisp_Object bus)
+ {
+   DBusConnection *connection;
+   Lisp_Object val;
+   /* Check whether we are connected.  */
+   val = Fassoc (bus, xd_registered_buses);
+   if (NILP (val))
+     return;
+   /* Retrieve bus address.  */
+   connection = xd_get_connection_address (bus);
+   /* Close connection, if there isn't another shared application.  */
+   if (xd_get_connection_references (connection) == 1)
+     {
+       XD_DEBUG_MESSAGE ("Close connection to bus %s",
+                       XD_OBJECT_TO_STRING (bus));
+       dbus_connection_close (connection);
+     }
+   /* Decrement reference count.  */
+   dbus_connection_unref (connection);
+   /* Remove bus from list of registered buses.  */
+   xd_registered_buses = Fdelete (val, xd_registered_buses);
+   /* Return.  */
+   return;
+ }
+ DEFUN ("dbus-init-bus", Fdbus_init_bus, Sdbus_init_bus, 1, 2, 0,
+        doc: /* Establish the connection to D-Bus BUS.
+ BUS can be either the symbol `:system' or the symbol `:session', or it
+ can be a string denoting the address of the corresponding bus.  For
+ the system and session buses, this function is called when loading
+ `dbus.el', there is no need to call it again.
+ The function returns a number, which counts the connections this Emacs
+ session has established to the BUS under the same unique name (see
+ `dbus-get-unique-name').  It depends on the libraries Emacs is linked
+ with, and on the environment Emacs is running.  For example, if Emacs
+ is linked with the gtk toolkit, and it runs in a GTK-aware environment
+ like Gnome, another connection might already be established.
+ When PRIVATE is non-nil, a new connection is established instead of
+ reusing an existing one.  It results in a new unique name at the bus.
+ This can be used, if it is necessary to distinguish from another
+ connection used in the same Emacs process, like the one established by
+ GTK+.  It should be used with care for at least the `:system' and
+ `:session' buses, because other Emacs Lisp packages might already use
+ this connection to those buses.  */)
+   (Lisp_Object bus, Lisp_Object private)
  {
    DBusConnection *connection;
-   void *busp;
+   DBusError derror;
+   Lisp_Object val;
+   int refcount;
  
    /* Check parameter.  */
-   if (SYMBOLP (bus))
-     busp = XSYMBOL (bus);
-   else if (STRINGP (bus))
-     busp = XSTRING (bus);
+   XD_DBUS_VALIDATE_BUS_ADDRESS (bus);
+   /* Close bus if it is already open.  */
+   xd_close_bus (bus);
+   /* Initialize.  */
+   dbus_error_init (&derror);
+   /* Open the connection.  */
+   if (STRINGP (bus))
+     if (NILP (private))
+       connection = dbus_connection_open (SSDATA (bus), &derror);
+     else
+       connection = dbus_connection_open_private (SSDATA (bus), &derror);
+   else
+     if (NILP (private))
+       connection = dbus_bus_get (EQ (bus, QCdbus_system_bus)
+                                ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION,
+                                &derror);
+     else
+       connection = dbus_bus_get_private (EQ (bus, QCdbus_system_bus)
+                                        ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION,
+                                        &derror);
+   if (dbus_error_is_set (&derror))
+     XD_ERROR (derror);
+   if (connection == NULL)
+     XD_SIGNAL2 (build_string ("No connection to bus"), bus);
+   /* If it is not the system or session bus, we must register
+      ourselves.  Otherwise, we have called dbus_bus_get, which has
+      configured us to exit if the connection closes - we undo this
+      setting.  */
+   if (STRINGP (bus))
+     dbus_bus_register (connection, &derror);
    else
-     wrong_type_argument (intern ("D-Bus"), bus);
+     dbus_connection_set_exit_on_disconnect (connection, FALSE);
  
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
+   if (dbus_error_is_set (&derror))
+     XD_ERROR (derror);
  
    /* Add the watch functions.  We pass also the bus as data, in order
       to distinguish between the buses in xd_remove_watch.  */
                                            xd_add_watch,
                                            xd_remove_watch,
                                              xd_toggle_watch,
-                                           busp, NULL))
+                                           SYMBOLP (bus)
+                                           ? (void *) XSYMBOL (bus)
+                                           : (void *) XSTRING (bus),
+                                           NULL))
      XD_SIGNAL1 (build_string ("Cannot add watch functions"));
  
    /* Add bus to list of registered buses.  */
-   Vdbus_registered_buses =  Fcons (bus, Vdbus_registered_buses);
+   XSETFASTINT (val, (intptr_t) connection);
+   xd_registered_buses = Fcons (Fcons (bus, val), xd_registered_buses);
  
    /* We do not want to abort.  */
    putenv ((char *) "DBUS_FATAL_WARNINGS=0");
  
-   /* Return.  */
-   return Qnil;
- }
- DEFUN ("dbus-close-bus", Fdbus_close_bus, Sdbus_close_bus, 1, 1, 0,
-        doc: /* Close connection to D-Bus BUS.  */)
-   (Lisp_Object bus)
- {
-   DBusConnection *connection;
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Decrement reference count to the bus.  */
-   dbus_connection_unref (connection);
-   /* Remove bus from list of registered buses.  */
-   Vdbus_registered_buses = Fdelete (bus, Vdbus_registered_buses);
+   /* Cleanup.  */
+   dbus_error_free (&derror);
  
-   /* Return.  */
-   return Qnil;
+   /* Return reference counter.  */
+   refcount = xd_get_connection_references (connection);
+   XD_DEBUG_MESSAGE ("Bus %s, Reference counter %d",
+                   XD_OBJECT_TO_STRING (bus), refcount);
+   return make_number (refcount);
  }
  
  DEFUN ("dbus-get-unique-name", Fdbus_get_unique_name, Sdbus_get_unique_name,
    DBusConnection *connection;
    const char *name;
  
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
+   /* Check parameter.  */
+   XD_DBUS_VALIDATE_BUS_ADDRESS (bus);
+   /* Retrieve bus address.  */
+   connection = xd_get_connection_address (bus);
  
    /* Request the name.  */
    name = dbus_bus_get_unique_name (connection);
    return build_string (name);
  }
  
- DEFUN ("dbus-call-method", Fdbus_call_method, Sdbus_call_method, 5, MANY, 0,
-        doc: /* Call METHOD on the D-Bus BUS.
- BUS is either a Lisp symbol, `:system' or `:session', or a string
- denoting the bus address.
- SERVICE is the D-Bus service name to be used.  PATH is the D-Bus
- object path SERVICE is registered at.  INTERFACE is an interface
- offered by SERVICE.  It must provide METHOD.
- If the parameter `:timeout' is given, the following integer TIMEOUT
- specifies the maximum number of milliseconds the method call must
- return.  The default value is 25,000.  If the method call doesn't
- return in time, a D-Bus error is raised.
- All other arguments ARGS are passed to METHOD as arguments.  They are
- converted into D-Bus types via the following rules:
-   t and nil => DBUS_TYPE_BOOLEAN
-   number    => DBUS_TYPE_UINT32
-   integer   => DBUS_TYPE_INT32
-   float     => DBUS_TYPE_DOUBLE
-   string    => DBUS_TYPE_STRING
-   list      => DBUS_TYPE_ARRAY
- All arguments can be preceded by a type symbol.  For details about
- type symbols, see Info node `(dbus)Type Conversion'.
- `dbus-call-method' returns the resulting values of METHOD as a list of
- Lisp objects.  The type conversion happens the other direction as for
- input arguments.  It follows the mapping rules:
-   DBUS_TYPE_BOOLEAN     => t or nil
-   DBUS_TYPE_BYTE        => number
-   DBUS_TYPE_UINT16      => number
-   DBUS_TYPE_INT16       => integer
-   DBUS_TYPE_UINT32      => number or float
-   DBUS_TYPE_UNIX_FD     => number or float
-   DBUS_TYPE_INT32       => integer or float
-   DBUS_TYPE_UINT64      => number or float
-   DBUS_TYPE_INT64       => integer or float
-   DBUS_TYPE_DOUBLE      => float
-   DBUS_TYPE_STRING      => string
-   DBUS_TYPE_OBJECT_PATH => string
-   DBUS_TYPE_SIGNATURE   => string
-   DBUS_TYPE_ARRAY       => list
-   DBUS_TYPE_VARIANT     => list
-   DBUS_TYPE_STRUCT      => list
-   DBUS_TYPE_DICT_ENTRY  => list
- Example:
- \(dbus-call-method
-   :session "org.gnome.seahorse" "/org/gnome/seahorse/keys/openpgp"
-   "org.gnome.seahorse.Keys" "GetKeyField"
-   "openpgp:657984B8C7A966DD" "simple-name")
-   => (t ("Philip R. Zimmermann"))
- If the result of the METHOD call is just one value, the converted Lisp
- object is returned instead of a list containing this single Lisp object.
- \(dbus-call-method
-   :system "org.freedesktop.Hal" "/org/freedesktop/Hal/devices/computer"
-   "org.freedesktop.Hal.Device" "GetPropertyString"
-   "system.kernel.machine")
-   => "i686"
- usage: (dbus-call-method BUS SERVICE PATH INTERFACE METHOD &optional :timeout TIMEOUT &rest ARGS)  */)
+ DEFUN ("dbus-message-internal", Fdbus_message_internal, Sdbus_message_internal,
+        4, MANY, 0,
+        doc: /* Send a D-Bus message.
+ This is an internal function, it shall not be used outside dbus.el.
+ The following usages are expected:
+ `dbus-call-method', `dbus-call-method-asynchronously':
+   \(dbus-message-internal
+     dbus-message-type-method-call BUS SERVICE PATH INTERFACE METHOD HANDLER
+     &optional :timeout TIMEOUT &rest ARGS)
+ `dbus-send-signal':
+   \(dbus-message-internal
+     dbus-message-type-signal BUS SERVICE PATH INTERFACE SIGNAL &rest ARGS)
+ `dbus-method-return-internal':
+   \(dbus-message-internal
+     dbus-message-type-method-return BUS SERVICE SERIAL &rest ARGS)
+ `dbus-method-error-internal':
+   \(dbus-message-internal
+     dbus-message-type-error BUS SERVICE SERIAL &rest ARGS)
+ usage: (dbus-message-internal &rest REST)  */)
    (ptrdiff_t nargs, Lisp_Object *args)
  {
-   Lisp_Object bus, service, path, interface, method;
+   Lisp_Object message_type, bus, service, handler;
+   Lisp_Object path = Qnil;
+   Lisp_Object interface = Qnil;
+   Lisp_Object member = Qnil;
    Lisp_Object result;
-   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
+   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
    DBusConnection *connection;
    DBusMessage *dmessage;
-   DBusMessage *reply;
    DBusMessageIter iter;
-   DBusError derror;
    unsigned int dtype;
+   unsigned int mtype;
+   dbus_uint32_t serial = 0;
+   unsigned int ui_serial;
    int timeout = -1;
-   ptrdiff_t i = 5;
+   ptrdiff_t count;
    char signature[DBUS_MAXIMUM_SIGNATURE_LENGTH];
  
+   /* Initialize parameters.  */
+   message_type = args[0];
+   bus = args[1];
+   service = args[2];
+   handler = Qnil;
+   CHECK_NATNUM (message_type);
+   mtype = XFASTINT (message_type);
+   if ((mtype <= DBUS_MESSAGE_TYPE_INVALID) || (mtype >= DBUS_NUM_MESSAGE_TYPES))
+     XD_SIGNAL2 (build_string ("Invalid message type"), message_type);
+   if ((mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)
+       || (mtype == DBUS_MESSAGE_TYPE_SIGNAL))
+     {
+       path = args[3];
+       interface = args[4];
+       member = args[5];
+       if (mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)
+       handler = args[6];
+       count = (mtype == DBUS_MESSAGE_TYPE_METHOD_CALL) ? 7 : 6;
+     }
+   else /* DBUS_MESSAGE_TYPE_METHOD_RETURN, DBUS_MESSAGE_TYPE_ERROR  */
+     {
+       XD_CHECK_DBUS_SERIAL (args[3], serial);
+       count = 4;
+     }
    /* Check parameters.  */
-   bus = args[0];
-   service = args[1];
-   path = args[2];
-   interface = args[3];
-   method = args[4];
-   CHECK_STRING (service);
-   CHECK_STRING (path);
-   CHECK_STRING (interface);
-   CHECK_STRING (method);
-   GCPRO5 (bus, service, path, interface, method);
-   XD_DEBUG_MESSAGE ("%s %s %s %s",
-                   SDATA (service),
-                   SDATA (path),
-                   SDATA (interface),
-                   SDATA (method));
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Create the message.  */
-   dmessage = dbus_message_new_method_call (SSDATA (service),
-                                          SSDATA (path),
-                                          SSDATA (interface),
-                                          SSDATA (method));
-   UNGCPRO;
+   XD_DBUS_VALIDATE_BUS_ADDRESS (bus);
+   XD_DBUS_VALIDATE_BUS_NAME (service);
+   if (nargs < count)
+     xsignal2 (Qwrong_number_of_arguments,
+             Qdbus_message_internal,
+             make_number (nargs));
+   if ((mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)
+       || (mtype == DBUS_MESSAGE_TYPE_SIGNAL))
+     {
+       XD_DBUS_VALIDATE_PATH (path);
+       XD_DBUS_VALIDATE_INTERFACE (interface);
+       XD_DBUS_VALIDATE_MEMBER (member);
+       if (!NILP (handler) && (!FUNCTIONP (handler)))
+       wrong_type_argument (Qinvalid_function, handler);
+     }
+   /* Protect Lisp variables.  */
+   GCPRO6 (bus, service, path, interface, member, handler);
+   /* Trace parameters.  */
+   switch (mtype)
+     {
+     case DBUS_MESSAGE_TYPE_METHOD_CALL:
+       XD_DEBUG_MESSAGE ("%s %s %s %s %s %s %s",
+                       XD_MESSAGE_TYPE_TO_STRING (mtype),
+                       XD_OBJECT_TO_STRING (bus),
+                       XD_OBJECT_TO_STRING (service),
+                       XD_OBJECT_TO_STRING (path),
+                       XD_OBJECT_TO_STRING (interface),
+                       XD_OBJECT_TO_STRING (member),
+                       XD_OBJECT_TO_STRING (handler));
+       break;
+     case DBUS_MESSAGE_TYPE_SIGNAL:
+       XD_DEBUG_MESSAGE ("%s %s %s %s %s %s",
+                       XD_MESSAGE_TYPE_TO_STRING (mtype),
+                       XD_OBJECT_TO_STRING (bus),
+                       XD_OBJECT_TO_STRING (service),
+                       XD_OBJECT_TO_STRING (path),
+                       XD_OBJECT_TO_STRING (interface),
+                       XD_OBJECT_TO_STRING (member));
+       break;
+     default: /* DBUS_MESSAGE_TYPE_METHOD_RETURN, DBUS_MESSAGE_TYPE_ERROR  */
+       ui_serial = serial;
+       XD_DEBUG_MESSAGE ("%s %s %s %u",
+                       XD_MESSAGE_TYPE_TO_STRING (mtype),
+                       XD_OBJECT_TO_STRING (bus),
+                       XD_OBJECT_TO_STRING (service),
+                       ui_serial);
+     }
+   /* Retrieve bus address.  */
+   connection = xd_get_connection_address (bus);
+   /* Create the D-Bus message.  */
+   dmessage = dbus_message_new (mtype);
    if (dmessage == NULL)
-     XD_SIGNAL1 (build_string ("Unable to create a new message"));
+     {
+       UNGCPRO;
+       XD_SIGNAL1 (build_string ("Unable to create a new message"));
+     }
+   if (STRINGP (service))
+     {
+       if (mtype != DBUS_MESSAGE_TYPE_SIGNAL)
+       /* Set destination.  */
+       {
+         if (!dbus_message_set_destination (dmessage, SSDATA (service)))
+           {
+             UNGCPRO;
+             XD_SIGNAL2 (build_string ("Unable to set the destination"),
+                         service);
+           }
+       }
+       else
+       /* Set destination for unicast signals.  */
+       {
+         Lisp_Object uname;
+         /* If it is the same unique name as we are registered at the
+            bus or an unknown name, we regard it as broadcast message
+            due to backward compatibility.  */
+         if (dbus_bus_name_has_owner (connection, SSDATA (service), NULL))
+           uname = call2 (intern ("dbus-get-name-owner"), bus, service);
+         else
+           uname = Qnil;
+         if (STRINGP (uname)
+             && (strcmp (dbus_bus_get_unique_name (connection), SSDATA (uname))
+                 != 0)
+             && (!dbus_message_set_destination (dmessage, SSDATA (service))))
+           {
+             UNGCPRO;
+             XD_SIGNAL2 (build_string ("Unable to set signal destination"),
+                         service);
+           }
+       }
+     }
+   /* Set message parameters.  */
+   if ((mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)
+       || (mtype == DBUS_MESSAGE_TYPE_SIGNAL))
+     {
+       if ((!dbus_message_set_path (dmessage, SSDATA (path)))
+         || (!dbus_message_set_interface (dmessage, SSDATA (interface)))
+         || (!dbus_message_set_member (dmessage, SSDATA (member))))
+       {
+         UNGCPRO;
+         XD_SIGNAL1 (build_string ("Unable to set the message parameter"));
+       }
+     }
+   else /* DBUS_MESSAGE_TYPE_METHOD_RETURN, DBUS_MESSAGE_TYPE_ERROR  */
+     {
+       if (!dbus_message_set_reply_serial (dmessage, serial))
+       {
+         UNGCPRO;
+         XD_SIGNAL1 (build_string ("Unable to create a return message"));
+       }
+       if ((mtype == DBUS_MESSAGE_TYPE_ERROR)
+         && (!dbus_message_set_error_name (dmessage, DBUS_ERROR_FAILED)))
+       {
+         UNGCPRO;
+         XD_SIGNAL1 (build_string ("Unable to create a error message"));
+       }
+     }
  
    /* Check for timeout parameter.  */
-   if ((i+2 <= nargs) && (EQ ((args[i]), QCdbus_timeout)))
+   if ((count+2 <= nargs) && (EQ ((args[count]), QCdbus_timeout)))
      {
-       CHECK_NATNUM (args[i+1]);
-       timeout = min (XFASTINT (args[i+1]), INT_MAX);
-       i = i+2;
+       CHECK_NATNUM (args[count+1]);
 -      timeout = XFASTINT (args[count+1]);
++      timeout = min (XFASTINT (args[count+1]), INT_MAX);
+       count = count+2;
      }
  
    /* Initialize parameter list of message.  */
    dbus_message_iter_init_append (dmessage, &iter);
  
    /* Append parameters to the message.  */
-   for (; i < nargs; ++i)
+   for (; count < nargs; ++count)
      {
-       dtype = XD_OBJECT_TO_DBUS_TYPE (args[i]);
-       if (XD_DBUS_TYPE_P (args[i]))
+       dtype = XD_OBJECT_TO_DBUS_TYPE (args[count]);
+       if (XD_DBUS_TYPE_P (args[count]))
        {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i+1]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s %s", i - 4,
-                           SDATA (format2 ("%s", args[i], Qnil)),
-                           SDATA (format2 ("%s", args[i+1], Qnil)));
-         ++i;
+         XD_DEBUG_VALID_LISP_OBJECT_P (args[count]);
+         XD_DEBUG_VALID_LISP_OBJECT_P (args[count+1]);
+         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s %s", count - 4,
+                           XD_OBJECT_TO_STRING (args[count]),
+                           XD_OBJECT_TO_STRING (args[count+1]));
+         ++count;
        }
        else
        {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s", i - 4,
-                           SDATA (format2 ("%s", args[i], Qnil)));
+         XD_DEBUG_VALID_LISP_OBJECT_P (args[count]);
+         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s", count - 4,
+                           XD_OBJECT_TO_STRING (args[count]));
        }
  
        /* Check for valid signature.  We use DBUS_TYPE_INVALID as
         indication that there is no parent type.  */
-       xd_signature (signature, dtype, DBUS_TYPE_INVALID, args[i]);
+       xd_signature (signature, dtype, DBUS_TYPE_INVALID, args[count]);
  
-       xd_append_arg (dtype, args[i], &iter);
+       xd_append_arg (dtype, args[count], &iter);
      }
  
-   /* Send the message.  */
-   dbus_error_init (&derror);
-   reply = dbus_connection_send_with_reply_and_block (connection,
-                                                    dmessage,
-                                                    timeout,
-                                                    &derror);
+   if (!NILP (handler))
+     {
+       /* Send the message.  The message is just added to the outgoing
+        message queue.  */
+       if (!dbus_connection_send_with_reply (connection, dmessage,
+                                           NULL, timeout))
+       {
+         UNGCPRO;
+         XD_SIGNAL1 (build_string ("Cannot send message"));
+       }
  
-   if (dbus_error_is_set (&derror))
-     XD_ERROR (derror);
-   if (reply == NULL)
-     XD_SIGNAL1 (build_string ("No reply"));
-   XD_DEBUG_MESSAGE ("Message sent");
-   /* Collect the results.  */
-   result = Qnil;
-   GCPRO1 (result);
-   if (dbus_message_iter_init (reply, &iter))
-     {
-       /* Loop over the parameters of the D-Bus reply message.  Construct a
-        Lisp list, which is returned by `dbus-call-method'.  */
-       while ((dtype = dbus_message_iter_get_arg_type (&iter))
-            != DBUS_TYPE_INVALID)
-       {
-         result = Fcons (xd_retrieve_arg (dtype, &iter), result);
-         dbus_message_iter_next (&iter);
-       }
-     }
-   else
-     {
-       /* No arguments: just return nil.  */
-     }
-   /* Cleanup.  */
-   dbus_error_free (&derror);
-   dbus_message_unref (dmessage);
-   dbus_message_unref (reply);
-   /* Return the result.  If there is only one single Lisp object,
-      return it as-it-is, otherwise return the reversed list.  */
-   if (XFASTINT (Flength (result)) == 1)
-     RETURN_UNGCPRO (CAR_SAFE (result));
-   else
-     RETURN_UNGCPRO (Fnreverse (result));
- }
- DEFUN ("dbus-call-method-asynchronously", Fdbus_call_method_asynchronously,
-        Sdbus_call_method_asynchronously, 6, MANY, 0,
-        doc: /* Call METHOD on the D-Bus BUS asynchronously.
- BUS is either a Lisp symbol, `:system' or `:session', or a string
- denoting the bus address.
- SERVICE is the D-Bus service name to be used.  PATH is the D-Bus
- object path SERVICE is registered at.  INTERFACE is an interface
- offered by SERVICE.  It must provide METHOD.
- HANDLER is a Lisp function, which is called when the corresponding
- return message has arrived.  If HANDLER is nil, no return message will
- be expected.
- If the parameter `:timeout' is given, the following integer TIMEOUT
- specifies the maximum number of milliseconds the method call must
- return.  The default value is 25,000.  If the method call doesn't
- return in time, a D-Bus error is raised.
- All other arguments ARGS are passed to METHOD as arguments.  They are
- converted into D-Bus types via the following rules:
-   t and nil => DBUS_TYPE_BOOLEAN
-   number    => DBUS_TYPE_UINT32
-   integer   => DBUS_TYPE_INT32
-   float     => DBUS_TYPE_DOUBLE
-   string    => DBUS_TYPE_STRING
-   list      => DBUS_TYPE_ARRAY
- All arguments can be preceded by a type symbol.  For details about
- type symbols, see Info node `(dbus)Type Conversion'.
- Unless HANDLER is nil, the function returns a key into the hash table
- `dbus-registered-objects-table'.  The corresponding entry in the hash
- table is removed, when the return message has been arrived, and
- HANDLER is called.
- Example:
- \(dbus-call-method-asynchronously
-   :system "org.freedesktop.Hal" "/org/freedesktop/Hal/devices/computer"
-   "org.freedesktop.Hal.Device" "GetPropertyString" 'message
-   "system.kernel.machine")
-   => (:system 2)
-   -| i686
- usage: (dbus-call-method-asynchronously BUS SERVICE PATH INTERFACE METHOD HANDLER &optional :timeout TIMEOUT &rest ARGS)  */)
-   (ptrdiff_t nargs, Lisp_Object *args)
- {
-   Lisp_Object bus, service, path, interface, method, handler;
-   Lisp_Object result;
-   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
-   DBusConnection *connection;
-   DBusMessage *dmessage;
-   DBusMessageIter iter;
-   unsigned int dtype;
-   dbus_uint32_t serial;
-   int timeout = -1;
-   ptrdiff_t i = 6;
-   char signature[DBUS_MAXIMUM_SIGNATURE_LENGTH];
-   /* Check parameters.  */
-   bus = args[0];
-   service = args[1];
-   path = args[2];
-   interface = args[3];
-   method = args[4];
-   handler = args[5];
-   CHECK_STRING (service);
-   CHECK_STRING (path);
-   CHECK_STRING (interface);
-   CHECK_STRING (method);
-   if (!NILP (handler) && !FUNCTIONP (handler))
-     wrong_type_argument (Qinvalid_function, handler);
-   GCPRO6 (bus, service, path, interface, method, handler);
-   XD_DEBUG_MESSAGE ("%s %s %s %s",
-                   SDATA (service),
-                   SDATA (path),
-                   SDATA (interface),
-                   SDATA (method));
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Create the message.  */
-   dmessage = dbus_message_new_method_call (SSDATA (service),
-                                          SSDATA (path),
-                                          SSDATA (interface),
-                                          SSDATA (method));
-   if (dmessage == NULL)
-     XD_SIGNAL1 (build_string ("Unable to create a new message"));
-   /* Check for timeout parameter.  */
-   if ((i+2 <= nargs) && (EQ ((args[i]), QCdbus_timeout)))
-     {
-       CHECK_NATNUM (args[i+1]);
-       timeout = min (XFASTINT (args[i+1]), INT_MAX);
-       i = i+2;
-     }
-   /* Initialize parameter list of message.  */
-   dbus_message_iter_init_append (dmessage, &iter);
-   /* Append parameters to the message.  */
-   for (; i < nargs; ++i)
-     {
-       dtype = XD_OBJECT_TO_DBUS_TYPE (args[i]);
-       if (XD_DBUS_TYPE_P (args[i]))
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i+1]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s %s", i - 4,
-                           SDATA (format2 ("%s", args[i], Qnil)),
-                           SDATA (format2 ("%s", args[i+1], Qnil)));
-         ++i;
-       }
-       else
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s", i - 4,
-                           SDATA (format2 ("%s", args[i], Qnil)));
-       }
-       /* Check for valid signature.  We use DBUS_TYPE_INVALID as
-        indication that there is no parent type.  */
-       xd_signature (signature, dtype, DBUS_TYPE_INVALID, args[i]);
-       xd_append_arg (dtype, args[i], &iter);
-     }
-   if (!NILP (handler))
-     {
-       /* Send the message.  The message is just added to the outgoing
-        message queue.  */
-       if (!dbus_connection_send_with_reply (connection, dmessage,
-                                           NULL, timeout))
-       XD_SIGNAL1 (build_string ("Cannot send message"));
-       /* The result is the key in Vdbus_registered_objects_table.  */
-       serial = dbus_message_get_serial (dmessage);
-       result = list2 (bus, make_fixnum_or_float (serial));
+       /* The result is the key in Vdbus_registered_objects_table.  */
+       serial = dbus_message_get_serial (dmessage);
+       result = list3 (QCdbus_registered_serial,
+                     bus, make_fixnum_or_float (serial));
  
        /* Create a hash table entry.  */
        Fputhash (result, handler, Vdbus_registered_objects_table);
        /* Send the message.  The message is just added to the outgoing
         message queue.  */
        if (!dbus_connection_send (connection, dmessage, NULL))
-       XD_SIGNAL1 (build_string ("Cannot send message"));
+       {
+         UNGCPRO;
+         XD_SIGNAL1 (build_string ("Cannot send message"));
+       }
  
        result = Qnil;
      }
  
-   XD_DEBUG_MESSAGE ("Message sent");
+   XD_DEBUG_MESSAGE ("Message sent: %s", XD_OBJECT_TO_STRING (result));
  
    /* Cleanup.  */
    dbus_message_unref (dmessage);
    RETURN_UNGCPRO (result);
  }
  
- DEFUN ("dbus-method-return-internal", Fdbus_method_return_internal,
-        Sdbus_method_return_internal,
-        3, MANY, 0,
-        doc: /* Return for message SERIAL on the D-Bus BUS.
- This is an internal function, it shall not be used outside dbus.el.
- usage: (dbus-method-return-internal BUS SERIAL SERVICE &rest ARGS)  */)
-   (ptrdiff_t nargs, Lisp_Object *args)
- {
-   Lisp_Object bus, service;
-   struct gcpro gcpro1, gcpro2;
-   DBusConnection *connection;
-   DBusMessage *dmessage;
-   DBusMessageIter iter;
-   dbus_uint32_t serial;
-   unsigned int ui_serial, dtype;
-   ptrdiff_t i;
-   char signature[DBUS_MAXIMUM_SIGNATURE_LENGTH];
-   /* Check parameters.  */
-   bus = args[0];
-   service = args[2];
-   CHECK_DBUS_SERIAL_GET_SERIAL (args[1], serial);
-   CHECK_STRING (service);
-   GCPRO2 (bus, service);
-   ui_serial = serial;
-   XD_DEBUG_MESSAGE ("%u %s ", ui_serial, SSDATA (service));
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Create the message.  */
-   dmessage = dbus_message_new (DBUS_MESSAGE_TYPE_METHOD_RETURN);
-   if ((dmessage == NULL)
-       || (!dbus_message_set_reply_serial (dmessage, serial))
-       || (!dbus_message_set_destination (dmessage, SSDATA (service))))
-     {
-       UNGCPRO;
-       XD_SIGNAL1 (build_string ("Unable to create a return message"));
-     }
-   UNGCPRO;
-   /* Initialize parameter list of message.  */
-   dbus_message_iter_init_append (dmessage, &iter);
-   /* Append parameters to the message.  */
-   for (i = 3; i < nargs; ++i)
-     {
-       dtype = XD_OBJECT_TO_DBUS_TYPE (args[i]);
-       if (XD_DBUS_TYPE_P (args[i]))
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i+1]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s %s", i - 2,
-                           SDATA (format2 ("%s", args[i], Qnil)),
-                           SDATA (format2 ("%s", args[i+1], Qnil)));
-         ++i;
-       }
-       else
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s", i - 2,
-                           SDATA (format2 ("%s", args[i], Qnil)));
-       }
-       /* Check for valid signature.  We use DBUS_TYPE_INVALID as
-        indication that there is no parent type.  */
-       xd_signature (signature, dtype, DBUS_TYPE_INVALID, args[i]);
-       xd_append_arg (dtype, args[i], &iter);
-     }
-   /* Send the message.  The message is just added to the outgoing
-      message queue.  */
-   if (!dbus_connection_send (connection, dmessage, NULL))
-     XD_SIGNAL1 (build_string ("Cannot send message"));
-   XD_DEBUG_MESSAGE ("Message sent");
-   /* Cleanup.  */
-   dbus_message_unref (dmessage);
-   /* Return.  */
-   return Qt;
- }
- DEFUN ("dbus-method-error-internal", Fdbus_method_error_internal,
-        Sdbus_method_error_internal,
-        3, MANY, 0,
-        doc: /* Return error message for message SERIAL on the D-Bus BUS.
- This is an internal function, it shall not be used outside dbus.el.
- usage: (dbus-method-error-internal BUS SERIAL SERVICE &rest ARGS)  */)
-   (ptrdiff_t nargs, Lisp_Object *args)
- {
-   Lisp_Object bus, service;
-   struct gcpro gcpro1, gcpro2;
-   DBusConnection *connection;
-   DBusMessage *dmessage;
-   DBusMessageIter iter;
-   dbus_uint32_t serial;
-   unsigned int ui_serial, dtype;
-   ptrdiff_t i;
-   char signature[DBUS_MAXIMUM_SIGNATURE_LENGTH];
-   /* Check parameters.  */
-   bus = args[0];
-   service = args[2];
-   CHECK_DBUS_SERIAL_GET_SERIAL (args[1], serial);
-   CHECK_STRING (service);
-   GCPRO2 (bus, service);
-   ui_serial = serial;
-   XD_DEBUG_MESSAGE ("%u %s ", ui_serial, SSDATA (service));
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Create the message.  */
-   dmessage = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
-   if ((dmessage == NULL)
-       || (!dbus_message_set_error_name (dmessage, DBUS_ERROR_FAILED))
-       || (!dbus_message_set_reply_serial (dmessage, serial))
-       || (!dbus_message_set_destination (dmessage, SSDATA (service))))
-     {
-       UNGCPRO;
-       XD_SIGNAL1 (build_string ("Unable to create a error message"));
-     }
-   UNGCPRO;
-   /* Initialize parameter list of message.  */
-   dbus_message_iter_init_append (dmessage, &iter);
-   /* Append parameters to the message.  */
-   for (i = 3; i < nargs; ++i)
-     {
-       dtype = XD_OBJECT_TO_DBUS_TYPE (args[i]);
-       if (XD_DBUS_TYPE_P (args[i]))
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i+1]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s %s", i - 2,
-                           SDATA (format2 ("%s", args[i], Qnil)),
-                           SDATA (format2 ("%s", args[i+1], Qnil)));
-         ++i;
-       }
-       else
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s", i - 2,
-                           SDATA (format2 ("%s", args[i], Qnil)));
-       }
-       /* Check for valid signature.  We use DBUS_TYPE_INVALID as
-        indication that there is no parent type.  */
-       xd_signature (signature, dtype, DBUS_TYPE_INVALID, args[i]);
-       xd_append_arg (dtype, args[i], &iter);
-     }
-   /* Send the message.  The message is just added to the outgoing
-      message queue.  */
-   if (!dbus_connection_send (connection, dmessage, NULL))
-     XD_SIGNAL1 (build_string ("Cannot send message"));
-   XD_DEBUG_MESSAGE ("Message sent");
-   /* Cleanup.  */
-   dbus_message_unref (dmessage);
-   /* Return.  */
-   return Qt;
- }
- DEFUN ("dbus-send-signal", Fdbus_send_signal, Sdbus_send_signal, 5, MANY, 0,
-        doc: /* Send signal SIGNAL on the D-Bus BUS.
- BUS is either a Lisp symbol, `:system' or `:session', or a string
- denoting the bus address.
- SERVICE is the D-Bus service name SIGNAL is sent from.  PATH is the
- D-Bus object path SERVICE is registered at.  INTERFACE is an interface
- offered by SERVICE.  It must provide signal SIGNAL.
- All other arguments ARGS are passed to SIGNAL as arguments.  They are
- converted into D-Bus types via the following rules:
-   t and nil => DBUS_TYPE_BOOLEAN
-   number    => DBUS_TYPE_UINT32
-   integer   => DBUS_TYPE_INT32
-   float     => DBUS_TYPE_DOUBLE
-   string    => DBUS_TYPE_STRING
-   list      => DBUS_TYPE_ARRAY
- All arguments can be preceded by a type symbol.  For details about
- type symbols, see Info node `(dbus)Type Conversion'.
- Example:
- \(dbus-send-signal
-   :session "org.gnu.Emacs" "/org/gnu/Emacs"
-   "org.gnu.Emacs.FileManager" "FileModified" "/home/albinus/.emacs")
- usage: (dbus-send-signal BUS SERVICE PATH INTERFACE SIGNAL &rest ARGS)  */)
-   (ptrdiff_t nargs, Lisp_Object *args)
- {
-   Lisp_Object bus, service, path, interface, signal;
-   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
-   DBusConnection *connection;
-   DBusMessage *dmessage;
-   DBusMessageIter iter;
-   unsigned int dtype;
-   ptrdiff_t i;
-   char signature[DBUS_MAXIMUM_SIGNATURE_LENGTH];
-   /* Check parameters.  */
-   bus = args[0];
-   service = args[1];
-   path = args[2];
-   interface = args[3];
-   signal = args[4];
-   CHECK_STRING (service);
-   CHECK_STRING (path);
-   CHECK_STRING (interface);
-   CHECK_STRING (signal);
-   GCPRO5 (bus, service, path, interface, signal);
-   XD_DEBUG_MESSAGE ("%s %s %s %s",
-                   SDATA (service),
-                   SDATA (path),
-                   SDATA (interface),
-                   SDATA (signal));
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Create the message.  */
-   dmessage = dbus_message_new_signal (SSDATA (path),
-                                     SSDATA (interface),
-                                     SSDATA (signal));
-   UNGCPRO;
-   if (dmessage == NULL)
-     XD_SIGNAL1 (build_string ("Unable to create a new message"));
-   /* Initialize parameter list of message.  */
-   dbus_message_iter_init_append (dmessage, &iter);
-   /* Append parameters to the message.  */
-   for (i = 5; i < nargs; ++i)
-     {
-       dtype = XD_OBJECT_TO_DBUS_TYPE (args[i]);
-       if (XD_DBUS_TYPE_P (args[i]))
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i+1]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s %s", i - 4,
-                           SDATA (format2 ("%s", args[i], Qnil)),
-                           SDATA (format2 ("%s", args[i+1], Qnil)));
-         ++i;
-       }
-       else
-       {
-         XD_DEBUG_VALID_LISP_OBJECT_P (args[i]);
-         XD_DEBUG_MESSAGE ("Parameter%"pD"d %s", i - 4,
-                           SDATA (format2 ("%s", args[i], Qnil)));
-       }
-       /* Check for valid signature.  We use DBUS_TYPE_INVALID as
-        indication that there is no parent type.  */
-       xd_signature (signature, dtype, DBUS_TYPE_INVALID, args[i]);
-       xd_append_arg (dtype, args[i], &iter);
-     }
-   /* Send the message.  The message is just added to the outgoing
-      message queue.  */
-   if (!dbus_connection_send (connection, dmessage, NULL))
-     XD_SIGNAL1 (build_string ("Cannot send message"));
-   XD_DEBUG_MESSAGE ("Signal sent");
-   /* Cleanup.  */
-   dbus_message_unref (dmessage);
-   /* Return.  */
-   return Qt;
- }
  /* Read one queued incoming message of the D-Bus BUS.
     BUS is either a Lisp symbol, :system or :session, or a string denoting
     the bus address.  */
@@@ -1702,7 -1450,7 +1505,7 @@@ xd_read_message_1 (DBusConnection *conn
    DBusMessage *dmessage;
    DBusMessageIter iter;
    unsigned int dtype;
-   int mtype;
+   unsigned int mtype;
    dbus_uint32_t serial;
    unsigned int ui_serial;
    const char *uname, *path, *interface, *member;
    member = dbus_message_get_member (dmessage);
  
    XD_DEBUG_MESSAGE ("Event received: %s %u %s %s %s %s %s",
-                   (mtype == DBUS_MESSAGE_TYPE_INVALID)
-                   ? "DBUS_MESSAGE_TYPE_INVALID"
-                   : (mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)
-                   ? "DBUS_MESSAGE_TYPE_METHOD_CALL"
-                   : (mtype == DBUS_MESSAGE_TYPE_METHOD_RETURN)
-                   ? "DBUS_MESSAGE_TYPE_METHOD_RETURN"
-                   : (mtype == DBUS_MESSAGE_TYPE_ERROR)
-                   ? "DBUS_MESSAGE_TYPE_ERROR"
-                   : "DBUS_MESSAGE_TYPE_SIGNAL",
+                   XD_MESSAGE_TYPE_TO_STRING (mtype),
                    ui_serial, uname, path, interface, member,
-                   SDATA (format2 ("%s", args, Qnil)));
+                   XD_OBJECT_TO_STRING (args));
  
-   if ((mtype == DBUS_MESSAGE_TYPE_METHOD_RETURN)
-       || (mtype == DBUS_MESSAGE_TYPE_ERROR))
+   if (mtype == DBUS_MESSAGE_TYPE_INVALID)
+     goto cleanup;
+   else if ((mtype == DBUS_MESSAGE_TYPE_METHOD_RETURN)
+          || (mtype == DBUS_MESSAGE_TYPE_ERROR))
      {
        /* Search for a registered function of the message.  */
-       key = list2 (bus, make_fixnum_or_float (serial));
+       key = list3 (QCdbus_registered_serial, bus,
+                  make_fixnum_or_float (serial));
        value = Fgethash (key, Vdbus_registered_objects_table, Qnil);
  
        /* There shall be exactly one entry.  Construct an event.  */
        event.arg = Fcons (value, args);
      }
  
-   else /* (mtype != DBUS_MESSAGE_TYPE_METHOD_RETURN)  */
+   else /* DBUS_MESSAGE_TYPE_METHOD_CALL, DBUS_MESSAGE_TYPE_SIGNAL.  */
      {
        /* Vdbus_registered_objects_table requires non-nil interface and
         member.  */
        goto cleanup;
  
        /* Search for a registered function of the message.  */
-       key = list3 (bus, build_string (interface), build_string (member));
+       key = list4 ((mtype == DBUS_MESSAGE_TYPE_METHOD_CALL)
+                  ? QCdbus_registered_method
+                  : QCdbus_registered_signal,
+                  bus, build_string (interface), build_string (member));
        value = Fgethash (key, Vdbus_registered_objects_table, Qnil);
  
        /* Loop over the registered functions.  Construct an event.  */
    /* Store it into the input event queue.  */
    kbd_buffer_store_event (&event);
  
-   XD_DEBUG_MESSAGE ("Event stored: %s",
-                   SDATA (format2 ("%s", event.arg, Qnil)));
+   XD_DEBUG_MESSAGE ("Event stored: %s", XD_OBJECT_TO_STRING (event.arg));
  
    /* Cleanup.  */
   cleanup:
  static Lisp_Object
  xd_read_message (Lisp_Object bus)
  {
-   /* Open a connection to the bus.  */
-   DBusConnection *connection = xd_initialize (bus, TRUE);
+   /* Retrieve bus address.  */
+   DBusConnection *connection = xd_get_connection_address (bus);
  
    /* Non blocking read of the next available message.  */
    dbus_connection_read_write (connection, 0);
  static void
  xd_read_queued_messages (int fd, void *data, int for_read)
  {
-   Lisp_Object busp = Vdbus_registered_buses;
+   Lisp_Object busp = xd_registered_buses;
    Lisp_Object bus = Qnil;
+   Lisp_Object key;
  
    /* Find bus related to fd.  */
    if (data != NULL)
      while (!NILP (busp))
        {
-       if ((SYMBOLP (CAR_SAFE (busp)) && XSYMBOL (CAR_SAFE (busp)) == data)
-           || (STRINGP (CAR_SAFE (busp)) && XSTRING (CAR_SAFE (busp)) == data))
-         bus = CAR_SAFE (busp);
+       key = CAR_SAFE (CAR_SAFE (busp));
+       if ((SYMBOLP (key) && XSYMBOL (key) == data)
+           || (STRINGP (key) && XSTRING (key) == data))
+         bus = key;
        busp = CDR_SAFE (busp);
        }
  
    xd_in_read_queued_messages = 0;
  }
  
- DEFUN ("dbus-register-service", Fdbus_register_service, Sdbus_register_service,
-        2, MANY, 0,
-        doc: /* Register known name SERVICE on the D-Bus BUS.
- BUS is either a Lisp symbol, `:system' or `:session', or a string
- denoting the bus address.
- SERVICE is the D-Bus service name that should be registered.  It must
- be a known name.
- FLAGS are keywords, which control how the service name is registered.
- The following keywords are recognized:
- `:allow-replacement': Allow another service to become the primary
- owner if requested.
- `:replace-existing': Request to replace the current primary owner.
- `:do-not-queue': If we can not become the primary owner do not place
- us in the queue.
- The function returns a keyword, indicating the result of the
- operation.  One of the following keywords is returned:
- `:primary-owner': Service has become the primary owner of the
- requested name.
- `:in-queue': Service could not become the primary owner and has been
- placed in the queue.
- `:exists': Service is already in the queue.
- `:already-owner': Service is already the primary owner.
- Example:
- \(dbus-register-service :session dbus-service-emacs)
-   => :primary-owner.
- \(dbus-register-service
-   :session "org.freedesktop.TextEditor"
-   dbus-service-allow-replacement dbus-service-replace-existing)
-   => :already-owner.
- usage: (dbus-register-service BUS SERVICE &rest FLAGS)  */)
-   (ptrdiff_t nargs, Lisp_Object *args)
- {
-   Lisp_Object bus, service;
-   DBusConnection *connection;
-   ptrdiff_t i;
-   unsigned int value;
-   unsigned int flags = 0;
-   int result;
-   DBusError derror;
-   bus = args[0];
-   service = args[1];
-   /* Check parameters.  */
-   CHECK_STRING (service);
-   /* Process flags.  */
-   for (i = 2; i < nargs; ++i) {
-     value = ((EQ (args[i], QCdbus_request_name_replace_existing))
-            ? DBUS_NAME_FLAG_REPLACE_EXISTING
-            : (EQ (args[i], QCdbus_request_name_allow_replacement))
-            ? DBUS_NAME_FLAG_ALLOW_REPLACEMENT
-            : (EQ (args[i], QCdbus_request_name_do_not_queue))
-            ? DBUS_NAME_FLAG_DO_NOT_QUEUE
-            : -1);
-     if (value == -1)
-       XD_SIGNAL2 (build_string ("Unrecognized name request flag"), args[i]);
-     flags |= value;
-   }
-   /* Open a connection to the bus.  */
-   connection = xd_initialize (bus, TRUE);
-   /* Request the known name from the bus.  */
-   dbus_error_init (&derror);
-   result = dbus_bus_request_name (connection, SSDATA (service), flags,
-                                 &derror);
-   if (dbus_error_is_set (&derror))
-     XD_ERROR (derror);
-   /* Cleanup.  */
-   dbus_error_free (&derror);
-   /* Return object.  */
-   switch (result)
-     {
-     case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER:
-       return QCdbus_request_name_reply_primary_owner;
-     case DBUS_REQUEST_NAME_REPLY_IN_QUEUE:
-       return QCdbus_request_name_reply_in_queue;
-     case DBUS_REQUEST_NAME_REPLY_EXISTS:
-       return QCdbus_request_name_reply_exists;
-     case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER:
-       return QCdbus_request_name_reply_already_owner;
-     default:
-       /* This should not happen.  */
-       XD_SIGNAL2 (build_string ("Could not register service"), service);
-     }
- }
- DEFUN ("dbus-register-signal", Fdbus_register_signal, Sdbus_register_signal,
-        6, MANY, 0,
-        doc: /* Register for signal SIGNAL on the D-Bus BUS.
- BUS is either a Lisp symbol, `:system' or `:session', or a string
- denoting the bus address.
- SERVICE is the D-Bus service name used by the sending D-Bus object.
- It can be either a known name or the unique name of the D-Bus object
- sending the signal.  When SERVICE is nil, related signals from all
- D-Bus objects shall be accepted.
- PATH is the D-Bus object path SERVICE is registered.  It can also be
- nil if the path name of incoming signals shall not be checked.
- INTERFACE is an interface offered by SERVICE.  It must provide SIGNAL.
- HANDLER is a Lisp function to be called when the signal is received.
- It must accept as arguments the values SIGNAL is sending.
- All other arguments ARGS, if specified, must be strings.  They stand
- for the respective arguments of the signal in their order, and are
- used for filtering as well.  A nil argument might be used to preserve
- the order.
- INTERFACE, SIGNAL and HANDLER must not be nil.  Example:
- \(defun my-signal-handler (device)
-   (message "Device %s added" device))
- \(dbus-register-signal
-   :system "org.freedesktop.Hal" "/org/freedesktop/Hal/Manager"
-   "org.freedesktop.Hal.Manager" "DeviceAdded" 'my-signal-handler)
-   => ((:system "org.freedesktop.Hal.Manager" "DeviceAdded")
-       ("org.freedesktop.Hal" "/org/freedesktop/Hal/Manager" my-signal-handler))
- `dbus-register-signal' returns an object, which can be used in
- `dbus-unregister-object' for removing the registration.
- usage: (dbus-register-signal BUS SERVICE PATH INTERFACE SIGNAL HANDLER &rest ARGS) */)
-   (ptrdiff_t nargs, Lisp_Object *args)
- {
-   Lisp_Object bus, service, path, interface, signal, handler;
-   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
-   Lisp_Object uname, key, key1, value;
-   DBusConnection *connection;
-   ptrdiff_t i;
-   char rule[DBUS_MAXIMUM_MATCH_RULE_LENGTH];
-   int rulelen;
-   DBusError derror;
-   /* Check parameters.  */
-   bus = args[0];
-   service = args[1];
-   path = args[2];
-   interface = args[3];
-   signal = args[4];
-   handler = args[5];
-   if (!NILP (service)) CHECK_STRING (service);
-   if (!NILP (path)) CHECK_STRING (path);
-   CHECK_STRING (interface);
-   CHECK_STRING (signal);
-   if (!FUNCTIONP (handler))
-     wrong_type_argument (Qinvalid_function, handler);
-   GCPRO6 (bus, service, path, interface, signal, handler);
-   /* Retrieve unique name of service.  If service is a known name, we
-      will register for the corresponding unique name, if any.  Signals
-      are sent always with the unique name as sender.  Note: the unique
-      name of "org.freedesktop.DBus" is that string itself.  */
-   if ((STRINGP (service))
-       && (SBYTES (service) > 0)
-       && (strcmp (SSDATA (service), DBUS_SERVICE_DBUS) != 0)
-       && (strncmp (SSDATA (service), ":", 1) != 0))
-     uname = call2 (intern ("dbus-get-name-owner"), bus, service);
-   else
-     uname = service;
-   /* Create a matching rule if the unique name exists (when no
-      wildcard).  */
-   if (NILP (uname) || (SBYTES (uname) > 0))
-     {
-       /* Open a connection to the bus.  */
-       connection = xd_initialize (bus, TRUE);
-       /* Create a rule to receive related signals.  */
-       rulelen = snprintf (rule, sizeof rule,
-                         "type='signal',interface='%s',member='%s'",
-                         SDATA (interface),
-                         SDATA (signal));
-       if (! (0 <= rulelen && rulelen < sizeof rule))
-       string_overflow ();
-       /* Add unique name and path to the rule if they are non-nil.  */
-       if (!NILP (uname))
-       {
-         int len = snprintf (rule + rulelen, sizeof rule - rulelen,
-                             ",sender='%s'", SDATA (uname));
-         if (! (0 <= len && len < sizeof rule - rulelen))
-           string_overflow ();
-         rulelen += len;
-       }
-       if (!NILP (path))
-       {
-         int len = snprintf (rule + rulelen, sizeof rule - rulelen,
-                             ",path='%s'", SDATA (path));
-         if (! (0 <= len && len < sizeof rule - rulelen))
-           string_overflow ();
-         rulelen += len;
-       }
-       /* Add arguments to the rule if they are non-nil.  */
-       for (i = 6; i < nargs; ++i)
-       if (!NILP (args[i]))
-         {
-           int len;
-           CHECK_STRING (args[i]);
-           len = snprintf (rule + rulelen, sizeof rule - rulelen,
-                           ",arg%"pD"d='%s'", i - 6, SDATA (args[i]));
-           if (! (0 <= len && len < sizeof rule - rulelen))
-             string_overflow ();
-           rulelen += len;
-         }
-       /* Add the rule to the bus.  */
-       dbus_error_init (&derror);
-       dbus_bus_add_match (connection, rule, &derror);
-       if (dbus_error_is_set (&derror))
-       {
-         UNGCPRO;
-         XD_ERROR (derror);
-       }
-       /* Cleanup.  */
-       dbus_error_free (&derror);
-       XD_DEBUG_MESSAGE ("Matching rule \"%s\" created", rule);
-     }
-   /* Create a hash table entry.  */
-   key = list3 (bus, interface, signal);
-   key1 = list5 (uname, service, path, handler, build_string (rule));
-   value = Fgethash (key, Vdbus_registered_objects_table, Qnil);
-   if (NILP (Fmember (key1, value)))
-     Fputhash (key, Fcons (key1, value), Vdbus_registered_objects_table);
-   /* Return object.  */
-   RETURN_UNGCPRO (list2 (key, list3 (service, path, handler)));
- }
- DEFUN ("dbus-register-method", Fdbus_register_method, Sdbus_register_method,
-        6, 7, 0,
-        doc: /* Register for method METHOD on the D-Bus BUS.
- BUS is either a Lisp symbol, `:system' or `:session', or a string
- denoting the bus address.
- SERVICE is the D-Bus service name of the D-Bus object METHOD is
- registered for.  It must be a known name (See discussion of
- DONT-REGISTER-SERVICE below).
- PATH is the D-Bus object path SERVICE is registered (See discussion of
- DONT-REGISTER-SERVICE below).  INTERFACE is the interface offered by
- SERVICE.  It must provide METHOD.
- HANDLER is a Lisp function to be called when a method call is
- received.  It must accept the input arguments of METHOD.  The return
- value of HANDLER is used for composing the returning D-Bus message.
- In case HANDLER shall return a reply message with an empty argument
- list, HANDLER must return the symbol `:ignore'.
- When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is not
- registered.  This means that other D-Bus clients have no way of
- noticing the newly registered method.  When interfaces are constructed
- incrementally by adding single methods or properties at a time,
- DONT-REGISTER-SERVICE can be used to prevent other clients from
- discovering the still incomplete interface.*/)
-   (Lisp_Object bus, Lisp_Object service, Lisp_Object path,
-    Lisp_Object interface, Lisp_Object method, Lisp_Object handler,
-    Lisp_Object dont_register_service)
- {
-   Lisp_Object key, key1, value;
-   Lisp_Object args[2] = { bus, service };
-   /* Check parameters.  */
-   CHECK_STRING (service);
-   CHECK_STRING (path);
-   CHECK_STRING (interface);
-   CHECK_STRING (method);
-   if (!FUNCTIONP (handler))
-     wrong_type_argument (Qinvalid_function, handler);
-   /* TODO: We must check for a valid service name, otherwise there is
-      a segmentation fault.  */
-   /* Request the name.  */
-   if (NILP (dont_register_service))
-     Fdbus_register_service (2, args);
-   /* Create a hash table entry.  We use nil for the unique name,
-      because the method might be called from anybody.  */
-   key = list3 (bus, interface, method);
-   key1 = list4 (Qnil, service, path, handler);
-   value = Fgethash (key, Vdbus_registered_objects_table, Qnil);
-   if (NILP (Fmember (key1, value)))
-     Fputhash (key, Fcons (key1, value), Vdbus_registered_objects_table);
-   /* Return object.  */
-   return list2 (key, list3 (service, path, handler));
- }
  \f
  void
  syms_of_dbusbind (void)
    DEFSYM (Qdbus_init_bus, "dbus-init-bus");
    defsubr (&Sdbus_init_bus);
  
-   DEFSYM (Qdbus_close_bus, "dbus-close-bus");
-   defsubr (&Sdbus_close_bus);
    DEFSYM (Qdbus_get_unique_name, "dbus-get-unique-name");
    defsubr (&Sdbus_get_unique_name);
  
-   DEFSYM (Qdbus_call_method, "dbus-call-method");
-   defsubr (&Sdbus_call_method);
-   DEFSYM (Qdbus_call_method_asynchronously, "dbus-call-method-asynchronously");
-   defsubr (&Sdbus_call_method_asynchronously);
-   DEFSYM (Qdbus_method_return_internal, "dbus-method-return-internal");
-   defsubr (&Sdbus_method_return_internal);
-   DEFSYM (Qdbus_method_error_internal, "dbus-method-error-internal");
-   defsubr (&Sdbus_method_error_internal);
-   DEFSYM (Qdbus_send_signal, "dbus-send-signal");
-   defsubr (&Sdbus_send_signal);
-   DEFSYM (Qdbus_register_service, "dbus-register-service");
-   defsubr (&Sdbus_register_service);
-   DEFSYM (Qdbus_register_signal, "dbus-register-signal");
-   defsubr (&Sdbus_register_signal);
-   DEFSYM (Qdbus_register_method, "dbus-register-method");
-   defsubr (&Sdbus_register_method);
+   DEFSYM (Qdbus_message_internal, "dbus-message-internal");
+   defsubr (&Sdbus_message_internal);
  
    DEFSYM (Qdbus_error, "dbus-error");
    Fput (Qdbus_error, Qerror_conditions,
  
    DEFSYM (QCdbus_system_bus, ":system");
    DEFSYM (QCdbus_session_bus, ":session");
-   DEFSYM (QCdbus_request_name_allow_replacement, ":allow-replacement");
-   DEFSYM (QCdbus_request_name_replace_existing, ":replace-existing");
-   DEFSYM (QCdbus_request_name_do_not_queue, ":do-not-queue");
-   DEFSYM (QCdbus_request_name_reply_primary_owner, ":primary-owner");
-   DEFSYM (QCdbus_request_name_reply_exists, ":exists");
-   DEFSYM (QCdbus_request_name_reply_in_queue, ":in-queue");
-   DEFSYM (QCdbus_request_name_reply_already_owner, ":already-owner");
    DEFSYM (QCdbus_timeout, ":timeout");
    DEFSYM (QCdbus_type_byte, ":byte");
    DEFSYM (QCdbus_type_boolean, ":boolean");
    DEFSYM (QCdbus_type_string, ":string");
    DEFSYM (QCdbus_type_object_path, ":object-path");
    DEFSYM (QCdbus_type_signature, ":signature");
  #ifdef DBUS_TYPE_UNIX_FD
    DEFSYM (QCdbus_type_unix_fd, ":unix-fd");
  #endif
    DEFSYM (QCdbus_type_array, ":array");
    DEFSYM (QCdbus_type_variant, ":variant");
    DEFSYM (QCdbus_type_struct, ":struct");
    DEFSYM (QCdbus_type_dict_entry, ":dict-entry");
+   DEFSYM (QCdbus_registered_serial, ":serial");
+   DEFSYM (QCdbus_registered_method, ":method");
+   DEFSYM (QCdbus_registered_signal, ":signal");
+   DEFVAR_LISP ("dbus-compiled-version",
+              Vdbus_compiled_version,
+     doc: /* The version of D-Bus Emacs is compiled against.  */);
+ #ifdef DBUS_VERSION_STRING
+   Vdbus_compiled_version = make_pure_c_string (DBUS_VERSION_STRING);
+ #else
+   Vdbus_compiled_version = Qnil;
+ #endif
  
-   DEFVAR_LISP ("dbus-registered-buses",
-              Vdbus_registered_buses,
-     doc: /* List of D-Bus buses we are polling for messages.  */);
-   Vdbus_registered_buses = Qnil;
+   DEFVAR_LISP ("dbus-runtime-version",
+              Vdbus_runtime_version,
+     doc: /* The version of D-Bus Emacs runs with.  */);
+   {
+ #ifdef DBUS_VERSION
+     int major, minor, micro;
+     char s[1024];
+     dbus_get_version (&major, &minor, &micro);
+     snprintf (s, sizeof s, "%d.%d.%d", major, minor, micro);
+     Vdbus_runtime_version = make_string (s, strlen (s));
+ #else
+     Vdbus_runtime_version = Qnil;
+ #endif
+   }
+   DEFVAR_LISP ("dbus-message-type-invalid",
+              Vdbus_message_type_invalid,
+     doc: /* This value is never a valid message type.  */);
+   Vdbus_message_type_invalid = make_number (DBUS_MESSAGE_TYPE_INVALID);
+   DEFVAR_LISP ("dbus-message-type-method-call",
+              Vdbus_message_type_method_call,
+     doc: /* Message type of a method call message.  */);
+   Vdbus_message_type_method_call = make_number (DBUS_MESSAGE_TYPE_METHOD_CALL);
+   DEFVAR_LISP ("dbus-message-type-method-return",
+              Vdbus_message_type_method_return,
+     doc: /* Message type of a method return message.  */);
+   Vdbus_message_type_method_return
+     = make_number (DBUS_MESSAGE_TYPE_METHOD_RETURN);
+   DEFVAR_LISP ("dbus-message-type-error",
+              Vdbus_message_type_error,
+     doc: /* Message type of an error reply message.  */);
+   Vdbus_message_type_error = make_number (DBUS_MESSAGE_TYPE_ERROR);
+   DEFVAR_LISP ("dbus-message-type-signal",
+              Vdbus_message_type_signal,
+     doc: /* Message type of a signal message.  */);
+   Vdbus_message_type_signal = make_number (DBUS_MESSAGE_TYPE_SIGNAL);
  
    DEFVAR_LISP ("dbus-registered-objects-table",
               Vdbus_registered_objects_table,
@@@ -2299,27 -1741,28 +1796,28 @@@ There are two different uses of the has
  registered interfaces properties, targeted by signals or method calls,
  and for calling handlers in case of non-blocking method call returns.
  
- In the first case, the key in the hash table is the list (BUS
- INTERFACE MEMBER).  BUS is either a Lisp symbol, `:system' or
+ In the first case, the key in the hash table is the list (TYPE BUS
+ INTERFACE MEMBER).  TYPE is one of the Lisp symbols `:method',
+ `:signal' or `:property'.  BUS is either a Lisp symbol, `:system' or
  `:session', or a string denoting the bus address.  INTERFACE is a
  string which denotes a D-Bus interface, and MEMBER, also a string, is
  either a method, a signal or a property INTERFACE is offering.  All
  arguments but BUS must not be nil.
  
- The value in the hash table is a list of quadruple lists
- \((UNAME SERVICE PATH OBJECT) (UNAME SERVICE PATH OBJECT) ...).
- SERVICE is the service name as registered, UNAME is the corresponding
- unique name.  In case of registered methods and properties, UNAME is
- nil.  PATH is the object path of the sending object.  All of them can
- be nil, which means a wildcard then.  OBJECT is either the handler to
- be called when a D-Bus message, which matches the key criteria,
- arrives (methods and signals), or a cons cell containing the value of
the property.
+ The value in the hash table is a list of quadruple lists \((UNAME
+ SERVICE PATH OBJECT [RULE]) ...).  SERVICE is the service name as
+ registered, UNAME is the corresponding unique name.  In case of
+ registered methods and properties, UNAME is nil.  PATH is the object
+ path of the sending object.  All of them can be nil, which means a
+ wildcard then.  OBJECT is either the handler to be called when a D-Bus
+ message, which matches the key criteria, arrives (TYPE `:method' and
+ `:signal'), or a cons cell containing the value of the property (TYPE
`:property').
  
- For signals, there is also a fifth element RULE, which keeps the match
- string the signal is registered with.
+ For entries of type `:signal', there is also a fifth element RULE,
which keeps the match string the signal is registered with.
  
- In the second case, the key in the hash table is the list (BUS
+ In the second case, the key in the hash table is the list (:serial BUS
  SERIAL).  BUS is either a Lisp symbol, `:system' or `:session', or a
  string denoting the bus address.  SERIAL is the serial number of the
  non-blocking method call, a reply is expected.  Both arguments must
@@@ -2343,6 -1786,10 +1841,10 @@@ be called when the D-Bus reply message 
    Vdbus_debug = Qnil;
  #endif
  
+   /* Initialize internal objects.  */
+   xd_registered_buses = Qnil;
+   staticpro (&xd_registered_buses);
    Fprovide (intern_c_string ("dbusbind"), Qnil);
  
  }
diff --combined src/dispextern.h
@@@ -179,10 -179,10 +179,10 @@@ extern int trace_redisplay_p EXTERNALLY
  struct text_pos
  {
    /* Character position.  */
 -  EMACS_INT charpos;
 +  ptrdiff_t charpos;
  
    /* Corresponding byte position.  */
 -  EMACS_INT bytepos;
 +  ptrdiff_t bytepos;
  };
  
  /* Access character and byte position of POS in a functional form.  */
@@@ -253,7 -253,7 +253,7 @@@ struct display_po
       is the index of that overlay string in the sequence of overlay
       strings at `pos' in the order redisplay processes them.  A value
       < 0 means that this is not a position in an overlay string.  */
 -  int overlay_string_index;
 +  ptrdiff_t overlay_string_index;
  
    /* If this is a position in an overlay string, string_pos is the
       position within that string.  */
@@@ -320,7 -320,7 +320,7 @@@ struct glyp
       buffer, this is a position in that buffer.  A value of -1
       together with a null object means glyph is a truncation glyph at
       the start of a row.  */
 -  EMACS_INT charpos;
 +  ptrdiff_t charpos;
  
    /* Lisp object source of this glyph.  Currently either a buffer or
       a string, if the glyph was produced from characters which came from
@@@ -1808,7 -1808,7 +1808,7 @@@ typedef enum { NEUTRAL_DIR, L2R, R2L } 
  /* Data type for storing information about characters we need to
     remember.  */
  struct bidi_saved_info {
 -  EMACS_INT bytepos, charpos; /* character's buffer position */
 +  ptrdiff_t bytepos, charpos; /* character's buffer position */
    bidi_type_t type;           /* character's resolved bidi type */
    bidi_type_t type_after_w1;  /* original type of the character, after W1 */
    bidi_type_t orig_type;      /* type as we found it in the buffer */
@@@ -1825,9 -1825,9 +1825,9 @@@ struct bidi_stack 
  struct bidi_string_data {
    Lisp_Object lstring;                /* Lisp string to reorder, or nil */
    const unsigned char *s;     /* string data, or NULL if reordering buffer */
 -  EMACS_INT schars;           /* the number of characters in the string,
 +  ptrdiff_t schars;           /* the number of characters in the string,
                                   excluding the terminating null */
 -  EMACS_INT bufpos;           /* buffer position of lstring, or 0 if N/A */
 +  ptrdiff_t bufpos;           /* buffer position of lstring, or 0 if N/A */
    unsigned from_disp_str : 1; /* 1 means the string comes from a
                                   display property */
    unsigned unibyte : 1;               /* 1 means the string is unibyte */
  
  /* Data type for reordering bidirectional text.  */
  struct bidi_it {
 -  EMACS_INT bytepos;          /* iterator's position in buffer/string */
 -  EMACS_INT charpos;
 +  ptrdiff_t bytepos;          /* iterator's position in buffer/string */
 +  ptrdiff_t charpos;
    int ch;                     /* character at that position, or u+FFFC
                                   ("object replacement character") for a run
                                   of characters covered by a display string */
 -  EMACS_INT nchars;           /* its "length", usually 1; it's > 1 for a run
 +  ptrdiff_t nchars;           /* its "length", usually 1; it's > 1 for a run
                                   of characters covered by a display string */
 -  EMACS_INT ch_len;           /* its length in bytes */
 +  ptrdiff_t ch_len;           /* its length in bytes */
    bidi_type_t type;           /* bidi type of this character, after
                                   resolving weak and neutral types */
    bidi_type_t type_after_w1;  /* original type, after overrides and W1 */
    struct bidi_saved_info next_for_neutral; /* surrounding characters for... */
    struct bidi_saved_info prev_for_neutral; /* ...resolving neutrals */
    struct bidi_saved_info next_for_ws; /* character after sequence of ws */
 -  EMACS_INT next_en_pos;      /* pos. of next char for determining ET type */
 +  ptrdiff_t next_en_pos;      /* pos. of next char for determining ET type */
    bidi_type_t next_en_type;   /* type of char at next_en_pos */
 -  EMACS_INT ignore_bn_limit;  /* position until which to ignore BNs */
 +  ptrdiff_t ignore_bn_limit;  /* position until which to ignore BNs */
    bidi_dir_t sor;             /* direction of start-of-run in effect */
    int scan_dir;                       /* direction of text scan, 1: forw, -1: back */
 -  EMACS_INT disp_pos;         /* position of display string after ch */
 +  ptrdiff_t disp_pos;         /* position of display string after ch */
    int disp_prop;              /* if non-zero, there really is a
                                   `display' property/string at disp_pos;
                                   if 2, the property is a `space' spec */
    struct bidi_stack level_stack[BIDI_MAXLEVEL]; /* stack of embedding levels */
    struct bidi_string_data string;     /* string to reorder */
    bidi_dir_t paragraph_dir;   /* current paragraph direction */
 -  EMACS_INT separator_limit;  /* where paragraph separator should end */
 +  ptrdiff_t separator_limit;  /* where paragraph separator should end */
    unsigned first_elt : 1;     /* if non-zero, examine current char first */
    unsigned new_paragraph : 1; /* if non-zero, we expect a new paragraph */
    unsigned frame_window_p : 1;        /* non-zero if displaying on a GUI frame */
@@@ -2058,7 -2058,7 +2058,7 @@@ enum it_method 
  struct composition_it
  {
    /* Next position at which to check the composition.  */
 -  EMACS_INT stop_pos;
 +  ptrdiff_t stop_pos;
    /* ID number of the composition or glyph-string.  If negative, we
       are not iterating over a composition now.  */
    ptrdiff_t id;
    /* If this is an automatic composition, how many characters to look
       back from the position where a character triggering the
       composition exists.  */
 -  int lookback;
 +  ptrdiff_t lookback;
    /* If non-negative, number of glyphs of the glyph-string.  */
    int nglyphs;
    /* Nonzero iff the composition is created while buffer is scanned in
    /** The following members contain information about the current
        grapheme cluster.  */
    /* Position of the first character of the current grapheme cluster.  */
 -  EMACS_INT charpos;
 +  ptrdiff_t charpos;
    /* Number of characters and bytes of the current grapheme cluster.  */
    int nchars, nbytes;
    /* Indices of the glyphs for the current grapheme cluster.  */
@@@ -2112,19 -2112,19 +2112,19 @@@ struct i
  
    /* The next position at which to check for face changes, invisible
       text, overlay strings, end of text etc., which see.  */
 -  EMACS_INT stop_charpos;
 +  ptrdiff_t stop_charpos;
  
    /* Previous stop position, i.e. the last one before the current
       iterator position in `current'.  */
 -  EMACS_INT prev_stop;
 +  ptrdiff_t prev_stop;
  
    /* Last stop position iterated across whose bidi embedding level is
       equal to the current paragraph's base embedding level.  */
 -  EMACS_INT base_level_stop;
 +  ptrdiff_t base_level_stop;
  
    /* Maximum string or buffer position + 1.  ZV when iterating over
       current_buffer.  */
 -  EMACS_INT end_charpos;
 +  ptrdiff_t end_charpos;
  
    /* C string to iterate over.  Non-null means get characters from
       this string, otherwise characters are read from current_buffer
  
    /* Number of characters in the string (s, or it->string) we iterate
       over.  */
 -  EMACS_INT string_nchars;
 +  ptrdiff_t string_nchars;
  
    /* Start and end of a visible region; -1 if the region is not
       visible in the window.  */
 -  EMACS_INT region_beg_charpos, region_end_charpos;
 +  ptrdiff_t region_beg_charpos, region_end_charpos;
  
    /* Position at which redisplay end trigger functions should be run.  */
 -  EMACS_INT redisplay_end_trigger_charpos;
 +  ptrdiff_t redisplay_end_trigger_charpos;
  
    /* 1 means multibyte characters are enabled.  */
    unsigned multibyte_p : 1;
  
    /* Total number of overlay strings to process.  This can be >
       OVERLAY_STRING_CHUNK_SIZE.  */
 -  int n_overlay_strings;
 +  ptrdiff_t n_overlay_strings;
  
    /* The charpos where n_overlay_strings was calculated.  This should
       be set at the same time as n_overlay_strings.  It is needed
       because we show before-strings at the start of invisible text;
       see handle_invisible_prop in xdisp.c.  */
 -  EMACS_INT overlay_strings_charpos;
 +  ptrdiff_t overlay_strings_charpos;
  
    /* Vector of overlays to process.  Overlay strings are processed
       OVERLAY_STRING_CHUNK_SIZE at a time.  */
    {
      Lisp_Object string;
      int string_nchars;
 -    EMACS_INT end_charpos;
 -    EMACS_INT stop_charpos;
 -    EMACS_INT prev_stop;
 -    EMACS_INT base_level_stop;
 +    ptrdiff_t end_charpos;
 +    ptrdiff_t stop_charpos;
 +    ptrdiff_t prev_stop;
 +    ptrdiff_t base_level_stop;
      struct composition_it cmp_it;
      int face_id;
  
  
    /* -1 means selective display hides everything between a \r and the
       next newline; > 0 means hide lines indented more than that value.  */
 -  EMACS_INT selective;
 +  ptrdiff_t selective;
  
    /* An enumeration describing what the next display element is
       after a call to get_next_display_element.  */
@@@ -2989,7 -2989,7 +2989,7 @@@ enum tool_bar_item_imag
  
  /* Defined in bidi.c */
  
 -extern void bidi_init_it (EMACS_INT, EMACS_INT, int, struct bidi_it *);
 +extern void bidi_init_it (ptrdiff_t, ptrdiff_t, int, struct bidi_it *);
  extern void bidi_move_to_visually_next (struct bidi_it *);
  extern void bidi_paragraph_init (bidi_dir_t, struct bidi_it *, int);
  extern int  bidi_mirror_char (int);
@@@ -3000,11 -3000,11 +3000,11 @@@ extern void bidi_unshelve_cache (void *
  
  /* Defined in xdisp.c */
  
 -struct glyph_row *row_containing_pos (struct window *, EMACS_INT,
 +struct glyph_row *row_containing_pos (struct window *, ptrdiff_t,
                                        struct glyph_row *,
                                        struct glyph_row *, int);
  int line_bottom_y (struct it *);
 -int display_prop_intangible_p (Lisp_Object, Lisp_Object, EMACS_INT, EMACS_INT);
 +int display_prop_intangible_p (Lisp_Object, Lisp_Object, ptrdiff_t, ptrdiff_t);
  void resize_echo_area_exactly (void);
  int resize_mini_window (struct window *, int);
  #if defined USE_TOOLKIT_SCROLL_BARS && !defined USE_GTK
@@@ -3026,18 -3026,18 +3026,18 @@@ void remember_mouse_glyph (struct fram
  
  void mark_window_display_accurate (Lisp_Object, int);
  void redisplay_preserve_echo_area (int);
 -void init_iterator (struct it *, struct window *, EMACS_INT,
 -                    EMACS_INT, struct glyph_row *, enum face_id);
 +void init_iterator (struct it *, struct window *, ptrdiff_t,
 +                    ptrdiff_t, struct glyph_row *, enum face_id);
  void init_iterator_to_row_start (struct it *, struct window *,
                                   struct glyph_row *);
  void start_display (struct it *, struct window *, struct text_pos);
 -void move_it_to (struct it *, EMACS_INT, int, int, int, int);
 +void move_it_to (struct it *, ptrdiff_t, int, int, int, int);
  void move_it_vertically (struct it *, int);
  void move_it_vertically_backward (struct it *, int);
 -void move_it_by_lines (struct it *, int);
 +void move_it_by_lines (struct it *, ptrdiff_t);
  void move_it_past_eol (struct it *);
  void move_it_in_display_line (struct it *it,
 -                            EMACS_INT to_charpos, int to_x,
 +                            ptrdiff_t to_charpos, int to_x,
                              enum move_operation_enum op);
  int in_display_vector_p (struct it *);
  int frame_mode_line_height (struct frame *);
@@@ -3047,15 -3047,15 +3047,15 @@@ extern int help_echo_showing_p
  extern int current_mode_line_height, current_header_line_height;
  extern Lisp_Object help_echo_string, help_echo_window;
  extern Lisp_Object help_echo_object, previous_help_echo_string;
 -extern EMACS_INT help_echo_pos;
 +extern ptrdiff_t help_echo_pos;
  extern struct frame *last_mouse_frame;
  extern int last_tool_bar_item;
  extern void reseat_at_previous_visible_line_start (struct it *);
  extern Lisp_Object lookup_glyphless_char_display (int, struct it *);
 -extern EMACS_INT compute_display_string_pos (struct text_pos *,
 +extern ptrdiff_t compute_display_string_pos (struct text_pos *,
                                             struct bidi_string_data *,
                                             int, int *);
 -extern EMACS_INT compute_display_string_end (EMACS_INT,
 +extern ptrdiff_t compute_display_string_end (ptrdiff_t,
                                             struct bidi_string_data *);
  extern void produce_stretch_glyph (struct it *);
  
@@@ -3101,7 -3101,7 +3101,7 @@@ extern void get_glyph_string_clip_rect 
  extern Lisp_Object find_hot_spot (Lisp_Object, int, int);
  
  extern void handle_tool_bar_click (struct frame *,
 -                                   int, int, int, unsigned int);
 +                                   int, int, int, int);
  
  extern void expose_frame (struct frame *, int, int, int, int);
  extern int x_intersect_rectangles (XRectangle *, XRectangle *,
@@@ -3207,19 -3207,19 +3207,19 @@@ int lookup_derived_face (struct frame *
  void init_frame_faces (struct frame *);
  void free_frame_faces (struct frame *);
  void recompute_basic_faces (struct frame *);
 -int face_at_buffer_position (struct window *w, EMACS_INT pos,
 -                             EMACS_INT region_beg, EMACS_INT region_end,
 -                             EMACS_INT *endptr, EMACS_INT limit,
 +int face_at_buffer_position (struct window *w, ptrdiff_t pos,
 +                             ptrdiff_t region_beg, ptrdiff_t region_end,
 +                             ptrdiff_t *endptr, ptrdiff_t limit,
                               int mouse, int base_face_id);
 -int face_for_overlay_string (struct window *w, EMACS_INT pos,
 -                             EMACS_INT region_beg, EMACS_INT region_end,
 -                             EMACS_INT *endptr, EMACS_INT limit,
 +int face_for_overlay_string (struct window *w, ptrdiff_t pos,
 +                             ptrdiff_t region_beg, ptrdiff_t region_end,
 +                             ptrdiff_t *endptr, ptrdiff_t limit,
                               int mouse, Lisp_Object overlay);
  int face_at_string_position (struct window *w, Lisp_Object string,
 -                             EMACS_INT pos, EMACS_INT bufpos,
 -                             EMACS_INT region_beg, EMACS_INT region_end,
 -                             EMACS_INT *endptr, enum face_id, int mouse);
 -int merge_faces (struct frame *, Lisp_Object, EMACS_INT, int);
 +                             ptrdiff_t pos, ptrdiff_t bufpos,
 +                             ptrdiff_t region_beg, ptrdiff_t region_end,
 +                             ptrdiff_t *endptr, enum face_id, int mouse);
 +int merge_faces (struct frame *, Lisp_Object, int, int);
  int compute_char_face (struct frame *, int, Lisp_Object);
  void free_all_realized_faces (Lisp_Object);
  extern Lisp_Object Qforeground_color, Qbackground_color;
@@@ -3243,7 -3243,6 +3243,6 @@@ extern Window tip_window
  EXFUN (Fx_hide_tip, 0);
  extern void start_hourglass (void);
  extern void cancel_hourglass (void);
- extern int hourglass_started (void);
  extern int hourglass_shown_p;
  struct atimer;                        /* Defined in atimer.h.  */
  /* If non-null, an asynchronous timer that, when it expires, displays
@@@ -3285,11 -3284,11 +3284,11 @@@ extern Lisp_Object buffer_posn_from_coo
                                              Lisp_Object *,
                                              int *, int *, int *, int *);
  extern Lisp_Object mode_line_string (struct window *, enum window_part,
 -                                     int *, int *, EMACS_INT *,
 +                                     int *, int *, ptrdiff_t *,
                                       Lisp_Object *,
                                       int *, int *, int *, int *);
  extern Lisp_Object marginal_area_string (struct window *, enum window_part,
 -                                         int *, int *, EMACS_INT *,
 +                                         int *, int *, ptrdiff_t *,
                                           Lisp_Object *,
                                           int *, int *, int *, int *);
  extern void redraw_frame (struct frame *);
@@@ -3309,7 -3308,7 +3308,7 @@@ void shift_glyph_matrix (struct window 
                           int, int, int);
  void rotate_matrix (struct glyph_matrix *, int, int, int);
  void increment_matrix_positions (struct glyph_matrix *,
 -                                 int, int, EMACS_INT, EMACS_INT);
 +                                 int, int, ptrdiff_t, ptrdiff_t);
  void blank_row (struct window *, struct glyph_row *, int);
  void enable_glyph_matrix_rows (struct glyph_matrix *, int, int, int);
  void clear_glyph_row (struct glyph_row *);
diff --combined src/dispnew.c
@@@ -1,5 -1,6 +1,6 @@@
  /* Updating of data structures for redisplay.
-    Copyright (C) 1985-1988, 1993-1995, 1997-2012 Free Software Foundation, Inc.
+ Copyright (C) 1985-1988, 1993-1995, 1997-2012 Free Software Foundation, Inc.
  
  This file is part of GNU Emacs.
  
@@@ -87,7 -88,7 +88,7 @@@ along with GNU Emacs.  If not, see <htt
  #endif
  #endif /* not __GNU_LIBRARY__ */
  
- #if defined (HAVE_TERM_H) && defined (GNU_LINUX) && defined (HAVE_LIBNCURSES)
+ #if defined (HAVE_TERM_H) && defined (GNU_LINUX)
  #include <term.h>             /* for tgetent */
  #endif
  \f
@@@ -108,7 -109,7 +109,7 @@@ static int required_matrix_height (stru
  static int required_matrix_width (struct window *);
  static void adjust_frame_glyphs (struct frame *);
  static void change_frame_size_1 (struct frame *, int, int, int, int, int);
 -static void increment_row_positions (struct glyph_row *, EMACS_INT, EMACS_INT);
 +static void increment_row_positions (struct glyph_row *, ptrdiff_t, ptrdiff_t);
  static void fill_up_frame_row_with_spaces (struct glyph_row *, int);
  static void build_frame_matrix_from_window_tree (struct glyph_matrix *,
                                                   struct window *);
@@@ -758,7 -759,7 +759,7 @@@ rotate_matrix (struct glyph_matrix *mat
  
  void
  increment_matrix_positions (struct glyph_matrix *matrix, int start, int end,
 -                          EMACS_INT delta, EMACS_INT delta_bytes)
 +                          ptrdiff_t delta, ptrdiff_t delta_bytes)
  {
    /* Check that START and END are reasonable values.  */
    xassert (start >= 0 && start <= matrix->nrows);
@@@ -1000,7 -1001,7 +1001,7 @@@ blank_row (struct window *w, struct gly
  
  static void
  increment_row_positions (struct glyph_row *row,
 -                       EMACS_INT delta, EMACS_INT delta_bytes)
 +                       ptrdiff_t delta, ptrdiff_t delta_bytes)
  {
    int area, i;
  
@@@ -1085,12 -1086,16 +1086,16 @@@ swap_glyph_pointers (struct glyph_row *
    for (i = 0; i < LAST_AREA + 1; ++i)
      {
        struct glyph *temp = a->glyphs[i];
-       short used_tem = a->used[i];
  
        a->glyphs[i] = b->glyphs[i];
        b->glyphs[i] = temp;
-       a->used[i] = b->used[i];
-       b->used[i] = used_tem;
+       if (i < LAST_AREA)
+       {
+         short used_tem = a->used[i];
+         a->used[i] = b->used[i];
+         b->used[i] = used_tem;
+       }
      }
    a->hash = b->hash;
    b->hash = hash_tem;
@@@ -1105,7 -1110,7 +1110,7 @@@ static inline voi
  copy_row_except_pointers (struct glyph_row *to, struct glyph_row *from)
  {
    struct glyph *pointers[1 + LAST_AREA];
-   short used[1 + LAST_AREA];
+   short used[LAST_AREA];
    unsigned hashval;
  
    /* Save glyph pointers of TO.  */
@@@ -2542,7 -2547,8 +2547,7 @@@ build_frame_matrix_from_leaf_window (st
  
          SET_GLYPH_FROM_CHAR (right_border_glyph, '|');
          if (dp
 -            && (gc = DISP_BORDER_GLYPH (dp), GLYPH_CODE_P (gc))
 -            && GLYPH_CODE_CHAR_VALID_P (gc))
 +            && (gc = DISP_BORDER_GLYPH (dp), GLYPH_CODE_P (gc)))
            {
              SET_GLYPH_FROM_GLYPH_CODE (right_border_glyph, gc);
              spec_glyph_lookup_face (w, &right_border_glyph);
@@@ -5473,7 -5479,7 +5478,7 @@@ buffer_posn_from_coords (struct window 
  
  Lisp_Object
  mode_line_string (struct window *w, enum window_part part,
 -                int *x, int *y, EMACS_INT *charpos, Lisp_Object *object,
 +                int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
                  int *dx, int *dy, int *width, int *height)
  {
    struct glyph_row *row;
  
  Lisp_Object
  marginal_area_string (struct window *w, enum window_part part,
 -                    int *x, int *y, EMACS_INT *charpos, Lisp_Object *object,
 +                    int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
                      int *dx, int *dy, int *width, int *height)
  {
    struct glyph_row *row = w->current_matrix->rows;
@@@ -5739,7 -5745,7 +5744,7 @@@ static voi
  change_frame_size_1 (register struct frame *f, int newheight, int newwidth, int pretend, int delay, int safe)
  {
    int new_frame_total_cols;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    /* If we can't deal with the change now, queue it for later.  */
    if (delay || (redisplaying_p && !safe))
@@@ -5960,38 -5966,6 +5965,38 @@@ bitch_at_user (void
                          Sleeping, Waiting
   ***********************************************************************/
  
 +/* Convert a positive value DURATION to a seconds count *PSEC plus a
 +   microseconds count *PUSEC, rounding up.  On overflow return the
 +   maximal value.  */
 +void
 +duration_to_sec_usec (double duration, int *psec, int *pusec)
 +{
 +  int MILLION = 1000000;
 +  int sec = INT_MAX, usec = MILLION - 1;
 +
 +  if (duration < INT_MAX + 1.0)
 +    {
 +      int s = duration;
 +      double usdouble = (duration - s) * MILLION;
 +      int usfloor = usdouble;
 +      int usceil = usfloor + (usfloor < usdouble);
 +
 +      if (usceil < MILLION)
 +      {
 +        sec = s;
 +        usec = usceil;
 +      }
 +      else if (sec < INT_MAX)
 +      {
 +        sec = s + 1;
 +        usec = 0;
 +      }
 +    }
 +
 +  *psec = sec;
 +  *pusec = usec;
 +}
 +
  DEFUN ("sleep-for", Fsleep_for, Ssleep_for, 1, 2, 0,
         doc: /* Pause, without updating display, for SECONDS seconds.
  SECONDS may be a floating-point value, meaning that you can wait for a
@@@ -6002,24 -5976,39 +6007,24 @@@ Emacs was built without floating point 
    (Lisp_Object seconds, Lisp_Object milliseconds)
  {
    int sec, usec;
 +  double duration = extract_float (seconds);
  
 -  if (NILP (milliseconds))
 -    XSETINT (milliseconds, 0);
 -  else
 -    CHECK_NUMBER (milliseconds);
 -  usec = XINT (milliseconds) * 1000;
 +  if (!NILP (milliseconds))
 +    {
 +      CHECK_NUMBER (milliseconds);
 +      duration += XINT (milliseconds) / 1000.0;
 +    }
  
 -  {
 -    double duration = extract_float (seconds);
 -    sec = (int) duration;
 -    usec += (duration - sec) * 1000000;
 -  }
 +  if (! (0 < duration))
 +    return Qnil;
 +
 +  duration_to_sec_usec (duration, &sec, &usec);
  
  #ifndef EMACS_HAS_USECS
    if (sec == 0 && usec != 0)
      error ("Millisecond `sleep-for' not supported on %s", SYSTEM_TYPE);
  #endif
  
 -  /* Assure that 0 <= usec < 1000000.  */
 -  if (usec < 0)
 -    {
 -      /* We can't rely on the rounding being correct if usec is negative.  */
 -      if (-1000000 < usec)
 -      sec--, usec += 1000000;
 -      else
 -      sec -= -usec / 1000000, usec = 1000000 - (-usec % 1000000);
 -    }
 -  else
 -    sec += usec / 1000000, usec %= 1000000;
 -
 -  if (sec < 0 || (sec == 0 && usec == 0))
 -    return Qnil;
 -
    wait_reading_process_output (sec, usec, 0, 0, Qnil, NULL, 0);
  
    return Qnil;
@@@ -6050,20 -6039,27 +6055,20 @@@ sit_for (Lisp_Object timeout, int readi
    if (do_display >= 2)
      redisplay_preserve_echo_area (2);
  
 -  if (INTEGERP (timeout))
 -    {
 -      sec = XINT (timeout);
 -      usec = 0;
 -    }
 -  else if (FLOATP (timeout))
 -    {
 -      double seconds = XFLOAT_DATA (timeout);
 -      sec = (int) seconds;
 -      usec = (int) ((seconds - sec) * 1000000);
 -    }
 -  else if (EQ (timeout, Qt))
 +  if (EQ (timeout, Qt))
      {
        sec = 0;
        usec = 0;
      }
    else
 -    wrong_type_argument (Qnumberp, timeout);
 +    {
 +      double duration = extract_float (timeout);
  
 -  if (sec == 0 && usec == 0 && !EQ (timeout, Qt))
 -    return Qt;
 +      if (! (0 < duration))
 +      return Qt;
 +
 +      duration_to_sec_usec (duration, &sec, &usec);
 +    }
  
  #ifdef SIGIO
    gobble_input (0);
@@@ -6087,7 -6083,7 +6092,7 @@@ Return t if redisplay was performed, ni
  immediately by pending input.  */)
    (Lisp_Object force)
  {
 -  int count;
 +  ptrdiff_t count;
  
    swallow_events (1);
    if ((detect_input_pending_run_timers (1)
@@@ -6133,7 -6129,7 +6138,7 @@@ pass nil for VARIABLE.  */
  {
    Lisp_Object state, tail, frame, buf;
    Lisp_Object *vecp, *end;
 -  int n;
 +  ptrdiff_t n;
  
    if (! NILP (variable))
      {
@@@ -6308,7 -6304,7 +6313,7 @@@ init_display (void
  #ifdef HAVE_X11
        Vwindow_system_version = make_number (11);
  #endif
- #if defined (GNU_LINUX) && defined (HAVE_LIBNCURSES)
+ #ifdef GNU_LINUX
        /* In some versions of ncurses,
         tputs crashes if we have not called tgetent.
         So call tgetent.  */
diff --combined src/editfns.c
@@@ -59,10 -59,6 +59,6 @@@ along with GNU Emacs.  If not, see <htt
  #include "window.h"
  #include "blockinput.h"
  
- #ifndef NULL
- #define NULL 0
- #endif
  #ifndef USER_FULL_NAME
  #define USER_FULL_NAME pw->pw_gecos
  #endif
@@@ -73,22 -69,15 +69,15 @@@ extern char **environ
  
  #define TM_YEAR_BASE 1900
  
- /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
-    asctime to have well-defined behavior.  */
- #ifndef TM_YEAR_IN_ASCTIME_RANGE
- # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
-     (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
- #endif
  #ifdef WINDOWSNT
  extern Lisp_Object w32_get_internal_run_time (void);
  #endif
  
  static void time_overflow (void) NO_RETURN;
  static Lisp_Object format_time_string (char const *, ptrdiff_t, Lisp_Object,
-                                      int, time_t *, struct tm **);
+                                      int, time_t *, struct tm *);
  static int tm_diff (struct tm *, struct tm *);
 -static void update_buffer_properties (EMACS_INT, EMACS_INT);
 +static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
  
  static Lisp_Object Qbuffer_access_fontify_functions;
  static Lisp_Object Fuser_full_name (Lisp_Object);
@@@ -148,14 -137,8 +137,14 @@@ init_editfns (void
    /* If the user name claimed in the environment vars differs from
       the real uid, use the claimed name to find the full name.  */
    tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
 -  Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid ())
 -                                   : Vuser_login_name);
 +  if (! NILP (tem))
 +    tem = Vuser_login_name;
 +  else
 +    {
 +      uid_t euid = geteuid ();
 +      tem = make_fixnum_or_float (euid);
 +    }
 +  Vuser_full_name = Fuser_full_name (tem);
  
    p = getenv ("NAME");
    if (p)
@@@ -220,7 -203,7 +209,7 @@@ DEFUN ("string-to-char", Fstring_to_cha
  }
  \f
  static Lisp_Object
 -buildmark (EMACS_INT charpos, EMACS_INT bytepos)
 +buildmark (ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    register Lisp_Object mark;
    mark = Fmake_marker ();
@@@ -245,6 -228,17 +234,6 @@@ DEFUN ("point-marker", Fpoint_marker, S
    return buildmark (PT, PT_BYTE);
  }
  
 -EMACS_INT
 -clip_to_bounds (EMACS_INT lower, EMACS_INT num, EMACS_INT upper)
 -{
 -  if (num < lower)
 -    return lower;
 -  else if (num > upper)
 -    return upper;
 -  else
 -    return num;
 -}
 -
  DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
         doc: /* Set point to POSITION, a number or marker.
  Beginning of buffer is position (point-min), end is (point-max).
  The return value is POSITION.  */)
    (register Lisp_Object position)
  {
 -  EMACS_INT pos;
 +  ptrdiff_t pos;
  
    if (MARKERP (position)
        && current_buffer == XMARKER (position)->buffer)
@@@ -332,7 -326,7 +321,7 @@@ overlays_around (EMACS_INT pos, Lisp_Ob
  {
    Lisp_Object overlay, start, end;
    struct Lisp_Overlay *tail;
 -  EMACS_INT startpos, endpos;
 +  ptrdiff_t startpos, endpos;
    ptrdiff_t idx = 0;
  
    for (tail = current_buffer->overlays_before; tail; tail = tail->next)
@@@ -481,7 -475,7 +470,7 @@@ get_pos_property (Lisp_Object position
  static void
  find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
            Lisp_Object beg_limit,
 -          EMACS_INT *beg, Lisp_Object end_limit, EMACS_INT *end)
 +          ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
  {
    /* Fields right before and after the point.  */
    Lisp_Object before_field, after_field;
@@@ -597,7 -591,7 +586,7 @@@ A field is a region of text with the sa
  If POS is nil, the value of point is used for POS.  */)
    (Lisp_Object pos)
  {
 -  EMACS_INT beg, end;
 +  ptrdiff_t beg, end;
    find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
    if (beg != end)
      del_range (beg, end);
@@@ -610,7 -604,7 +599,7 @@@ A field is a region of text with the sa
  If POS is nil, the value of point is used for POS.  */)
    (Lisp_Object pos)
  {
 -  EMACS_INT beg, end;
 +  ptrdiff_t beg, end;
    find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
    return make_buffer_string (beg, end, 1);
  }
@@@ -621,7 -615,7 +610,7 @@@ A field is a region of text with the sa
  If POS is nil, the value of point is used for POS.  */)
    (Lisp_Object pos)
  {
 -  EMACS_INT beg, end;
 +  ptrdiff_t beg, end;
    find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
    return make_buffer_string (beg, end, 0);
  }
@@@ -636,7 -630,7 +625,7 @@@ If LIMIT is non-nil, it is a buffer pos
  is before LIMIT, then LIMIT will be returned instead.  */)
    (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
  {
 -  EMACS_INT beg;
 +  ptrdiff_t beg;
    find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
    return make_number (beg);
  }
@@@ -651,7 -645,7 +640,7 @@@ If LIMIT is non-nil, it is a buffer pos
  is after LIMIT, then LIMIT will be returned instead.  */)
    (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
  {
 -  EMACS_INT end;
 +  ptrdiff_t end;
    find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
    return make_number (end);
  }
@@@ -687,7 -681,7 +676,7 @@@ Field boundaries are not noticed if `in
    (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge, Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
  {
    /* If non-zero, then the original point, before re-positioning.  */
 -  EMACS_INT orig_point = 0;
 +  ptrdiff_t orig_point = 0;
    int fwd;
    Lisp_Object prev_old, prev_new;
  
    CHECK_NUMBER_COERCE_MARKER (new_pos);
    CHECK_NUMBER_COERCE_MARKER (old_pos);
  
 -  fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
 +  fwd = (XINT (new_pos) > XINT (old_pos));
  
 -  prev_old = make_number (XFASTINT (old_pos) - 1);
 -  prev_new = make_number (XFASTINT (new_pos) - 1);
 +  prev_old = make_number (XINT (old_pos) - 1);
 +  prev_new = make_number (XINT (new_pos) - 1);
  
    if (NILP (Vinhibit_field_text_motion)
        && !EQ (new_pos, old_pos)
      /* It is possible that NEW_POS is not within the same field as
         OLD_POS; try to move NEW_POS so that it is.  */
      {
 -      EMACS_INT shortage;
 +      ptrdiff_t shortage;
        Lisp_Object field_bound;
  
        if (fwd)
@@@ -784,8 -778,8 +773,8 @@@ boundaries bind `inhibit-field-text-mot
  This function does not move point.  */)
    (Lisp_Object n)
  {
 -  EMACS_INT orig, orig_byte, end;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t orig, orig_byte, end;
 +  ptrdiff_t count = SPECPDL_INDEX ();
    specbind (Qinhibit_point_motion_hooks, Qt);
  
    if (NILP (n))
@@@ -825,17 -819,15 +814,17 @@@ boundaries bind `inhibit-field-text-mot
  This function does not move point.  */)
    (Lisp_Object n)
  {
 -  EMACS_INT end_pos;
 -  EMACS_INT orig = PT;
 +  ptrdiff_t clipped_n;
 +  ptrdiff_t end_pos;
 +  ptrdiff_t orig = PT;
  
    if (NILP (n))
      XSETFASTINT (n, 1);
    else
      CHECK_NUMBER (n);
  
 -  end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
 +  clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
 +  end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0));
  
    /* Return END_POS constrained to the current input field.  */
    return Fconstrain_to_field (make_number (end_pos), make_number (orig),
@@@ -962,7 -954,7 +951,7 @@@ usage: (save-excursion &rest BODY)  */
    (Lisp_Object args)
  {
    register Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    record_unwind_protect (save_excursion_restore, save_excursion_save ());
  
@@@ -977,7 -969,7 +966,7 @@@ usage: (save-current-buffer &rest BODY
    (Lisp_Object args)
  {
    Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
  
@@@ -1103,7 -1095,7 +1092,7 @@@ At the beginning of the buffer or acces
      XSETFASTINT (temp, 0);
    else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
      {
 -      EMACS_INT pos = PT_BYTE;
 +      ptrdiff_t pos = PT_BYTE;
        DEC_POS (pos);
        XSETFASTINT (temp, FETCH_CHAR (pos));
      }
@@@ -1157,7 -1149,7 +1146,7 @@@ POS is an integer or a marker and defau
  If POS is out of range, the value is nil.  */)
    (Lisp_Object pos)
  {
 -  register EMACS_INT pos_byte;
 +  register ptrdiff_t pos_byte;
  
    if (NILP (pos))
      {
@@@ -1190,7 -1182,7 +1179,7 @@@ If POS is out of range, the value is ni
    (Lisp_Object pos)
  {
    register Lisp_Object val;
 -  register EMACS_INT pos_byte;
 +  register ptrdiff_t pos_byte;
  
    if (NILP (pos))
      {
@@@ -1250,7 -1242,7 +1239,7 @@@ of the user with that uid, or nil if th
    if (NILP (uid))
      return Vuser_login_name;
  
 -  id = XFLOATINT (uid);
 +  CONS_TO_INTEGER (uid, uid_t, id);
    BLOCK_INPUT;
    pw = getpwuid (id);
    UNBLOCK_INPUT;
@@@ -1277,7 -1269,14 +1266,7 @@@ DEFUN ("user-uid", Fuser_uid, Suser_uid
  Value is an integer or a float, depending on the value.  */)
    (void)
  {
 -  /* Assignment to EMACS_INT stops GCC whining about limited range of
 -     data type.  */
 -  EMACS_INT euid = geteuid ();
 -
 -  /* Make sure we don't produce a negative UID due to signed integer
 -     overflow.  */
 -  if (euid < 0)
 -    return make_float (geteuid ());
 +  uid_t euid = geteuid ();
    return make_fixnum_or_float (euid);
  }
  
@@@ -1286,7 -1285,14 +1275,7 @@@ DEFUN ("user-real-uid", Fuser_real_uid
  Value is an integer or a float, depending on the value.  */)
    (void)
  {
 -  /* Assignment to EMACS_INT stops GCC whining about limited range of
 -     data type.  */
 -  EMACS_INT uid = getuid ();
 -
 -  /* Make sure we don't produce a negative UID due to signed integer
 -     overflow.  */
 -  if (uid < 0)
 -    return make_float (getuid ());
 +  uid_t uid = getuid ();
    return make_fixnum_or_float (uid);
  }
  
@@@ -1309,8 -1315,7 +1298,8 @@@ name, or nil if there is no such user
      return Vuser_full_name;
    else if (NUMBERP (uid))
      {
 -      uid_t u = XFLOATINT (uid);
 +      uid_t u;
 +      CONS_TO_INTEGER (uid, uid_t, u);
        BLOCK_INPUT;
        pw = getpwuid (u);
        UNBLOCK_INPUT;
@@@ -1372,11 -1377,10 +1361,11 @@@ get_system_name (void
  }
  
  DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
 -       doc: /* Return the process ID of Emacs, as an integer.  */)
 +       doc: /* Return the process ID of Emacs, as a number.  */)
    (void)
  {
 -  return make_number (getpid ());
 +  pid_t pid = getpid ();
 +  return make_fixnum_or_float (pid);
  }
  
  \f
@@@ -1416,7 -1420,7 +1405,7 @@@ hi_time (time_t t
  }
  
  /* Return the bottom 16 bits of the time T.  */
 -static EMACS_INT
 +static int
  lo_time (time_t t)
  {
    return t & ((1 << 16) - 1);
@@@ -1534,8 -1538,6 +1523,8 @@@ lisp_time_argument (Lisp_Object specifi
                else
                  {
                    CHECK_NUMBER (usec_l);
 +                if (! (0 <= XINT (usec_l) && XINT (usec_l) < 1000000))
 +                  return 0;
                    *usec = XINT (usec_l);
                  }
              }
@@@ -1691,7 -1693,7 +1680,7 @@@ usage: (format-time-string FORMAT-STRIN
    (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
  {
    time_t t;
-   struct tm *tm;
+   struct tm tm;
  
    CHECK_STRING (format_string);
    format_string = code_convert_string_norecord (format_string,
  
  static Lisp_Object
  format_time_string (char const *format, ptrdiff_t formatlen,
-                   Lisp_Object timeval, int ut, time_t *tval, struct tm **tmp)
+                   Lisp_Object timeval, int ut, time_t *tval, struct tm *tmp)
  {
-   ptrdiff_t size;
+   char buffer[4000];
+   char *buf = buffer;
+   size_t size = sizeof buffer;
+   size_t len;
+   Lisp_Object bufstring;
    int usec;
    int ns;
    struct tm *tm;
+   USE_SAFE_ALLOCA;
  
 -  if (! (lisp_time_argument (timeval, tval, &usec)
 -       && 0 <= usec && usec < 1000000))
 +  if (! lisp_time_argument (timeval, tval, &usec))
      error ("Invalid time specification");
    ns = usec * 1000;
  
-   /* This is probably enough.  */
-   size = formatlen;
-   if (size <= (STRING_BYTES_BOUND - 50) / 6)
-     size = size * 6 + 50;
-   BLOCK_INPUT;
-   tm = ut ? gmtime (tval) : localtime (tval);
-   UNBLOCK_INPUT;
-   if (! tm)
-     time_overflow ();
-   *tmp = tm;
-   synchronize_system_time_locale ();
    while (1)
      {
-       char *buf = (char *) alloca (size + 1);
-       size_t result;
+       BLOCK_INPUT;
+       synchronize_system_time_locale ();
+       tm = ut ? gmtime (tval) : localtime (tval);
+       if (! tm)
+       {
+         UNBLOCK_INPUT;
+         time_overflow ();
+       }
+       *tmp = *tm;
  
        buf[0] = '\1';
-       BLOCK_INPUT;
-       result = emacs_nmemftime (buf, size, format, formatlen, tm, ut, ns);
-       UNBLOCK_INPUT;
-       if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
-       return code_convert_string_norecord (make_unibyte_string (buf, result),
-                                            Vlocale_coding_system, 0);
+       len = emacs_nmemftime (buf, size, format, formatlen, tm, ut, ns);
+       if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
+       break;
  
-       /* If buffer was too small, make it bigger and try again.  */
-       BLOCK_INPUT;
-       result = emacs_nmemftime (NULL, (size_t) -1, format, formatlen,
-                               tm, ut, ns);
+       /* Buffer was too small, so make it bigger and try again.  */
+       len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tm, ut, ns);
        UNBLOCK_INPUT;
-       if (STRING_BYTES_BOUND <= result)
+       if (STRING_BYTES_BOUND <= len)
        string_overflow ();
-       size = result + 1;
+       size = len + 1;
+       SAFE_ALLOCA (buf, char *, size);
      }
+   UNBLOCK_INPUT;
+   bufstring = make_unibyte_string (buf, len);
+   SAFE_FREE ();
+   return code_convert_string_norecord (bufstring, Vlocale_coding_system, 0);
  }
  
  DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
@@@ -1778,31 -1782,32 +1768,32 @@@ DOW and ZONE.)  */
  
    BLOCK_INPUT;
    decoded_time = localtime (&time_spec);
+   /* Make a copy, in case a signal handler modifies TZ or the struct.  */
+   if (decoded_time)
+     save_tm = *decoded_time;
    UNBLOCK_INPUT;
    if (! (decoded_time
-        && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= decoded_time->tm_year
-        && decoded_time->tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
+        && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= save_tm.tm_year
+        && save_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
      time_overflow ();
-   XSETFASTINT (list_args[0], decoded_time->tm_sec);
-   XSETFASTINT (list_args[1], decoded_time->tm_min);
-   XSETFASTINT (list_args[2], decoded_time->tm_hour);
-   XSETFASTINT (list_args[3], decoded_time->tm_mday);
-   XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
+   XSETFASTINT (list_args[0], save_tm.tm_sec);
+   XSETFASTINT (list_args[1], save_tm.tm_min);
+   XSETFASTINT (list_args[2], save_tm.tm_hour);
+   XSETFASTINT (list_args[3], save_tm.tm_mday);
+   XSETFASTINT (list_args[4], save_tm.tm_mon + 1);
    /* On 64-bit machines an int is narrower than EMACS_INT, thus the
       cast below avoids overflow in int arithmetics.  */
-   XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
-   XSETFASTINT (list_args[6], decoded_time->tm_wday);
-   list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
+   XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) save_tm.tm_year);
+   XSETFASTINT (list_args[6], save_tm.tm_wday);
+   list_args[7] = save_tm.tm_isdst ? Qt : Qnil;
  
-   /* Make a copy, in case gmtime modifies the struct.  */
-   save_tm = *decoded_time;
    BLOCK_INPUT;
    decoded_time = gmtime (&time_spec);
-   UNBLOCK_INPUT;
    if (decoded_time == 0)
      list_args[8] = Qnil;
    else
      XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
+   UNBLOCK_INPUT;
    return Flist (9, list_args);
  }
  
@@@ -1876,32 -1881,31 +1867,34 @@@ usage: (encode-time SECOND MINUTE HOUR 
        tzstring = SSDATA (zone);
        else if (INTEGERP (zone))
        {
 -        int abszone = eabs (XINT (zone));
 -        sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
 -                 abszone / (60*60), (abszone/60) % 60, abszone % 60);
 +        EMACS_INT abszone = eabs (XINT (zone));
 +        EMACS_INT zone_hr = abszone / (60*60);
 +        int zone_min = (abszone/60) % 60;
 +        int zone_sec = abszone % 60;
 +        sprintf (tzbuf, "XXX%s%"pI"d:%02d:%02d", "-" + (XINT (zone) < 0),
 +                 zone_hr, zone_min, zone_sec);
          tzstring = tzbuf;
        }
        else
        error ("Invalid time zone specification");
  
+       BLOCK_INPUT;
        /* Set TZ before calling mktime; merely adjusting mktime's returned
         value doesn't suffice, since that would mishandle leap seconds.  */
        set_time_zone_rule (tzstring);
  
-       BLOCK_INPUT;
        value = mktime (&tm);
-       UNBLOCK_INPUT;
  
        /* Restore TZ to previous value.  */
        newenv = environ;
        environ = oldenv;
-       xfree (newenv);
  #ifdef LOCALTIME_CACHE
        tzset ();
  #endif
+       UNBLOCK_INPUT;
+       xfree (newenv);
      }
  
    if (value == (time_t) -1)
@@@ -1928,24 -1932,37 +1921,37 @@@ but this is considered obsolete.  */
  {
    time_t value;
    struct tm *tm;
-   register char *tem;
+   char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
+   int len IF_LINT (= 0);
  
    if (! lisp_time_argument (specified_time, &value, NULL))
      error ("Invalid time specification");
  
-   /* Convert to a string, checking for out-of-range time stamps.
-      Don't use 'ctime', as that might dump core if VALUE is out of
-      range.  */
+   /* Convert to a string in ctime format, except without the trailing
+      newline, and without the 4-digit year limit.  Don't use asctime
+      or ctime, as they might dump core if the year is outside the
+      range -999 .. 9999.  */
    BLOCK_INPUT;
    tm = localtime (&value);
+   if (tm)
+     {
+       static char const wday_name[][4] =
+       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
+       static char const mon_name[][4] =
+       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
+       printmax_t year_base = TM_YEAR_BASE;
+       len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
+                    wday_name[tm->tm_wday], mon_name[tm->tm_mon], tm->tm_mday,
+                    tm->tm_hour, tm->tm_min, tm->tm_sec,
+                    tm->tm_year + year_base);
+     }
    UNBLOCK_INPUT;
-   if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
+   if (! tm)
      time_overflow ();
  
-   /* Remove the trailing newline.  */
-   tem[strlen (tem) - 1] = '\0';
-   return build_string (tem);
+   return make_unibyte_string (buf, len);
  }
  
  /* Yield A - B, measured in seconds.
@@@ -1989,22 -2006,22 +1995,22 @@@ the data it can't find.  */
    (Lisp_Object specified_time)
  {
    time_t value;
+   int offset;
    struct tm *t;
    struct tm localtm;
-   struct tm *localt;
    Lisp_Object zone_offset, zone_name;
  
    zone_offset = Qnil;
    zone_name = format_time_string ("%Z", sizeof "%Z" - 1, specified_time,
-                                 0, &value, &localt);
-   localtm = *localt;
+                                 0, &value, &localtm);
    BLOCK_INPUT;
    t = gmtime (&value);
+   if (t)
+     offset = tm_diff (&localtm, t);
    UNBLOCK_INPUT;
  
    if (t)
      {
-       int offset = tm_diff (&localtm, t);
        zone_offset = make_number (offset);
        if (SCHARS (zone_name) == 0)
        {
@@@ -2042,9 -2059,16 +2048,16 @@@ only the former.  */
    (Lisp_Object tz)
  {
    const char *tzstring;
+   char **old_environbuf;
+   if (! (NILP (tz) || EQ (tz, Qt)))
+     CHECK_STRING (tz);
+   BLOCK_INPUT;
  
    /* When called for the first time, save the original TZ.  */
-   if (!environbuf)
+   old_environbuf = environbuf;
+   if (!old_environbuf)
      initial_tz = (char *) getenv ("TZ");
  
    if (NILP (tz))
    else if (EQ (tz, Qt))
      tzstring = "UTC0";
    else
-     {
-       CHECK_STRING (tz);
-       tzstring = SSDATA (tz);
-     }
+     tzstring = SSDATA (tz);
  
    set_time_zone_rule (tzstring);
-   xfree (environbuf);
    environbuf = environ;
  
+   UNBLOCK_INPUT;
+   xfree (old_environbuf);
    return Qnil;
  }
  
@@@ -2166,10 -2189,10 +2178,10 @@@ set_time_zone_rule (const char *tzstrin
  
  static void
  general_insert_function (void (*insert_func)
 -                            (const char *, EMACS_INT),
 +                            (const char *, ptrdiff_t),
                         void (*insert_from_string_func)
 -                            (Lisp_Object, EMACS_INT, EMACS_INT,
 -                             EMACS_INT, EMACS_INT, int),
 +                            (Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                             ptrdiff_t, ptrdiff_t, int),
                         int inherit, ptrdiff_t nargs, Lisp_Object *args)
  {
    ptrdiff_t argnum;
@@@ -2305,7 -2328,7 +2317,7 @@@ from adjoining text, if those propertie
    (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
  {
    int i, stringlen;
 -  register EMACS_INT n;
 +  register ptrdiff_t n;
    int c, len;
    unsigned char str[MAX_MULTIBYTE_LENGTH];
    char string[4000];
@@@ -2381,10 -2404,10 +2393,10 @@@ from adjoining text, if those propertie
     buffer substrings.  */
  
  Lisp_Object
 -make_buffer_string (EMACS_INT start, EMACS_INT end, int props)
 +make_buffer_string (ptrdiff_t start, ptrdiff_t end, int props)
  {
 -  EMACS_INT start_byte = CHAR_TO_BYTE (start);
 -  EMACS_INT end_byte = CHAR_TO_BYTE (end);
 +  ptrdiff_t start_byte = CHAR_TO_BYTE (start);
 +  ptrdiff_t end_byte = CHAR_TO_BYTE (end);
  
    return make_buffer_string_both (start, start_byte, end, end_byte, props);
  }
     buffer substrings.  */
  
  Lisp_Object
 -make_buffer_string_both (EMACS_INT start, EMACS_INT start_byte,
 -                       EMACS_INT end, EMACS_INT end_byte, int props)
 +make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
 +                       ptrdiff_t end, ptrdiff_t end_byte, int props)
  {
    Lisp_Object result, tem, tem1;
  
     in the current buffer, if necessary.  */
  
  static void
 -update_buffer_properties (EMACS_INT start, EMACS_INT end)
 +update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
  {
    /* If this buffer has some access functions,
       call them, specifying the range of the buffer being accessed.  */
@@@ -2478,7 -2501,7 +2490,7 @@@ into the result string; if you don't wa
  use `buffer-substring-no-properties' instead.  */)
    (Lisp_Object start, Lisp_Object end)
  {
 -  register EMACS_INT b, e;
 +  register ptrdiff_t b, e;
  
    validate_region (&start, &end);
    b = XINT (start);
@@@ -2494,7 -2517,7 +2506,7 @@@ The two arguments START and END are cha
  they can be in either order.  */)
    (Lisp_Object start, Lisp_Object end)
  {
 -  register EMACS_INT b, e;
 +  register ptrdiff_t b, e;
  
    validate_region (&start, &end);
    b = XINT (start);
@@@ -2578,8 -2601,8 +2590,8 @@@ determines whether case is significant 
    register Lisp_Object trt
      = (!NILP (BVAR (current_buffer, case_fold_search))
         ? BVAR (current_buffer, case_canon_table) : Qnil);
 -  EMACS_INT chars = 0;
 -  EMACS_INT i1, i2, i1_byte, i2_byte;
 +  ptrdiff_t chars = 0;
 +  ptrdiff_t i1, i2, i1_byte, i2_byte;
  
    /* Find the first buffer and its substring.  */
  
@@@ -2740,21 -2763,21 +2752,21 @@@ and don't mark the buffer as really cha
  Both characters must have the same length of multi-byte form.  */)
    (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
  {
 -  register EMACS_INT pos, pos_byte, stop, i, len, end_byte;
 +  register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
    /* Keep track of the first change in the buffer:
       if 0 we haven't found it yet.
       if < 0 we've found it and we've run the before-change-function.
       if > 0 we've actually performed it and the value is its position.  */
 -  EMACS_INT changed = 0;
 +  ptrdiff_t changed = 0;
    unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
    unsigned char *p;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  #define COMBINING_NO   0
  #define COMBINING_BEFORE 1
  #define COMBINING_AFTER  2
  #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
    int maybe_byte_combining = COMBINING_NO;
 -  EMACS_INT last_changed = 0;
 +  ptrdiff_t last_changed = 0;
    int multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
    int fromc, toc;
  
      stop = min (stop, GPT_BYTE);
    while (1)
      {
 -      EMACS_INT pos_byte_next = pos_byte;
 +      ptrdiff_t pos_byte_next = pos_byte;
  
        if (pos_byte >= stop)
        {
  }
  
  
 -static Lisp_Object check_translation (EMACS_INT, EMACS_INT, EMACS_INT,
 +static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
                                      Lisp_Object);
  
  /* Helper function for Ftranslate_region_internal.
     element is found, return it.  Otherwise return Qnil.  */
  
  static Lisp_Object
 -check_translation (EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT end,
 +check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
                   Lisp_Object val)
  {
    int buf_size = 16, buf_used = 0;
    for (; CONSP (val); val = XCDR (val))
      {
        Lisp_Object elt;
 -      EMACS_INT len, i;
 +      ptrdiff_t len, i;
  
        elt = XCAR (val);
        if (! CONSP (elt))
@@@ -2989,8 -3012,8 +3001,8 @@@ It returns the number of characters cha
    register unsigned char *tt; /* Trans table. */
    register int nc;            /* New character. */
    int cnt;                    /* Number of changes made. */
 -  EMACS_INT size;             /* Size of translate table. */
 -  EMACS_INT pos, pos_byte, end_pos;
 +  ptrdiff_t size;             /* Size of translate table. */
 +  ptrdiff_t pos, pos_byte, end_pos;
    int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
    int string_multibyte IF_LINT (= 0);
  
@@@ -3268,7 -3291,7 +3280,7 @@@ save_restriction_restore (Lisp_Object d
        /* The restriction has changed from the saved one, so restore
           the saved restriction.  */
        {
 -        EMACS_INT pt = BUF_PT (buf);
 +        ptrdiff_t pt = BUF_PT (buf);
  
          SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
          SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
@@@ -3326,7 -3349,7 +3338,7 @@@ usage: (save-restriction &rest BODY)  *
    (Lisp_Object body)
  {
    register Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    record_unwind_protect (save_restriction_restore, save_restriction_save ());
    val = Fprogn (body);
@@@ -3544,12 -3567,12 +3556,12 @@@ usage: (format STRING &rest OBJECTS)  *
    ptrdiff_t n;                /* The number of the next arg to substitute */
    char initial_buffer[4000];
    char *buf = initial_buffer;
 -  EMACS_INT bufsize = sizeof initial_buffer;
 -  EMACS_INT max_bufsize = STRING_BYTES_BOUND + 1;
 +  ptrdiff_t bufsize = sizeof initial_buffer;
 +  ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
    char *p;
    Lisp_Object buf_save_value IF_LINT (= {0});
    register char *format, *end, *format_start;
 -  EMACS_INT formatlen, nchars;
 +  ptrdiff_t formatlen, nchars;
    /* Nonzero if the format is multibyte.  */
    int multibyte_format = 0;
    /* Nonzero if the output should be a multibyte string,
       info[0] is unused.  Unused elements have -1 for start.  */
    struct info
    {
 -    EMACS_INT start, end;
 +    ptrdiff_t start, end;
      int converted_to_string;
      int intervals;
    } *info = 0;
        char *format0 = format;
  
        /* Bytes needed to represent the output of this conversion.  */
 -      EMACS_INT convbytes;
 +      ptrdiff_t convbytes;
  
        if (*format == '%')
        {
          int space_flag = 0;
          int sharp_flag = 0;
          int  zero_flag = 0;
 -        EMACS_INT field_width;
 +        ptrdiff_t field_width;
          int precision_given;
          uintmax_t precision = UINTMAX_MAX;
          char *num_end;
            {
              /* handle case (precision[n] >= 0) */
  
 -            EMACS_INT width, padding, nbytes;
 -            EMACS_INT nchars_string;
 +            ptrdiff_t width, padding, nbytes;
 +            ptrdiff_t nchars_string;
  
 -            EMACS_INT prec = -1;
 -            if (precision_given && precision <= TYPE_MAXIMUM (EMACS_INT))
 +            ptrdiff_t prec = -1;
 +            if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
                prec = precision;
  
              /* lisp_string_width ignores a precision of 0, but GNU
                width = nchars_string = nbytes = 0;
              else
                {
 -                EMACS_INT nch, nby;
 +                ptrdiff_t nch, nby;
                  width = lisp_string_width (args[n], prec, &nch, &nby);
                  if (prec < 0)
                    {
              verify (0 < USEFUL_PRECISION_MAX);
  
              int prec;
 -            EMACS_INT padding, sprintf_bytes;
 +            ptrdiff_t padding, sprintf_bytes;
              uintmax_t excess_precision, numwidth;
              uintmax_t leading_zeros = 0, trailing_zeros = 0;
  
  
        if (CONSP (props))
        {
 -        EMACS_INT bytepos = 0, position = 0, translated = 0;
 -        EMACS_INT argn = 1;
 +        ptrdiff_t bytepos = 0, position = 0, translated = 0;
 +        ptrdiff_t argn = 1;
          Lisp_Object list;
  
          /* Adjust the bounds of each text property
          for (list = props; CONSP (list); list = XCDR (list))
            {
              Lisp_Object item;
 -            EMACS_INT pos;
 +            ptrdiff_t pos;
  
              item = XCAR (list);
  
@@@ -4346,12 -4369,12 +4358,12 @@@ Case is ignored if `case-fold-search' i
     It's the caller's job to ensure that START1 <= END1 <= START2 <= END2.  */
  
  static void
 -transpose_markers (EMACS_INT start1, EMACS_INT end1,
 -                 EMACS_INT start2, EMACS_INT end2,
 -                 EMACS_INT start1_byte, EMACS_INT end1_byte,
 -                 EMACS_INT start2_byte, EMACS_INT end2_byte)
 +transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
 +                 ptrdiff_t start2, ptrdiff_t end2,
 +                 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
 +                 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
  {
 -  register EMACS_INT amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
 +  register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
    register struct Lisp_Marker *marker;
  
    /* Update point as if it were a marker.  */
@@@ -4425,9 -4448,9 +4437,9 @@@ any markers that happen to be located i
  Transposing beyond buffer boundaries is an error.  */)
    (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
  {
 -  register EMACS_INT start1, end1, start2, end2;
 -  EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
 -  EMACS_INT gap, len1, len_mid, len2;
 +  register ptrdiff_t start1, end1, start2, end2;
 +  ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte;
 +  ptrdiff_t gap, len1, len_mid, len2;
    unsigned char *start1_addr, *start2_addr, *temp;
  
    INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
    /* Swap the regions if they're reversed.  */
    if (start2 < end1)
      {
 -      register EMACS_INT glumph = start1;
 +      register ptrdiff_t glumph = start1;
        start1 = start2;
        start2 = glumph;
        glumph = end1;
diff --combined src/eval.c
@@@ -90,7 -90,7 +90,7 @@@ Lisp_Object Vautoload_queue
  
  /* Current number of specbindings allocated in specpdl.  */
  
 -EMACS_INT specpdl_size;
 +ptrdiff_t specpdl_size;
  
  /* Pointer to beginning of specpdl.  */
  
@@@ -111,7 -111,7 +111,7 @@@ static EMACS_INT lisp_eval_depth
     signal the error instead of entering an infinite loop of debugger
     invocations.  */
  
 -static int when_entered_debugger;
 +static EMACS_INT when_entered_debugger;
  
  /* The function from which the last `signal' was called.  Set in
     Fsignal.  */
@@@ -183,7 -183,7 +183,7 @@@ static Lisp_Objec
  call_debugger (Lisp_Object arg)
  {
    int debug_while_redisplaying;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object val;
    EMACS_INT old_max = max_specpdl_size;
  
@@@ -379,14 -379,23 +379,14 @@@ usage: (prog1 FIRST BODY...)  */
    Lisp_Object val;
    register Lisp_Object args_left;
    struct gcpro gcpro1, gcpro2;
 -  register int argnum = 0;
 -
 -  if (NILP (args))
 -    return Qnil;
  
    args_left = args;
    val = Qnil;
    GCPRO2 (args, val);
  
 -  do
 -    {
 -      Lisp_Object tem = eval_sub (XCAR (args_left));
 -      if (!(argnum++))
 -      val = tem;
 -      args_left = XCDR (args_left);
 -    }
 -  while (CONSP (args_left));
 +  val = eval_sub (XCAR (args_left));
 +  while (CONSP (args_left = XCDR (args_left)))
 +    eval_sub (XCAR (args_left));
  
    UNGCPRO;
    return val;
@@@ -399,12 -408,31 +399,12 @@@ remaining args, whose values are discar
  usage: (prog2 FORM1 FORM2 BODY...)  */)
    (Lisp_Object args)
  {
 -  Lisp_Object val;
 -  register Lisp_Object args_left;
 -  struct gcpro gcpro1, gcpro2;
 -  register int argnum = -1;
 -
 -  val = Qnil;
 -
 -  if (NILP (args))
 -    return Qnil;
 -
 -  args_left = args;
 -  val = Qnil;
 -  GCPRO2 (args, val);
 -
 -  do
 -    {
 -      Lisp_Object tem = eval_sub (XCAR (args_left));
 -      if (!(argnum++))
 -      val = tem;
 -      args_left = XCDR (args_left);
 -    }
 -  while (CONSP (args_left));
 +  struct gcpro gcpro1;
  
 +  GCPRO1 (args);
 +  eval_sub (XCAR (args));
    UNGCPRO;
 -  return val;
 +  return Fprog1 (XCDR (args));
  }
  
  DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
@@@ -736,8 -764,8 +736,8 @@@ The return value is BASE-VARIABLE.  */
    {
      struct specbinding *p;
  
 -    for (p = specpdl_ptr - 1; p >= specpdl; p--)
 -      if (p->func == NULL
 +    for (p = specpdl_ptr; p > specpdl; )
 +      if ((--p)->func == NULL
          && (EQ (new_alias,
                  CONSP (p->symbol) ? XCAR (p->symbol) : p->symbol)))
        error ("Don't know how to make a let-bound variable an alias");
@@@ -814,9 -842,9 +814,9 @@@ usage: (defvar SYMBOL &optional INITVAL
        { /* Check if there is really a global binding rather than just a let
             binding that shadows the global unboundness of the var.  */
          volatile struct specbinding *pdl = specpdl_ptr;
 -        while (--pdl >= specpdl)
 +        while (pdl > specpdl)
            {
 -            if (EQ (pdl->symbol, sym) && !pdl->func
 +            if (EQ ((--pdl)->symbol, sym) && !pdl->func
                  && EQ (pdl->old_value, Qunbound))
                {
                  message_with_string ("Warning: defvar ignored because %s is let-bound",
@@@ -904,7 -932,7 +904,7 @@@ usage: (let* VARLIST BODY...)  */
    (Lisp_Object args)
  {
    Lisp_Object varlist, var, val, elt, lexenv;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3;
  
    GCPRO3 (args, elt, varlist);
@@@ -967,7 -995,7 +967,7 @@@ usage: (let VARLIST BODY...)  */
  {
    Lisp_Object *temps, tem, lexenv;
    register Lisp_Object elt, varlist;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    ptrdiff_t argnum;
    struct gcpro gcpro1, gcpro2;
    USE_SAFE_ALLOCA;
@@@ -1270,7 -1298,7 +1270,7 @@@ usage: (unwind-protect BODYFORM UNWINDF
    (Lisp_Object args)
  {
    Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    record_unwind_protect (Fprogn, Fcdr (args));
    val = eval_sub (Fcar (args));
@@@ -2020,7 -2048,7 +2020,7 @@@ this does nothing and returns nil.  */
         We used to use 0 here, but that leads to accidental sharing in
         purecopy's hash-consing, so we use a (hopefully) unique integer
         instead.  */
-     docstring = make_number (XPNTR (function));
+     docstring = make_number (XUNTAG (function, Lisp_Symbol));
    return Ffset (function,
                Fpurecopy (list5 (Qautoload, file, docstring,
                                  interactive, type)));
@@@ -2056,7 -2084,7 +2056,7 @@@ un_autoload (Lisp_Object oldqueue
  void
  do_autoload (Lisp_Object fundef, Lisp_Object funname)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object fun;
    struct gcpro gcpro1, gcpro2, gcpro3;
  
@@@ -2103,7 -2131,7 +2103,7 @@@ DEFUN ("eval", Feval, Seval, 1, 2, 0
  If LEXICAL is t, evaluate using lexical scoping.  */)
    (Lisp_Object form, Lisp_Object lexical)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    specbind (Qinternal_interpreter_environment,
            NILP (lexical) ? Qnil : Fcons (Qt, Qnil));
    return unbind_to (count, eval_sub (form));
@@@ -2337,8 -2365,7 +2337,8 @@@ Thus, (apply '+ 1 2 '(3 4)) returns 10
  usage: (apply FUNCTION &rest ARGUMENTS)  */)
    (ptrdiff_t nargs, Lisp_Object *args)
  {
 -  ptrdiff_t i, numargs;
 +  ptrdiff_t i;
 +  EMACS_INT numargs;
    register Lisp_Object spread_arg;
    register Lisp_Object *funcall_args;
    Lisp_Object fun, retval;
@@@ -2988,8 -3015,7 +2988,8 @@@ static Lisp_Objec
  apply_lambda (Lisp_Object fun, Lisp_Object args)
  {
    Lisp_Object args_left;
 -  ptrdiff_t i, numargs;
 +  ptrdiff_t i;
 +  EMACS_INT numargs;
    register Lisp_Object *arg_vector;
    struct gcpro gcpro1, gcpro2, gcpro3;
    register Lisp_Object tem;
@@@ -3034,7 -3060,7 +3034,7 @@@ funcall_lambda (Lisp_Object fun, ptrdif
                register Lisp_Object *arg_vector)
  {
    Lisp_Object val, syms_left, next, lexenv;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    ptrdiff_t i;
    int optional, rest;
  
@@@ -3173,8 -3199,12 +3173,8 @@@ DEFUN ("fetch-bytecode", Ffetch_bytecod
  static void
  grow_specpdl (void)
  {
 -  register int count = SPECPDL_INDEX ();
 -  int max_size =
 -    min (max_specpdl_size,
 -       min (max (PTRDIFF_MAX, SIZE_MAX) / sizeof (struct specbinding),
 -            INT_MAX));
 -  int size;
 +  register ptrdiff_t count = SPECPDL_INDEX ();
 +  ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX);
    if (max_size <= specpdl_size)
      {
        if (max_specpdl_size < 400)
        if (max_size <= specpdl_size)
        signal_error ("Variable binding depth exceeds max-specpdl-size", Qnil);
      }
 -  size = specpdl_size < max_size / 2 ? 2 * specpdl_size : max_size;
 -  specpdl = xnrealloc (specpdl, size, sizeof *specpdl);
 -  specpdl_size = size;
 +  specpdl = xpalloc (specpdl, &specpdl_size, 1, max_size, sizeof *specpdl);
    specpdl_ptr = specpdl + count;
  }
  
@@@ -3312,7 -3344,7 +3312,7 @@@ record_unwind_protect (Lisp_Object (*fu
  }
  
  Lisp_Object
 -unbind_to (int count, Lisp_Object value)
 +unbind_to (ptrdiff_t count, Lisp_Object value)
  {
    Lisp_Object quitf = Vquit_flag;
    struct gcpro gcpro1, gcpro2;
@@@ -3392,7 -3424,7 +3392,7 @@@ The debugger is entered when that fram
    (Lisp_Object level, Lisp_Object flag)
  {
    register struct backtrace *backlist = backtrace_list;
 -  register int i;
 +  register EMACS_INT i;
  
    CHECK_NUMBER (level);
  
diff --combined src/fileio.c
@@@ -1,6 -1,6 +1,6 @@@
  /* File IO for GNU Emacs.
  
- Copyright (C) 1985-1988, 1993-2012  Free Software Foundation, Inc.
+ Copyright (C) 1985-1988, 1993-2012 Free Software Foundation, Inc.
  
  This file is part of GNU Emacs.
  
@@@ -87,17 -87,17 +87,17 @@@ along with GNU Emacs.  If not, see <htt
  #define FILE_SYSTEM_CASE(filename)  (filename)
  #endif
  
- /* Nonzero during writing of auto-save files */
+ /* Nonzero during writing of auto-save files */
  static int auto_saving;
  
- /* Nonzero umask during creation of auto-save directories */
+ /* Nonzero umask during creation of auto-save directories */
  static int auto_saving_dir_umask;
  
  /* Set by auto_save_1 to mode of original file so Fwrite_region will create
-    a new file with the same mode as the original */
+    a new file with the same mode as the original */
  static int auto_save_mode_bits;
  
- /* Set by auto_save_1 if an error occurred during the last auto-save. */
+ /* Set by auto_save_1 if an error occurred during the last auto-save.  */
  static int auto_save_error_occurred;
  
  /* The symbol bound to coding-system-for-read when
@@@ -111,7 -111,7 +111,7 @@@ static Lisp_Object Qauto_save_coding
     which gives a list of operations it handles..  */
  static Lisp_Object Qoperations;
  
- /* Lisp functions for translating file formats */
+ /* Lisp functions for translating file formats */
  static Lisp_Object Qformat_decode, Qformat_annotate_function;
  
  /* Lisp function for setting buffer-file-coding-system and the
@@@ -148,9 -148,9 +148,9 @@@ Lisp_Object Qfile_name_history
  static Lisp_Object Qcar_less_than_car;
  
  static Lisp_Object Fmake_symbolic_link (Lisp_Object, Lisp_Object, Lisp_Object);
 -static int a_write (int, Lisp_Object, EMACS_INT, EMACS_INT,
 +static int a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
                      Lisp_Object *, struct coding_system *);
 -static int e_write (int, Lisp_Object, EMACS_INT, EMACS_INT,
 +static int e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
                    struct coding_system *);
  
  \f
@@@ -260,7 -260,7 +260,7 @@@ use the standard functions without call
  {
    /* This function must not munge the match data.  */
    Lisp_Object chain, inhibited_handlers, result;
 -  int pos = -1;
 +  ptrdiff_t pos = -1;
  
    result = Qnil;
    CHECK_STRING (filename);
        if (CONSP (elt))
        {
          Lisp_Object string = XCAR (elt);
 -        EMACS_INT match_pos;
 +        ptrdiff_t match_pos;
          Lisp_Object handler = XCDR (elt);
          Lisp_Object operations = Qnil;
  
@@@ -877,7 -877,7 +877,7 @@@ filesystem tree, not (expand-file-name 
        }
      }
  
-   /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
+   /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below.  */
    nm = (char *) alloca (SBYTES (name) + 1);
    memcpy (nm, SSDATA (name), SBYTES (name) + 1);
  
    if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
      nm++;
  
-   /* Discard any previous drive specifier if nm is now in UNC format. */
+   /* Discard any previous drive specifier if nm is now in UNC format.  */
    if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
      {
        drive = 0;
            }
          else
  #endif
-         /* drive must be set, so this is okay */
+         /* Drive must be set, so this is okay.  */
          if (strcmp (nm - 2, SSDATA (name)) != 0)
            {
              char temp[] = " :";
          if (!(newdir = egetenv ("HOME")))
            newdir = "";
          nm++;
-         /* egetenv may return a unibyte string, which will bite us since
+         /* `egetenv' may return a unibyte string, which will bite us since
             we expect the directory to be multibyte.  */
          tem = build_string (newdir);
          if (!STRING_MULTIBYTE (tem))
       use the drive's current directory as the prefix if needed.  */
    if (!newdir && drive)
      {
-       /* Get default directory if needed to make nm absolute. */
+       /* Get default directory if needed to make nm absolute.  */
        char *adir = NULL;
        if (!IS_DIRECTORY_SEP (nm[0]))
        {
        }
        if (!adir)
        {
-         /* Either nm starts with /, or drive isn't mounted. */
+         /* Either nm starts with /, or drive isn't mounted.  */
          adir = alloca (4);
          adir[0] = DRIVE_LETTER (drive);
          adir[1] = ':';
  #endif /* DOS_NT */
  
    /* Finally, if no prefix has been specified and nm is not absolute,
-      then it must be expanded relative to default_directory. */
+      then it must be expanded relative to default_directory.  */
  
    if (1
  #ifndef DOS_NT
-       /* /... alone is not absolute on DOS and Windows. */
+       /* /... alone is not absolute on DOS and Windows.  */
        && !IS_DIRECTORY_SEP (nm[0])
  #endif
  #ifdef WINDOWSNT
  #ifdef DOS_NT
    if (newdir)
      {
-       /* First ensure newdir is an absolute name. */
+       /* First ensure newdir is an absolute name.  */
        if (
          /* Detect MSDOS file names with drive specifiers.  */
          ! (IS_DRIVE (newdir[0])
             Because of the admonition against calling expand-file-name
             when we have pointers into lisp strings, we accomplish this
             indirectly by prepending newdir to nm if necessary, and using
-            cwd (or the wd of newdir's drive) as the new newdir. */
+            cwd (or the wd of newdir's drive) as the new newdir.  */
          char *adir;
          if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
            {
          newdir = adir;
        }
  
-       /* Strip off drive name from prefix, if present. */
+       /* Strip off drive name from prefix, if present.  */
        if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
        {
          drive = newdir[0];
    else
      tlen = 0;
  
-   /* Now concatenate the directory and name to new space in the stack frame */
+   /* Now concatenate the directory and name to new space in the stack frame */
    tlen += strlen (nm) + 1;
  #ifdef DOS_NT
    /* Reserve space for drive specifier and escape prefix, since either
        }
  
  #ifdef DOS_NT
-     /* At last, set drive name. */
+     /* At last, set drive name.  */
  #ifdef WINDOWSNT
      /* Except for network file name.  */
      if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
       and perhaps call the corresponding file handler.  This is needed
       for filenames such as "/foo/../user@host:/bar/../baz".  Expanding
       the ".." component gives us "/user@host:/bar/../baz" which needs
-      to be expanded again. */
+      to be expanded again.  */
    handler = Ffind_file_name_handler (result, Qexpand_file_name);
    if (!NILP (handler))
      {
@@@ -1396,7 -1396,7 +1396,7 @@@ See also the function `substitute-in-fi
        }
      }
  
-   /* Now determine directory to start with and put it in NEWDIR */
+   /* Now determine directory to start with and put it in NEWDIR */
  
    newdir = 0;
  
        }
      else  /* ~user/filename */
        {
-       /* Get past ~ to user */
+       /* Get past ~ to user */
        unsigned char *user = nm + 1;
-       /* Find end of name. */
+       /* Find end of name.  */
        unsigned char *ptr = (unsigned char *) strchr (user, '/');
        ptrdiff_t len = ptr ? ptr - user : strlen (user);
-       /* Copy the user name into temp storage. */
+       /* Copy the user name into temp storage.  */
        o = (unsigned char *) alloca (len + 1);
        memcpy (o, user, len);
        o[len] = 0;
  
-       /* Look up the user name. */
+       /* Look up the user name.  */
        BLOCK_INPUT;
        pw = (struct passwd *) getpwnam (o + 1);
        UNBLOCK_INPUT;
        newdir = SDATA (defalt);
      }
  
-   /* Now concatenate the directory and name to new space in the stack frame */
+   /* Now concatenate the directory and name to new space in the stack frame */
  
    tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
    target = (unsigned char *) alloca (tlen);
  
    strcat (target, nm);
  
-   /* Now canonicalize by removing /. and /foo/.. if they appear */
+   /* Now canonicalize by removing /. and /foo/.. if they appear */
  
    p = target;
    o = target;
@@@ -1528,7 -1528,7 +1528,7 @@@ search_embedded_absfilename (char *nm, 
              )
        {
          for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
-         if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
+         if (p[0] == '~' && s > p + 1) /* We've got "/~something/".  */
            {
              char *o = alloca (s - p + 1);
              struct passwd *pw;
@@@ -1612,7 -1612,7 +1612,7 @@@ those `/' is discarded.  */
        (make_specified_string (p, -1, endp - p, multibyte));
  
    /* See if any variables are substituted into the string
-      and find the total length of their values in `total' */
+      and find the total length of their values in `total' */
  
    for (p = nm; p != endp;)
      if (*p != '$')
          goto badsubst;
        else if (*p == '$')
          {
-           /* "$$" means a single "$" */
+           /* "$$" means a single "$" */
            p++;
            total -= 1;
            substituted = 1;
            s = p;
          }
  
-       /* Copy out the variable name */
+       /* Copy out the variable name */
        target = (char *) alloca (s - o + 1);
        strncpy (target, o, s - o);
        target[s - o] = 0;
        strupr (target); /* $home == $HOME etc.  */
  #endif /* DOS_NT */
  
-       /* Get variable value */
+       /* Get variable value */
        o = egetenv (target);
        if (o)
          {
    if (!substituted)
      return filename;
  
-   /* If substitution required, recopy the string and do it */
-   /* Make space in stack frame for the new copy */
+   /* If substitution required, recopy the string and do it */
+   /* Make space in stack frame for the new copy */
    xnm = (char *) alloca (SBYTES (filename) + total + 1);
    x = xnm;
  
-   /* Copy the rest of the name through, replacing $ constructs with values */
+   /* Copy the rest of the name through, replacing $ constructs with values */
    for (p = nm; *p;)
      if (*p != '$')
        *x++ = *p++;
            s = p;
          }
  
-       /* Copy out the variable name */
+       /* Copy out the variable name */
        target = (char *) alloca (s - o + 1);
        strncpy (target, o, s - o);
        target[s - o] = 0;
        strupr (target); /* $home == $HOME etc.  */
  #endif /* DOS_NT */
  
-       /* Get variable value */
+       /* Get variable value */
        o = egetenv (target);
        if (!o)
          {
@@@ -1777,7 -1777,7 +1777,7 @@@ expand_and_dir_to_file (Lisp_Object fil
       stat behaves differently depending!  */
    if (SCHARS (absname) > 1
        && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
-       && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
+       && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
      /* We cannot take shortcuts; they might be wrong for magic file names.  */
      absname = Fdirectory_file_name (absname);
    return absname;
@@@ -1805,7 -1805,7 +1805,7 @@@ barf_or_query_if_file_exists (Lisp_Obje
  
    encoded_filename = ENCODE_FILE (absname);
  
-   /* stat is a good way to tell whether the file exists,
+   /* `stat' is a good way to tell whether the file exists,
       regardless of what access permissions it has.  */
    if (lstat (SSDATA (encoded_filename), &statbuf) >= 0)
      {
@@@ -1867,12 -1867,12 +1867,12 @@@ on the system, we copy the SELinux cont
    (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists, Lisp_Object keep_time, Lisp_Object preserve_uid_gid, Lisp_Object preserve_selinux_context)
  {
    int ifd, ofd;
 -  EMACS_INT n;
 +  int n;
    char buf[16 * 1024];
    struct stat st, out_st;
    Lisp_Object handler;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int input_file_statable_p;
    Lisp_Object encoded_file, encoded_newname;
  #if HAVE_LIBSELINUX
  #if HAVE_LIBSELINUX
    if (conlength > 0)
      {
-       /* Set the modified context back to the file. */
+       /* Set the modified context back to the file.  */
        fail = fsetfilecon (ofd, con);
-       if (fail)
+       /* See http://debbugs.gnu.org/11245 for ENOTSUP.  */
+       if (fail && errno != ENOTSUP)
        report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
  
        freecon (con);
@@@ -2264,7 -2265,7 +2265,7 @@@ This is what happens in interactive us
      {
        if (errno == EXDEV)
        {
 -          int count;
 +          ptrdiff_t count;
            symlink_target = Ffile_symlink_p (file);
            if (! NILP (symlink_target))
              Fmake_symbolic_link (symlink_target, newname,
@@@ -2917,10 -2918,11 +2918,11 @@@ compiled with SELinux support.  */
                error ("Doing context_range_set");
            }
  
-         /* Set the modified context back to the file. */
+         /* Set the modified context back to the file.  */
          fail = lsetfilecon (SSDATA (encoded_absname),
                              context_str (parsed_con));
-         if (fail)
+           /* See http://debbugs.gnu.org/11245 for ENOTSUP.  */
+         if (fail && errno != ENOTSUP)
            report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
  
          context_free (parsed_con);
@@@ -3128,8 -3130,6 +3130,8 @@@ otherwise, if FILE2 does not exist, th
  #ifndef READ_BUF_SIZE
  #define READ_BUF_SIZE (64 << 10)
  #endif
 +/* Some buffer offsets are stored in 'int' variables.  */
 +verify (READ_BUF_SIZE <= INT_MAX);
  
  /* This function is called after Lisp functions to decide a coding
     system are called, or when they cause an error.  Before they are
@@@ -3174,8 -3174,8 +3176,8 @@@ decide_coding_unwind (Lisp_Object unwin
  /* Used to pass values from insert-file-contents to read_non_regular.  */
  
  static int non_regular_fd;
 -static EMACS_INT non_regular_inserted;
 -static EMACS_INT non_regular_nbytes;
 +static ptrdiff_t non_regular_inserted;
 +static int non_regular_nbytes;
  
  
  /* Read from a non-regular file.
  static Lisp_Object
  read_non_regular (Lisp_Object ignore)
  {
 -  EMACS_INT nbytes;
 +  int nbytes;
  
    immediate_quit = 1;
    QUIT;
@@@ -3251,16 -3251,16 +3253,16 @@@ variable `last-coding-system-used' to t
  {
    struct stat st;
    register int fd;
 -  EMACS_INT inserted = 0;
 +  ptrdiff_t inserted = 0;
    int nochange = 0;
 -  register EMACS_INT how_much;
 +  register ptrdiff_t how_much;
    off_t beg_offset, end_offset;
 -  register EMACS_INT unprocessed;
 -  int count = SPECPDL_INDEX ();
 +  register int unprocessed;
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
    Lisp_Object handler, val, insval, orig_filename, old_undo;
    Lisp_Object p;
 -  EMACS_INT total = 0;
 +  ptrdiff_t total = 0;
    int not_regular = 0;
    int save_errno = 0;
    char read_buf[READ_BUF_SIZE];
      {
        val = call6 (handler, Qinsert_file_contents, filename,
                   visit, beg, end, replace);
 -      if (CONSP (val) && CONSP (XCDR (val)))
 +      if (CONSP (val) && CONSP (XCDR (val))
 +        && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
        inserted = XINT (XCAR (XCDR (val)));
        goto handled;
      }
                 We assume that the 1K-byte and 3K-byte for heading
                 and tailing respectively are sufficient for this
                 purpose.  */
 -            EMACS_INT nread;
 +            int nread;
  
              if (st.st_size <= (1024 * 4))
                nread = emacs_read (fd, read_buf, 1024 * 4);
        /* same_at_start and same_at_end count bytes,
         because file access counts bytes
         and BEG and END count bytes.  */
 -      EMACS_INT same_at_start = BEGV_BYTE;
 -      EMACS_INT same_at_end = ZV_BYTE;
 -      EMACS_INT overlap;
 +      ptrdiff_t same_at_start = BEGV_BYTE;
 +      ptrdiff_t same_at_end = ZV_BYTE;
 +      ptrdiff_t overlap;
        /* There is still a possibility we will find the need to do code
         conversion.  If that happens, we set this variable to 1 to
         give up on handling REPLACE in the optimized way.  */
         match the text at the beginning of the buffer.  */
        while (1)
        {
 -        EMACS_INT nread, bufpos;
 +        int nread, bufpos;
  
          nread = emacs_read (fd, buffer, sizeof buffer);
          if (nread < 0)
  
        if (! giveup_match_end)
        {
 -        EMACS_INT temp;
 +        ptrdiff_t temp;
  
          /* We win!  We can handle REPLACE the optimized way.  */
  
       in a more optimized way.  */
    if (!NILP (replace) && ! replace_handled && BEGV < ZV)
      {
 -      EMACS_INT same_at_start = BEGV_BYTE;
 -      EMACS_INT same_at_end = ZV_BYTE;
 -      EMACS_INT same_at_start_charpos;
 -      EMACS_INT inserted_chars;
 -      EMACS_INT overlap;
 -      EMACS_INT bufpos;
 +      ptrdiff_t same_at_start = BEGV_BYTE;
 +      ptrdiff_t same_at_end = ZV_BYTE;
 +      ptrdiff_t same_at_start_charpos;
 +      ptrdiff_t inserted_chars;
 +      ptrdiff_t overlap;
 +      ptrdiff_t bufpos;
        unsigned char *decoded;
 -      EMACS_INT temp;
 -      EMACS_INT this = 0;
 -      int this_count = SPECPDL_INDEX ();
 +      ptrdiff_t temp;
 +      ptrdiff_t this = 0;
 +      ptrdiff_t this_count = SPECPDL_INDEX ();
        int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
        Lisp_Object conversion_buffer;
        struct gcpro gcpro1;
          /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
             quitting while reading a huge while.  */
          /* `try'' is reserved in some compilers (Microsoft C).  */
 -        EMACS_INT trytry = min (total - how_much,
 -                                READ_BUF_SIZE - unprocessed);
 +        int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
  
          /* Allow quitting out of the actual I/O.  */
          immediate_quit = 1;
    /* Here, we don't do code conversion in the loop.  It is done by
       decode_coding_gap after all data are read into the buffer.  */
    {
 -    EMACS_INT gap_size = GAP_SIZE;
 +    ptrdiff_t gap_size = GAP_SIZE;
  
      while (how_much < total)
        {
        /* try is reserved in some compilers (Microsoft C) */
 -      EMACS_INT trytry = min (total - how_much, READ_BUF_SIZE);
 -      EMACS_INT this;
 +      int trytry = min (total - how_much, READ_BUF_SIZE);
 +      ptrdiff_t this;
  
        if (not_regular)
          {
             care of marker adjustment.  By this way, we can run Lisp
             program safely before decoding the inserted text.  */
          Lisp_Object unwind_data;
 -        int count1 = SPECPDL_INDEX ();
 +        ptrdiff_t count1 = SPECPDL_INDEX ();
  
          unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
                               Fcons (BVAR (current_buffer, undo_list),
                      visit);
        if (! NILP (insval))
        {
 -        CHECK_NUMBER (insval);
 +        if (! RANGED_INTEGERP (0, insval, ZV - PT))
 +          wrong_type_argument (intern ("inserted-chars"), insval);
          inserted = XFASTINT (insval);
        }
      }
    if (inserted > 0)
      {
        /* Don't run point motion or modification hooks when decoding.  */
 -      int count1 = SPECPDL_INDEX ();
 -      EMACS_INT old_inserted = inserted;
 +      ptrdiff_t count1 = SPECPDL_INDEX ();
 +      ptrdiff_t old_inserted = inserted;
        specbind (Qinhibit_point_motion_hooks, Qt);
        specbind (Qinhibit_modification_hooks, Qt);
  
        {
          insval = call3 (Qformat_decode,
                          Qnil, make_number (inserted), visit);
 -        CHECK_NUMBER (insval);
 +        if (! RANGED_INTEGERP (0, insval, ZV - PT))
 +          wrong_type_argument (intern ("inserted-chars"), insval);
          inserted = XFASTINT (insval);
        }
        else
             Hence we temporarily save `point' and `inserted' here and
             restore `point' iff format-decode did not insert or delete
             any text.  Otherwise we leave `point' at point-min.  */
 -        EMACS_INT opoint = PT;
 -        EMACS_INT opoint_byte = PT_BYTE;
 -        EMACS_INT oinserted = ZV - BEGV;
 -        int ochars_modiff = CHARS_MODIFF;
 +        ptrdiff_t opoint = PT;
 +        ptrdiff_t opoint_byte = PT_BYTE;
 +        ptrdiff_t oinserted = ZV - BEGV;
 +        EMACS_INT ochars_modiff = CHARS_MODIFF;
  
          TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
          insval = call3 (Qformat_decode,
                          Qnil, make_number (oinserted), visit);
 -        CHECK_NUMBER (insval);
 +        if (! RANGED_INTEGERP (0, insval, ZV - PT))
 +          wrong_type_argument (intern ("inserted-chars"), insval);
          if (ochars_modiff == CHARS_MODIFF)
            /* format_decode didn't modify buffer's characters => move
               point back to position before inserted text and leave
              insval = call1 (XCAR (p), make_number (inserted));
              if (!NILP (insval))
                {
 -                CHECK_NUMBER (insval);
 +                if (! RANGED_INTEGERP (0, insval, ZV - PT))
 +                  wrong_type_argument (intern ("inserted-chars"), insval);
                  inserted = XFASTINT (insval);
                }
            }
            {
              /* For the rationale of this see the comment on
                 format-decode above.  */
 -            EMACS_INT opoint = PT;
 -            EMACS_INT opoint_byte = PT_BYTE;
 -            EMACS_INT oinserted = ZV - BEGV;
 -            int ochars_modiff = CHARS_MODIFF;
 +            ptrdiff_t opoint = PT;
 +            ptrdiff_t opoint_byte = PT_BYTE;
 +            ptrdiff_t oinserted = ZV - BEGV;
 +            EMACS_INT ochars_modiff = CHARS_MODIFF;
  
              TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
              insval = call1 (XCAR (p), make_number (oinserted));
              if (!NILP (insval))
                {
 -                CHECK_NUMBER (insval);
 +                if (! RANGED_INTEGERP (0, insval, ZV - PT))
 +                  wrong_type_argument (intern ("inserted-chars"), insval);
                  if (ochars_modiff == CHARS_MODIFF)
                    /* after_insert_file_functions didn't modify
                       buffer's characters => move point back to
@@@ -4542,7 -4537,7 +4544,7 @@@ This calls `write-region-annotate-funct
    int save_errno = 0;
    const char *fn;
    struct stat st;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int count1;
    Lisp_Object handler;
    Lisp_Object visit_file;
@@@ -4942,13 -4937,13 +4944,13 @@@ build_annotations (Lisp_Object start, L
     The return value is negative in case of system call failure.  */
  
  static int
 -a_write (int desc, Lisp_Object string, EMACS_INT pos,
 -       register EMACS_INT nchars, Lisp_Object *annot,
 +a_write (int desc, Lisp_Object string, ptrdiff_t pos,
 +       register ptrdiff_t nchars, Lisp_Object *annot,
         struct coding_system *coding)
  {
    Lisp_Object tem;
 -  EMACS_INT nextpos;
 -  EMACS_INT lastpos = pos + nchars;
 +  ptrdiff_t nextpos;
 +  ptrdiff_t lastpos = pos + nchars;
  
    while (NILP (*annot) || CONSP (*annot))
      {
     are indexes to the string STRING.  */
  
  static int
 -e_write (int desc, Lisp_Object string, EMACS_INT start, EMACS_INT end,
 +e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
         struct coding_system *coding)
  {
    if (STRINGP (string))
        }
        else
        {
 -        EMACS_INT start_byte = CHAR_TO_BYTE (start);
 -        EMACS_INT end_byte = CHAR_TO_BYTE (end);
 +        ptrdiff_t start_byte = CHAR_TO_BYTE (start);
 +        ptrdiff_t end_byte = CHAR_TO_BYTE (end);
  
          coding->src_multibyte = (end - start) < (end_byte - start_byte);
          if (CODING_REQUIRE_ENCODING (coding))
@@@ -5307,7 -5302,7 +5309,7 @@@ A non-nil CURRENT-ONLY argument means s
    int do_handled_files;
    Lisp_Object oquit;
    FILE *stream = NULL;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int orig_minibuffer_auto_raise = minibuffer_auto_raise;
    int old_message_p = 0;
    struct gcpro gcpro1, gcpro2;
diff --combined src/fns.c
+++ b/src/fns.c
@@@ -42,10 -42,6 +42,6 @@@ along with GNU Emacs.  If not, see <htt
  #endif
  #endif /* HAVE_MENUS */
  
- #ifndef NULL
- #define NULL ((POINTER_TYPE *)0)
- #endif
  Lisp_Object Qstring_lessp;
  static Lisp_Object Qprovide, Qrequire;
  static Lisp_Object Qyes_or_no_p_history;
@@@ -250,8 -246,8 +246,8 @@@ If string STR1 is greater, the value i
    N - 1 is the number of characters that match at the beginning.  */)
    (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
  {
 -  register EMACS_INT end1_char, end2_char;
 -  register EMACS_INT i1, i1_byte, i2, i2_byte;
 +  register ptrdiff_t end1_char, end2_char;
 +  register ptrdiff_t i1, i1_byte, i2, i2_byte;
  
    CHECK_STRING (str1);
    CHECK_STRING (str2);
    if (! NILP (end2))
      CHECK_NATNUM (end2);
  
 -  i1 = XINT (start1);
 -  i2 = XINT (start2);
 -
 -  i1_byte = string_char_to_byte (str1, i1);
 -  i2_byte = string_char_to_byte (str2, i2);
 -
    end1_char = SCHARS (str1);
    if (! NILP (end1) && end1_char > XINT (end1))
      end1_char = XINT (end1);
 +  if (end1_char < XINT (start1))
 +    args_out_of_range (str1, start1);
  
    end2_char = SCHARS (str2);
    if (! NILP (end2) && end2_char > XINT (end2))
      end2_char = XINT (end2);
 +  if (end2_char < XINT (start2))
 +    args_out_of_range (str2, start2);
 +
 +  i1 = XINT (start1);
 +  i2 = XINT (start2);
 +
 +  i1_byte = string_char_to_byte (str1, i1);
 +  i2_byte = string_char_to_byte (str2, i2);
  
    while (i1 < end1_char && i2 < end2_char)
      {
@@@ -345,8 -337,8 +341,8 @@@ Case is significant
  Symbols are also allowed; their print names are used instead.  */)
    (register Lisp_Object s1, Lisp_Object s2)
  {
 -  register EMACS_INT end;
 -  register EMACS_INT i1, i1_byte, i2, i2_byte;
 +  register ptrdiff_t end;
 +  register ptrdiff_t i1, i1_byte, i2, i2_byte;
  
    if (SYMBOLP (s1))
      s1 = SYMBOL_NAME (s1);
@@@ -469,8 -461,8 +465,8 @@@ with the original.  */
  struct textprop_rec
  {
    ptrdiff_t argnum;           /* refer to ARGS (arguments of `concat') */
 -  EMACS_INT from;             /* refer to ARGS[argnum] (argument string) */
 -  EMACS_INT to;                       /* refer to VAL (the target string) */
 +  ptrdiff_t from;             /* refer to ARGS[argnum] (argument string) */
 +  ptrdiff_t to;                       /* refer to VAL (the target string) */
  };
  
  static Lisp_Object
@@@ -480,8 -472,8 +476,8 @@@ concat (ptrdiff_t nargs, Lisp_Object *a
    Lisp_Object val;
    register Lisp_Object tail;
    register Lisp_Object this;
 -  EMACS_INT toindex;
 -  EMACS_INT toindex_byte = 0;
 +  ptrdiff_t toindex;
 +  ptrdiff_t toindex_byte = 0;
    register EMACS_INT result_len;
    register EMACS_INT result_len_byte;
    ptrdiff_t argnum;
        {
          /* We must count the number of bytes needed in the string
             as well as the number of characters.  */
 -        EMACS_INT i;
 +        ptrdiff_t i;
          Lisp_Object ch;
          int c;
 -        EMACS_INT this_len_byte;
 +        ptrdiff_t this_len_byte;
  
          if (VECTORP (this) || COMPILEDP (this))
            for (i = 0; i < len; i++)
                CHECK_CHARACTER (ch);
                c = XFASTINT (ch);
                this_len_byte = CHAR_BYTES (c);
 +              if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
 +                string_overflow ();
                result_len_byte += this_len_byte;
                if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
                  some_multibyte = 1;
                CHECK_CHARACTER (ch);
                c = XFASTINT (ch);
                this_len_byte = CHAR_BYTES (c);
 +              if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
 +                string_overflow ();
                result_len_byte += this_len_byte;
                if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
                  some_multibyte = 1;
              if (STRING_MULTIBYTE (this))
                {
                  some_multibyte = 1;
 -                result_len_byte += SBYTES (this);
 +                this_len_byte = SBYTES (this);
                }
              else
 -              result_len_byte += count_size_as_multibyte (SDATA (this),
 -                                                          SCHARS (this));
 +              this_len_byte = count_size_as_multibyte (SDATA (this),
 +                                                       SCHARS (this));
 +            if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
 +              string_overflow ();
 +            result_len_byte += this_len_byte;
            }
        }
  
        result_len += len;
 -      if (STRING_BYTES_BOUND < result_len)
 -      string_overflow ();
 +      if (MOST_POSITIVE_FIXNUM < result_len)
 +      memory_full (SIZE_MAX);
      }
  
    if (! some_multibyte)
    for (argnum = 0; argnum < nargs; argnum++)
      {
        Lisp_Object thislen;
 -      EMACS_INT thisleni = 0;
 -      register EMACS_INT thisindex = 0;
 -      register EMACS_INT thisindex_byte = 0;
 +      ptrdiff_t thisleni = 0;
 +      register ptrdiff_t thisindex = 0;
 +      register ptrdiff_t thisindex_byte = 0;
  
        this = args[argnum];
        if (!CONSP (this))
        if (STRINGP (this) && STRINGP (val)
          && STRING_MULTIBYTE (this) == some_multibyte)
        {
 -        EMACS_INT thislen_byte = SBYTES (this);
 +        ptrdiff_t thislen_byte = SBYTES (this);
  
          memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
          if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
    if (num_textprops > 0)
      {
        Lisp_Object props;
 -      EMACS_INT last_to_end = -1;
 +      ptrdiff_t last_to_end = -1;
  
        for (argnum = 0; argnum < num_textprops; argnum++)
        {
  }
  \f
  static Lisp_Object string_char_byte_cache_string;
 -static EMACS_INT string_char_byte_cache_charpos;
 -static EMACS_INT string_char_byte_cache_bytepos;
 +static ptrdiff_t string_char_byte_cache_charpos;
 +static ptrdiff_t string_char_byte_cache_bytepos;
  
  void
  clear_string_char_byte_cache (void)
  
  /* Return the byte index corresponding to CHAR_INDEX in STRING.  */
  
 -EMACS_INT
 -string_char_to_byte (Lisp_Object string, EMACS_INT char_index)
 +ptrdiff_t
 +string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
  {
 -  EMACS_INT i_byte;
 -  EMACS_INT best_below, best_below_byte;
 -  EMACS_INT best_above, best_above_byte;
 +  ptrdiff_t i_byte;
 +  ptrdiff_t best_below, best_below_byte;
 +  ptrdiff_t best_above, best_above_byte;
  
    best_below = best_below_byte = 0;
    best_above = SCHARS (string);
  \f
  /* Return the character index corresponding to BYTE_INDEX in STRING.  */
  
 -EMACS_INT
 -string_byte_to_char (Lisp_Object string, EMACS_INT byte_index)
 +ptrdiff_t
 +string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
  {
 -  EMACS_INT i, i_byte;
 -  EMACS_INT best_below, best_below_byte;
 -  EMACS_INT best_above, best_above_byte;
 +  ptrdiff_t i, i_byte;
 +  ptrdiff_t best_below, best_below_byte;
 +  ptrdiff_t best_above, best_above_byte;
  
    best_below = best_below_byte = 0;
    best_above = SCHARS (string);
@@@ -894,7 -879,7 +890,7 @@@ static Lisp_Objec
  string_make_multibyte (Lisp_Object string)
  {
    unsigned char *buf;
 -  EMACS_INT nbytes;
 +  ptrdiff_t nbytes;
    Lisp_Object ret;
    USE_SAFE_ALLOCA;
  
@@@ -927,7 -912,7 +923,7 @@@ Lisp_Objec
  string_to_multibyte (Lisp_Object string)
  {
    unsigned char *buf;
 -  EMACS_INT nbytes;
 +  ptrdiff_t nbytes;
    Lisp_Object ret;
    USE_SAFE_ALLOCA;
  
  Lisp_Object
  string_make_unibyte (Lisp_Object string)
  {
 -  EMACS_INT nchars;
 +  ptrdiff_t nchars;
    unsigned char *buf;
    Lisp_Object ret;
    USE_SAFE_ALLOCA;
@@@ -1021,7 -1006,7 +1017,7 @@@ If STRING is multibyte and contains a c
  
    if (STRING_MULTIBYTE (string))
      {
 -      EMACS_INT bytes = SBYTES (string);
 +      ptrdiff_t bytes = SBYTES (string);
        unsigned char *str = (unsigned char *) xmalloc (bytes);
  
        memcpy (str, SDATA (string), bytes);
@@@ -1054,7 -1039,7 +1050,7 @@@ If you're not sure, whether to use `str
    if (! STRING_MULTIBYTE (string))
      {
        Lisp_Object new_string;
 -      EMACS_INT nchars, nbytes;
 +      ptrdiff_t nchars, nbytes;
  
        parse_str_as_multibyte (SDATA (string),
                              SBYTES (string),
@@@ -1103,12 -1088,12 +1099,12 @@@ an error is signaled.  */
  
    if (STRING_MULTIBYTE (string))
      {
 -      EMACS_INT chars = SCHARS (string);
 +      ptrdiff_t chars = SCHARS (string);
        unsigned char *str = (unsigned char *) xmalloc (chars);
 -      EMACS_INT converted = str_to_unibyte (SDATA (string), str, chars, 0);
 +      ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars, 0);
  
        if (converted < chars)
 -      error ("Can't convert the %"pI"dth character to unibyte", converted);
 +      error ("Can't convert the %"pD"dth character to unibyte", converted);
        string = make_unibyte_string ((char *) str, chars);
        xfree (str);
      }
@@@ -1156,19 -1141,27 +1152,19 @@@ value is a new vector that contains th
    (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
  {
    Lisp_Object res;
 -  EMACS_INT size;
 -  EMACS_INT size_byte = 0;
 +  ptrdiff_t size;
    EMACS_INT from_char, to_char;
 -  EMACS_INT from_byte = 0, to_byte = 0;
  
    CHECK_VECTOR_OR_STRING (string);
    CHECK_NUMBER (from);
  
    if (STRINGP (string))
 -    {
 -      size = SCHARS (string);
 -      size_byte = SBYTES (string);
 -    }
 +    size = SCHARS (string);
    else
      size = ASIZE (string);
  
    if (NILP (to))
 -    {
 -      to_char = size;
 -      to_byte = size_byte;
 -    }
 +    to_char = size;
    else
      {
        CHECK_NUMBER (to);
        to_char = XINT (to);
        if (to_char < 0)
        to_char += size;
 -
 -      if (STRINGP (string))
 -      to_byte = string_char_to_byte (string, to_char);
      }
  
    from_char = XINT (from);
    if (from_char < 0)
      from_char += size;
 -  if (STRINGP (string))
 -    from_byte = string_char_to_byte (string, from_char);
 -
    if (!(0 <= from_char && from_char <= to_char && to_char <= size))
      args_out_of_range_3 (string, make_number (from_char),
                         make_number (to_char));
  
    if (STRINGP (string))
      {
 +      ptrdiff_t to_byte =
 +      (NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char));
 +      ptrdiff_t from_byte = string_char_to_byte (string, from_char);
        res = make_specified_string (SSDATA (string) + from_byte,
                                   to_char - from_char, to_byte - from_byte,
                                   STRING_MULTIBYTE (string));
@@@ -1213,41 -1209,47 +1209,41 @@@ If FROM or TO is negative, it counts fr
  With one argument, just copy STRING without its properties.  */)
    (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
  {
 -  EMACS_INT size, size_byte;
 +  ptrdiff_t size;
    EMACS_INT from_char, to_char;
 -  EMACS_INT from_byte, to_byte;
 +  ptrdiff_t from_byte, to_byte;
  
    CHECK_STRING (string);
  
    size = SCHARS (string);
 -  size_byte = SBYTES (string);
  
    if (NILP (from))
 -    from_char = from_byte = 0;
 +    from_char = 0;
    else
      {
        CHECK_NUMBER (from);
        from_char = XINT (from);
        if (from_char < 0)
        from_char += size;
 -
 -      from_byte = string_char_to_byte (string, from_char);
      }
  
    if (NILP (to))
 -    {
 -      to_char = size;
 -      to_byte = size_byte;
 -    }
 +    to_char = size;
    else
      {
        CHECK_NUMBER (to);
 -
        to_char = XINT (to);
        if (to_char < 0)
        to_char += size;
 -
 -      to_byte = string_char_to_byte (string, to_char);
      }
  
    if (!(0 <= from_char && from_char <= to_char && to_char <= size))
      args_out_of_range_3 (string, make_number (from_char),
                         make_number (to_char));
  
 +  from_byte = NILP (from) ? 0 : string_char_to_byte (string, from_char);
 +  to_byte =
 +    NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char);
    return make_specified_string (SSDATA (string) + from_byte,
                                to_char - from_char, to_byte - from_byte,
                                STRING_MULTIBYTE (string));
     both in characters and in bytes.  */
  
  Lisp_Object
 -substring_both (Lisp_Object string, EMACS_INT from, EMACS_INT from_byte,
 -              EMACS_INT to, EMACS_INT to_byte)
 +substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
 +              ptrdiff_t to, ptrdiff_t to_byte)
  {
    Lisp_Object res;
 -  EMACS_INT size;
 +  ptrdiff_t size;
  
    CHECK_VECTOR_OR_STRING (string);
  
@@@ -1595,7 -1597,7 +1591,7 @@@ to be sure of changing the value of `fo
  {
    if (VECTORP (seq))
      {
 -      EMACS_INT i, n;
 +      ptrdiff_t i, n;
  
        for (i = n = 0; i < ASIZE (seq); ++i)
        if (NILP (Fequal (AREF (seq, i), elt)))
      }
    else if (STRINGP (seq))
      {
 -      EMACS_INT i, ibyte, nchars, nbytes, cbytes;
 +      ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
        int c;
  
        for (i = nchars = nbytes = ibyte = 0;
                {
                  unsigned char *from = SDATA (seq) + ibyte;
                  unsigned char *to   = SDATA (tem) + nbytes;
 -                EMACS_INT n;
 +                ptrdiff_t n;
  
                  ++nchars;
                  nbytes += cbytes;
@@@ -2073,7 -2075,7 +2069,7 @@@ internal_equal (register Lisp_Object o1
      case Lisp_Vectorlike:
        {
        register int i;
 -      EMACS_INT size = ASIZE (o1);
 +      ptrdiff_t size = ASIZE (o1);
        /* Pseudovectors have the type encoded in the size field, so this test
           actually checks that the objects have the same type as well as the
           same size.  */
@@@ -2140,7 -2142,7 +2136,7 @@@ DEFUN ("fillarray", Ffillarray, Sfillar
  ARRAY is a vector, string, char-table, or bool-vector.  */)
    (Lisp_Object array, Lisp_Object item)
  {
 -  register EMACS_INT size, idx;
 +  register ptrdiff_t size, idx;
  
    if (VECTORP (array))
      {
        {
          unsigned char str[MAX_MULTIBYTE_LENGTH];
          int len = CHAR_STRING (charval, str);
 -        EMACS_INT size_byte = SBYTES (array);
 +        ptrdiff_t size_byte = SBYTES (array);
  
          if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
              || SCHARS (array) * len != size_byte)
    else if (BOOL_VECTOR_P (array))
      {
        register unsigned char *p = XBOOL_VECTOR (array)->data;
 -      EMACS_INT size_in_chars;
 -      size = XBOOL_VECTOR (array)->size;
 -      size_in_chars
 -      = ((size + BOOL_VECTOR_BITS_PER_CHAR - 1)
 -         / BOOL_VECTOR_BITS_PER_CHAR);
 +      size =
 +      ((XBOOL_VECTOR (array)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
 +       / BOOL_VECTOR_BITS_PER_CHAR);
  
 -      if (size_in_chars)
 +      if (size)
        {
 -        memset (p, ! NILP (item) ? -1 : 0, size_in_chars);
 +        memset (p, ! NILP (item) ? -1 : 0, size);
  
          /* Clear any extraneous bits in the last byte.  */
 -        p[size_in_chars - 1] &= (1 << (size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
 +        p[size - 1] &= (1 << (size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
        }
      }
    else
@@@ -2206,7 -2210,7 +2202,7 @@@ DEFUN ("clear-string", Fclear_string, S
  This makes STRING unibyte and may change its length.  */)
    (Lisp_Object string)
  {
 -  EMACS_INT len;
 +  ptrdiff_t len;
    CHECK_STRING (string);
    len = SBYTES (string);
    memset (SDATA (string), 0, len);
@@@ -2316,12 -2320,12 +2312,12 @@@ mapcar1 (EMACS_INT leni, Lisp_Object *v
      }
    else if (STRINGP (seq))
      {
 -      EMACS_INT i_byte;
 +      ptrdiff_t i_byte;
  
        for (i = 0, i_byte = 0; i < leni;)
        {
          int c;
 -        EMACS_INT i_before = i;
 +        ptrdiff_t i_before = i;
  
          FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
          XSETFASTINT (dummy, c);
@@@ -2354,8 -2358,7 +2350,8 @@@ SEQUENCE may be a list, a vector, a boo
  {
    Lisp_Object len;
    register EMACS_INT leni;
 -  ptrdiff_t i, nargs;
 +  EMACS_INT nargs;
 +  ptrdiff_t i;
    register Lisp_Object *args;
    struct gcpro gcpro1;
    Lisp_Object ret;
@@@ -2642,7 -2645,7 +2638,7 @@@ The normal messages at start and end o
  
    if (NILP (tem))
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        int nesting = 0;
  
        /* This is to make sure that loadup.el gives a clear picture
@@@ -2945,9 -2948,9 +2941,9 @@@ static const short base64_char_to_value
     base64 characters.  */
  
  
 -static EMACS_INT base64_encode_1 (const char *, char *, EMACS_INT, int, int);
 -static EMACS_INT base64_decode_1 (const char *, char *, EMACS_INT, int,
 -                                EMACS_INT *);
 +static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, int, int);
 +static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, int,
 +                                ptrdiff_t *);
  
  DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
         2, 3, "r",
@@@ -2958,9 -2961,9 +2954,9 @@@ into shorter lines.  */
    (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
  {
    char *encoded;
 -  EMACS_INT allength, length;
 -  EMACS_INT ibeg, iend, encoded_length;
 -  EMACS_INT old_pos = PT;
 +  ptrdiff_t allength, length;
 +  ptrdiff_t ibeg, iend, encoded_length;
 +  ptrdiff_t old_pos = PT;
    USE_SAFE_ALLOCA;
  
    validate_region (&beg, &end);
@@@ -3016,7 -3019,7 +3012,7 @@@ Optional second argument NO-LINE-BREAK 
  into shorter lines.  */)
    (Lisp_Object string, Lisp_Object no_line_break)
  {
 -  EMACS_INT allength, length, encoded_length;
 +  ptrdiff_t allength, length, encoded_length;
    char *encoded;
    Lisp_Object encoded_string;
    USE_SAFE_ALLOCA;
    return encoded_string;
  }
  
 -static EMACS_INT
 -base64_encode_1 (const char *from, char *to, EMACS_INT length,
 +static ptrdiff_t
 +base64_encode_1 (const char *from, char *to, ptrdiff_t length,
                 int line_break, int multibyte)
  {
    int counter = 0;
 -  EMACS_INT i = 0;
 +  ptrdiff_t i = 0;
    char *e = to;
    int c;
    unsigned int value;
@@@ -3156,11 -3159,11 +3152,11 @@@ Return the length of the decoded text
  If the region can't be decoded, signal an error and don't modify the buffer.  */)
    (Lisp_Object beg, Lisp_Object end)
  {
 -  EMACS_INT ibeg, iend, length, allength;
 +  ptrdiff_t ibeg, iend, length, allength;
    char *decoded;
 -  EMACS_INT old_pos = PT;
 -  EMACS_INT decoded_length;
 -  EMACS_INT inserted_chars;
 +  ptrdiff_t old_pos = PT;
 +  ptrdiff_t decoded_length;
 +  ptrdiff_t inserted_chars;
    int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
    USE_SAFE_ALLOCA;
  
@@@ -3218,7 -3221,7 +3214,7 @@@ DEFUN ("base64-decode-string", Fbase64_
    (Lisp_Object string)
  {
    char *decoded;
 -  EMACS_INT length, decoded_length;
 +  ptrdiff_t length, decoded_length;
    Lisp_Object decoded_string;
    USE_SAFE_ALLOCA;
  
     form.  If NCHARS_RETURN is not NULL, store the number of produced
     characters in *NCHARS_RETURN.  */
  
 -static EMACS_INT
 -base64_decode_1 (const char *from, char *to, EMACS_INT length,
 -               int multibyte, EMACS_INT *nchars_return)
 +static ptrdiff_t
 +base64_decode_1 (const char *from, char *to, ptrdiff_t length,
 +               int multibyte, ptrdiff_t *nchars_return)
  {
 -  EMACS_INT i = 0;            /* Used inside READ_QUADRUPLET_BYTE */
 +  ptrdiff_t i = 0;            /* Used inside READ_QUADRUPLET_BYTE */
    char *e = to;
    unsigned char c;
    unsigned long value;
 -  EMACS_INT nchars = 0;
 +  ptrdiff_t nchars = 0;
  
    while (1)
      {
@@@ -3425,31 -3428,23 +3421,31 @@@ get_key_arg (Lisp_Object key, ptrdiff_
  
  
  /* Return a Lisp vector which has the same contents as VEC but has
 -   size NEW_SIZE, NEW_SIZE >= VEC->size.  Entries in the resulting
 -   vector that are not copied from VEC are set to INIT.  */
 +   at least INCR_MIN more entries, where INCR_MIN is positive.
 +   If NITEMS_MAX is not -1, do not grow the vector to be any larger
 +   than NITEMS_MAX.  Entries in the resulting
 +   vector that are not copied from VEC are set to nil.  */
  
  Lisp_Object
 -larger_vector (Lisp_Object vec, EMACS_INT new_size, Lisp_Object init)
 +larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
  {
    struct Lisp_Vector *v;
 -  EMACS_INT i, old_size;
 -
 +  ptrdiff_t i, incr, incr_max, old_size, new_size;
 +  ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
 +  ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
 +                   ? nitems_max : C_language_max);
    xassert (VECTORP (vec));
 +  xassert (0 < incr_min && -1 <= nitems_max);
    old_size = ASIZE (vec);
 -  xassert (new_size >= old_size);
 -
 +  incr_max = n_max - old_size;
 +  incr = max (incr_min, min (old_size >> 1, incr_max));
 +  if (incr_max < incr)
 +    memory_full (SIZE_MAX);
 +  new_size = old_size + incr;
    v = allocate_vector (new_size);
    memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
    for (i = old_size; i < new_size; ++i)
 -    v->contents[i] = init;
 +    v->contents[i] = Qnil;
    XSETVECTOR (vec, v);
    return vec;
  }
@@@ -3570,10 -3565,6 +3566,10 @@@ hashfn_user_defined (struct Lisp_Hash_T
    return XUINT (hash);
  }
  
 +/* An upper bound on the size of a hash table index.  It must fit in
 +   ptrdiff_t and be a valid Emacs fixnum.  */
 +#define INDEX_SIZE_BOUND \
 +  ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / sizeof (Lisp_Object)))
  
  /* Create and initialize a new hash table.
  
@@@ -3604,8 -3595,7 +3600,8 @@@ make_hash_table (Lisp_Object test, Lisp
  {
    struct Lisp_Hash_Table *h;
    Lisp_Object table;
 -  EMACS_INT index_size, i, sz;
 +  EMACS_INT index_size, sz;
 +  ptrdiff_t i;
    double index_float;
  
    /* Preconditions.  */
  
    sz = XFASTINT (size);
    index_float = sz / XFLOAT_DATA (rehash_threshold);
 -  index_size = (index_float < MOST_POSITIVE_FIXNUM + 1
 +  index_size = (index_float < INDEX_SIZE_BOUND + 1
                ? next_almost_prime (index_float)
 -              : MOST_POSITIVE_FIXNUM + 1);
 -  if (MOST_POSITIVE_FIXNUM < max (index_size, 2 * sz))
 +              : INDEX_SIZE_BOUND + 1);
 +  if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
      error ("Hash table too large");
  
    /* Allocate a table and initialize it.  */
@@@ -3726,9 -3716,9 +3722,9 @@@ maybe_resize_hash_table (struct Lisp_Ha
  {
    if (NILP (h->next_free))
      {
 -      EMACS_INT old_size = HASH_TABLE_SIZE (h);
 -      EMACS_INT i, new_size, index_size;
 -      EMACS_INT nsize;
 +      ptrdiff_t old_size = HASH_TABLE_SIZE (h);
 +      EMACS_INT new_size, index_size, nsize;
 +      ptrdiff_t i;
        double index_float;
  
        if (INTEGERP (h->rehash_size))
        else
        {
          double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
 -        if (float_new_size < MOST_POSITIVE_FIXNUM + 1)
 +        if (float_new_size < INDEX_SIZE_BOUND + 1)
            {
              new_size = float_new_size;
              if (new_size <= old_size)
                new_size = old_size + 1;
            }
          else
 -          new_size = MOST_POSITIVE_FIXNUM + 1;
 +          new_size = INDEX_SIZE_BOUND + 1;
        }
        index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
 -      index_size = (index_float < MOST_POSITIVE_FIXNUM + 1
 +      index_size = (index_float < INDEX_SIZE_BOUND + 1
                    ? next_almost_prime (index_float)
 -                  : MOST_POSITIVE_FIXNUM + 1);
 +                  : INDEX_SIZE_BOUND + 1);
        nsize = max (index_size, 2 * new_size);
 -      if (nsize > MOST_POSITIVE_FIXNUM)
 +      if (INDEX_SIZE_BOUND < nsize)
        error ("Hash table too large to resize");
  
 -      h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
 -      h->next = larger_vector (h->next, new_size, Qnil);
 -      h->hash = larger_vector (h->hash, new_size, Qnil);
 +      h->key_and_value = larger_vector (h->key_and_value,
 +                                      2 * (new_size - old_size), -1);
 +      h->next = larger_vector (h->next, new_size - old_size, -1);
 +      h->hash = larger_vector (h->hash, new_size - old_size, -1);
        h->index = Fmake_vector (make_number (index_size), Qnil);
  
        /* Update the free list.  Do it so that new entries are added at
        if (!NILP (HASH_HASH (h, i)))
          {
            EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
 -          EMACS_INT start_of_bucket = hash_code % ASIZE (h->index);
 +          ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
            HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
            HASH_INDEX (h, start_of_bucket) = make_number (i);
          }
@@@ -3813,7 -3802,7 +3809,7 @@@ hash_lookup (struct Lisp_Hash_Table *h
    /* We need not gcpro idx since it's either an integer or nil.  */
    while (!NILP (idx))
      {
 -      EMACS_INT i = XFASTINT (idx);
 +      ptrdiff_t i = XFASTINT (idx);
        if (EQ (key, HASH_KEY (h, i))
          || (h->cmpfn
              && h->cmpfn (h, key, hash_code,
@@@ -3865,7 -3854,7 +3861,7 @@@ static voi
  hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
  {
    EMACS_UINT hash_code;
 -  EMACS_INT start_of_bucket;
 +  ptrdiff_t start_of_bucket;
    Lisp_Object idx, prev;
  
    hash_code = h->hashfn (h, key);
    /* We need not gcpro idx, prev since they're either integers or nil.  */
    while (!NILP (idx))
      {
 -      EMACS_INT i = XFASTINT (idx);
 +      ptrdiff_t i = XFASTINT (idx);
  
        if (EQ (key, HASH_KEY (h, i))
          || (h->cmpfn
@@@ -3914,7 -3903,7 +3910,7 @@@ hash_clear (struct Lisp_Hash_Table *h
  {
    if (h->count > 0)
      {
 -      EMACS_INT i, size = HASH_TABLE_SIZE (h);
 +      ptrdiff_t i, size = HASH_TABLE_SIZE (h);
  
        for (i = 0; i < size; ++i)
        {
@@@ -3952,7 -3941,7 +3948,7 @@@ init_weak_hash_tables (void
  static int
  sweep_weak_table (struct Lisp_Hash_Table *h, int remove_entries_p)
  {
 -  EMACS_INT bucket, n;
 +  ptrdiff_t bucket, n;
    int marked;
  
    n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
        prev = Qnil;
        for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
        {
 -        EMACS_INT i = XFASTINT (idx);
 +        ptrdiff_t i = XFASTINT (idx);
          int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
          int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
          int remove_p;
@@@ -4533,7 -4522,7 +4529,7 @@@ FUNCTION is called with two arguments, 
  {
    struct Lisp_Hash_Table *h = check_hash_table (table);
    Lisp_Object args[3];
 -  EMACS_INT i;
 +  ptrdiff_t i;
  
    for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
      if (!NILP (HASH_HASH (h, i)))
@@@ -4582,9 -4571,10 +4578,9 @@@ static Lisp_Objec
  secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
  {
    int i;
 -  EMACS_INT size;
 -  EMACS_INT size_byte = 0;
 +  ptrdiff_t size;
    EMACS_INT start_char = 0, end_char = 0;
 -  EMACS_INT start_byte = 0, end_byte = 0;
 +  ptrdiff_t start_byte, end_byte;
    register EMACS_INT b, e;
    register struct buffer *bp;
    EMACS_INT temp;
        object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
  
        size = SCHARS (object);
 -      size_byte = SBYTES (object);
  
        if (!NILP (start))
        {
  
          if (start_char < 0)
            start_char += size;
 -
 -        start_byte = string_char_to_byte (object, start_char);
        }
  
        if (NILP (end))
 -      {
 -        end_char = size;
 -        end_byte = size_byte;
 -      }
 +      end_char = size;
        else
        {
          CHECK_NUMBER (end);
  
          if (end_char < 0)
            end_char += size;
 -
 -        end_byte = string_char_to_byte (object, end_char);
        }
  
        if (!(0 <= start_char && start_char <= end_char && end_char <= size))
        args_out_of_range_3 (object, make_number (start_char),
                             make_number (end_char));
 +
 +      start_byte = NILP (start) ? 0 : string_char_to_byte (object, start_char);
 +      end_byte =
 +      NILP (end) ? SBYTES (object) : string_char_to_byte (object, end_char);
      }
    else
      {
  
        if (STRING_MULTIBYTE (object))
        object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
 +      start_byte = 0;
 +      end_byte = SBYTES (object);
      }
  
    if (EQ (algorithm, Qmd5))
    digest = make_uninit_string (digest_size * 2);
  
    hash_func (SSDATA (object) + start_byte,
 -           SBYTES (object) - (size_byte - end_byte),
 +           end_byte - start_byte,
             SSDATA (digest));
  
    if (NILP (binary))
diff --combined src/font.h
@@@ -469,11 -469,12 +469,12 @@@ struct font_bitma
    } while (0)
  
  #define XFONT_SPEC(p) \
-   (eassert (FONT_SPEC_P(p)), (struct font_spec *) XPNTR (p))
+   (eassert (FONT_SPEC_P (p)), (struct font_spec *) XUNTAG (p, Lisp_Vectorlike))
  #define XFONT_ENTITY(p)       \
-   (eassert (FONT_ENTITY_P(p)), (struct font_entity *) XPNTR (p))
+   (eassert (FONT_ENTITY_P (p)), \
+    (struct font_entity *) XUNTAG (p, Lisp_Vectorlike))
  #define XFONT_OBJECT(p)       \
-   (eassert (FONT_OBJECT_P(p)), (struct font *) XPNTR (p))
+   (eassert (FONT_OBJECT_P (p)), (struct font *) XUNTAG (p, Lisp_Vectorlike))
  #define XSETFONT(a, b) (XSETPSEUDOVECTOR (a, b, PVEC_FONT))
  
  /* Number of pt per inch (from the TeXbook).  */
@@@ -793,7 -794,7 +794,7 @@@ extern int font_unparse_fcname (Lisp_Ob
  extern void register_font_driver (struct font_driver *driver, FRAME_PTR f);
  extern void free_font_driver_list (FRAME_PTR f);
  extern Lisp_Object font_update_drivers (FRAME_PTR f, Lisp_Object list);
 -extern Lisp_Object font_range (EMACS_INT, EMACS_INT *,
 +extern Lisp_Object font_range (ptrdiff_t, ptrdiff_t *,
                               struct window *, struct face *,
                               Lisp_Object);
  extern void font_fill_lglyph_metrics (Lisp_Object, Lisp_Object);
diff --combined src/frame.h
@@@ -322,7 -322,7 +322,7 @@@ struct fram
      struct x_output *x;         /* xterm.h */
      struct w32_output *w32;     /* w32term.h */
      struct ns_output *ns;       /* nsterm.h */
 -    EMACS_INT nothing;
 +    intptr_t nothing;
    }
    output_data;
  
  
  typedef struct frame *FRAME_PTR;
  
- #define XFRAME(p) (eassert (FRAMEP(p)),(struct frame *) XPNTR (p))
+ #define XFRAME(p) \
+   (eassert (FRAMEP (p)), (struct frame *) XUNTAG (p, Lisp_Vectorlike))
  #define XSETFRAME(a, b) (XSETPSEUDOVECTOR (a, b, PVEC_FRAME))
  
  /* Given a window, return its frame as a Lisp_Object.  */
diff --combined src/gnutls.c
@@@ -200,8 -200,12 +200,12 @@@ init_gnutls_functions (Lisp_Object libr
  
    max_log_level = global_gnutls_log_level;
  
-   GNUTLS_LOG2 (1, max_log_level, "GnuTLS library loaded:",
-              SDATA (Fget (Qgnutls_dll, QCloaded_from)));
+   {
+     Lisp_Object name = CAR_SAFE (Fget (Qgnutls_dll, QCloaded_from));
+     GNUTLS_LOG2 (1, max_log_level, "GnuTLS library loaded:",
+                  STRINGP (name) ? (const char *) SDATA (name) : "unknown");
+   }
    return 1;
  }
  
@@@ -347,11 -351,11 +351,11 @@@ emacs_gnutls_transport_set_errno (gnutl
    fn_gnutls_transport_set_errno (state, err);
  }
  
 -EMACS_INT
 -emacs_gnutls_write (struct Lisp_Process *proc, const char *buf, EMACS_INT nbyte)
 +ptrdiff_t
 +emacs_gnutls_write (struct Lisp_Process *proc, const char *buf, ptrdiff_t nbyte)
  {
    ssize_t rtnval = 0;
 -  EMACS_INT bytes_written;
 +  ptrdiff_t bytes_written;
    gnutls_session_t state = proc->gnutls_state;
  
    if (proc->gnutls_initstage != GNUTLS_STAGE_READY)
    return (bytes_written);
  }
  
 -EMACS_INT
 -emacs_gnutls_read (struct Lisp_Process *proc, char *buf, EMACS_INT nbyte)
 +ptrdiff_t
 +emacs_gnutls_read (struct Lisp_Process *proc, char *buf, ptrdiff_t nbyte)
  {
    ssize_t rtnval;
    gnutls_session_t state = proc->gnutls_state;
          {
            proc->gnutls_handshakes_tried++;
            emacs_gnutls_handshake (proc);
-           GNUTLS_LOG2i (5, log_level, "Retried handshake", 
+           GNUTLS_LOG2i (5, log_level, "Retried handshake",
                          proc->gnutls_handshakes_tried);
            return -1;
          }
@@@ -595,7 -599,7 +599,7 @@@ usage: (gnutls-error-fatalp ERROR)  */
        }
      }
  
 -  if (!NUMBERP (err))
 +  if (! TYPE_RANGED_INTEGERP (int, err))
      error ("Not an error symbol or code");
  
    if (0 == fn_gnutls_error_is_fatal (XINT (err)))
@@@ -627,7 -631,7 +631,7 @@@ usage: (gnutls-error-string ERROR)  */
        }
      }
  
 -  if (!NUMBERP (err))
 +  if (! TYPE_RANGED_INTEGERP (int, err))
      return build_string ("Not an error symbol or code");
  
    return build_string (fn_gnutls_strerror (XINT (err)));
@@@ -800,10 -804,7 +804,10 @@@ one trustfile (usually a CA bundle).  *
      error ("gnutls-boot: invalid :hostname parameter");
    c_hostname = SSDATA (hostname);
  
 -  if (NUMBERP (loglevel))
 +  state = XPROCESS (proc)->gnutls_state;
 +  XPROCESS (proc)->gnutls_p = 1;
 +
 +  if (TYPE_RANGED_INTEGERP (int, loglevel))
      {
        fn_gnutls_global_set_log_function (gnutls_log_function);
        fn_gnutls_global_set_log_level (XINT (loglevel));
diff --combined src/gtkutil.c
@@@ -1090,7 -1090,9 +1090,9 @@@ xg_create_frame_widgets (FRAME_PTR f
    GtkWidget *wtop;
    GtkWidget *wvbox, *whbox;
    GtkWidget *wfixed;
+ #ifndef HAVE_GTK3
    GtkRcStyle *style;
+ #endif
    char *title = 0;
  
    BLOCK_INPUT;
@@@ -1632,7 -1634,7 +1634,7 @@@ xg_maybe_add_timer (gpointer data
  static int
  xg_dialog_run (FRAME_PTR f, GtkWidget *w)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct xg_dialog_data dd;
  
    xg_set_screen (w, f);
@@@ -4287,6 -4289,7 +4289,6 @@@ xg_make_tool_item (FRAME_PTR f
           rather than the GtkButton specific signals "enter" and
           "leave", so we can have only one callback.  The event
           will tell us what kind of event it is.  */
 -      /* The EMACS_INT cast avoids a warning. */
        g_signal_connect (G_OBJECT (weventbox),
                          "enter-notify-event",
                          G_CALLBACK (xg_tool_bar_help_callback),
@@@ -4412,17 -4415,20 +4414,17 @@@ update_frame_tool_bar (FRAME_PTR f
  
    BLOCK_INPUT;
  
 -  if (INTEGERP (Vtool_bar_button_margin)
 -      && XINT (Vtool_bar_button_margin) > 0)
 +  if (RANGED_INTEGERP (1, Vtool_bar_button_margin, INT_MAX))
      {
        hmargin = XFASTINT (Vtool_bar_button_margin);
        vmargin = XFASTINT (Vtool_bar_button_margin);
      }
    else if (CONSP (Vtool_bar_button_margin))
      {
 -      if (INTEGERP (XCAR (Vtool_bar_button_margin))
 -          && XINT (XCAR (Vtool_bar_button_margin)) > 0)
 +      if (RANGED_INTEGERP (1, XCAR (Vtool_bar_button_margin), INT_MAX))
          hmargin = XFASTINT (XCAR (Vtool_bar_button_margin));
  
 -      if (INTEGERP (XCDR (Vtool_bar_button_margin))
 -          && XINT (XCDR (Vtool_bar_button_margin)) > 0)
 +      if (RANGED_INTEGERP (1, XCDR (Vtool_bar_button_margin), INT_MAX))
          vmargin = XFASTINT (XCDR (Vtool_bar_button_margin));
      }
  
diff --combined src/insdel.c
@@@ -31,19 -31,15 +31,15 @@@ along with GNU Emacs.  If not, see <htt
  #include "blockinput.h"
  #include "region-cache.h"
  
- #ifndef NULL
- #define NULL 0
- #endif
  static void insert_from_string_1 (Lisp_Object string,
 -                                EMACS_INT pos, EMACS_INT pos_byte,
 -                                EMACS_INT nchars, EMACS_INT nbytes,
 +                                ptrdiff_t pos, ptrdiff_t pos_byte,
 +                                ptrdiff_t nchars, ptrdiff_t nbytes,
                                  int inherit, int before_markers);
  static void insert_from_buffer_1 (struct buffer *buf,
 -                                EMACS_INT from, EMACS_INT nchars,
 +                                ptrdiff_t from, ptrdiff_t nchars,
                                  int inherit);
 -static void gap_left (EMACS_INT charpos, EMACS_INT bytepos, int newgap);
 -static void gap_right (EMACS_INT charpos, EMACS_INT bytepos);
 +static void gap_left (ptrdiff_t charpos, ptrdiff_t bytepos, int newgap);
 +static void gap_right (ptrdiff_t charpos, ptrdiff_t bytepos);
  
  static Lisp_Object Fcombine_after_change_execute (void);
  
@@@ -64,7 -60,7 +60,7 @@@ static Lisp_Object combine_after_change
  
  Lisp_Object Qinhibit_modification_hooks;
  
 -static void signal_before_change (EMACS_INT, EMACS_INT, EMACS_INT *);
 +static void signal_before_change (ptrdiff_t, ptrdiff_t, ptrdiff_t *);
  \f
  #define CHECK_MARKERS()                               \
    do                                          \
@@@ -97,7 -93,7 +93,7 @@@ check_markers (void
     Note that this can quit!  */
  
  void
 -move_gap (EMACS_INT charpos)
 +move_gap (ptrdiff_t charpos)
  {
    move_gap_both (charpos, charpos_to_bytepos (charpos));
  }
     Note that this can quit!  */
  
  void
 -move_gap_both (EMACS_INT charpos, EMACS_INT bytepos)
 +move_gap_both (ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    if (bytepos < GPT_BYTE)
      gap_left (charpos, bytepos, 0);
     If NEWGAP is nonzero, then don't update beg_unchanged and end_unchanged.  */
  
  static void
 -gap_left (EMACS_INT charpos, EMACS_INT bytepos, int newgap)
 +gap_left (ptrdiff_t charpos, ptrdiff_t bytepos, int newgap)
  {
    register unsigned char *to, *from;
 -  register EMACS_INT i;
 -  EMACS_INT new_s1;
 +  register ptrdiff_t i;
 +  ptrdiff_t new_s1;
  
    if (!newgap)
      BUF_COMPUTE_UNCHANGED (current_buffer, charpos, GPT);
     and CHARPOS is the corresponding char position.  */
  
  static void
 -gap_right (EMACS_INT charpos, EMACS_INT bytepos)
 +gap_right (ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    register unsigned char *to, *from;
 -  register EMACS_INT i;
 -  EMACS_INT new_s1;
 +  register ptrdiff_t i;
 +  ptrdiff_t new_s1;
  
    BUF_COMPUTE_UNCHANGED (current_buffer, charpos, GPT);
  
     or inside of the range being deleted.  */
  
  void
 -adjust_markers_for_delete (EMACS_INT from, EMACS_INT from_byte,
 -                         EMACS_INT to, EMACS_INT to_byte)
 +adjust_markers_for_delete (ptrdiff_t from, ptrdiff_t from_byte,
 +                         ptrdiff_t to, ptrdiff_t to_byte)
  {
    Lisp_Object marker;
    register struct Lisp_Marker *m;
 -  register EMACS_INT charpos;
 +  register ptrdiff_t charpos;
  
    for (m = BUF_MARKERS (current_buffer); m; m = m->next)
      {
     or BEFORE_MARKERS is true.  */
  
  static void
 -adjust_markers_for_insert (EMACS_INT from, EMACS_INT from_byte,
 -                         EMACS_INT to, EMACS_INT to_byte, int before_markers)
 +adjust_markers_for_insert (ptrdiff_t from, ptrdiff_t from_byte,
 +                         ptrdiff_t to, ptrdiff_t to_byte, int before_markers)
  {
    struct Lisp_Marker *m;
    int adjusted = 0;
 -  EMACS_INT nchars = to - from;
 -  EMACS_INT nbytes = to_byte - from_byte;
 +  ptrdiff_t nchars = to - from;
 +  ptrdiff_t nbytes = to_byte - from_byte;
  
    for (m = BUF_MARKERS (current_buffer); m; m = m->next)
      {
     intervals.  */
  
  static void
 -adjust_point (EMACS_INT nchars, EMACS_INT nbytes)
 +adjust_point (ptrdiff_t nchars, ptrdiff_t nbytes)
  {
    SET_BUF_PT_BOTH (current_buffer, PT + nchars, PT_BYTE + nbytes);
    /* In a single-byte buffer, the two positions must be equal.  */
     an insertion.  */
  
  static void
 -adjust_markers_for_replace (EMACS_INT from, EMACS_INT from_byte,
 -                          EMACS_INT old_chars, EMACS_INT old_bytes,
 -                          EMACS_INT new_chars, EMACS_INT new_bytes)
 +adjust_markers_for_replace (ptrdiff_t from, ptrdiff_t from_byte,
 +                          ptrdiff_t old_chars, ptrdiff_t old_bytes,
 +                          ptrdiff_t new_chars, ptrdiff_t new_bytes)
  {
    register struct Lisp_Marker *m;
 -  EMACS_INT prev_to_byte = from_byte + old_bytes;
 -  EMACS_INT diff_chars = new_chars - old_chars;
 -  EMACS_INT diff_bytes = new_bytes - old_bytes;
 +  ptrdiff_t prev_to_byte = from_byte + old_bytes;
 +  ptrdiff_t diff_chars = new_chars - old_chars;
 +  ptrdiff_t diff_bytes = new_bytes - old_bytes;
  
    for (m = BUF_MARKERS (current_buffer); m; m = m->next)
      {
@@@ -394,13 -390,13 +390,13 @@@ buffer_overflow (void
  /* Make the gap NBYTES_ADDED bytes longer.  */
  
  static void
 -make_gap_larger (EMACS_INT nbytes_added)
 +make_gap_larger (ptrdiff_t nbytes_added)
  {
    Lisp_Object tem;
 -  EMACS_INT real_gap_loc;
 -  EMACS_INT real_gap_loc_byte;
 -  EMACS_INT old_gap_size;
 -  EMACS_INT current_size = Z_BYTE - BEG_BYTE + GAP_SIZE;
 +  ptrdiff_t real_gap_loc;
 +  ptrdiff_t real_gap_loc_byte;
 +  ptrdiff_t old_gap_size;
 +  ptrdiff_t current_size = Z_BYTE - BEG_BYTE + GAP_SIZE;
    enum { enough_for_a_while = 2000 };
  
    if (BUF_BYTES_MAX - current_size < nbytes_added)
  /* Make the gap NBYTES_REMOVED bytes shorter.  */
  
  static void
 -make_gap_smaller (EMACS_INT nbytes_removed)
 +make_gap_smaller (ptrdiff_t nbytes_removed)
  {
    Lisp_Object tem;
 -  EMACS_INT real_gap_loc;
 -  EMACS_INT real_gap_loc_byte;
 -  EMACS_INT real_Z;
 -  EMACS_INT real_Z_byte;
 -  EMACS_INT real_beg_unchanged;
 -  EMACS_INT new_gap_size;
 +  ptrdiff_t real_gap_loc;
 +  ptrdiff_t real_gap_loc_byte;
 +  ptrdiff_t real_Z;
 +  ptrdiff_t real_Z_byte;
 +  ptrdiff_t real_beg_unchanged;
 +  ptrdiff_t new_gap_size;
  
    /* Make sure the gap is at least 20 bytes.  */
    if (GAP_SIZE - nbytes_removed < 20)
  #endif /* USE_MMAP_FOR_BUFFERS || REL_ALLOC || DOUG_LEA_MALLOC */
  
  void
 -make_gap (EMACS_INT nbytes_added)
 +make_gap (ptrdiff_t nbytes_added)
  {
    if (nbytes_added >= 0)
      make_gap_larger (nbytes_added);
  
     Return the number of bytes stored at TO_ADDR.  */
  
 -EMACS_INT
 +ptrdiff_t
  copy_text (const unsigned char *from_addr, unsigned char *to_addr,
 -         EMACS_INT nbytes, int from_multibyte, int to_multibyte)
 +         ptrdiff_t nbytes, int from_multibyte, int to_multibyte)
  {
    if (from_multibyte == to_multibyte)
      {
      }
    else if (from_multibyte)
      {
 -      EMACS_INT nchars = 0;
 -      EMACS_INT bytes_left = nbytes;
 +      ptrdiff_t nchars = 0;
 +      ptrdiff_t bytes_left = nbytes;
  
        while (bytes_left > 0)
        {
     prepare_to_modify_buffer could relocate the text.  */
  
  void
 -insert (const char *string, EMACS_INT nbytes)
 +insert (const char *string, ptrdiff_t nbytes)
  {
    if (nbytes > 0)
      {
 -      EMACS_INT len = chars_in_text ((unsigned char *) string, nbytes), opoint;
 +      ptrdiff_t len = chars_in_text ((unsigned char *) string, nbytes), opoint;
        insert_1_both (string, len, nbytes, 0, 1, 0);
        opoint = PT - len;
        signal_after_change (opoint, 0, len);
  /* Likewise, but inherit text properties from neighboring characters.  */
  
  void
 -insert_and_inherit (const char *string, EMACS_INT nbytes)
 +insert_and_inherit (const char *string, ptrdiff_t nbytes)
  {
    if (nbytes > 0)
      {
 -      EMACS_INT len = chars_in_text ((unsigned char *) string, nbytes), opoint;
 +      ptrdiff_t len = chars_in_text ((unsigned char *) string, nbytes), opoint;
        insert_1_both (string, len, nbytes, 1, 1, 0);
        opoint = PT - len;
        signal_after_change (opoint, 0, len);
@@@ -640,11 -636,11 +636,11 @@@ insert_string (const char *s
     since gc could happen and relocate it.  */
  
  void
 -insert_before_markers (const char *string, EMACS_INT nbytes)
 +insert_before_markers (const char *string, ptrdiff_t nbytes)
  {
    if (nbytes > 0)
      {
 -      EMACS_INT len = chars_in_text ((unsigned char *) string, nbytes), opoint;
 +      ptrdiff_t len = chars_in_text ((unsigned char *) string, nbytes), opoint;
        insert_1_both (string, len, nbytes, 0, 1, 1);
        opoint = PT - len;
        signal_after_change (opoint, 0, len);
  
  void
  insert_before_markers_and_inherit (const char *string,
 -                                 EMACS_INT nbytes)
 +                                 ptrdiff_t nbytes)
  {
    if (nbytes > 0)
      {
 -      EMACS_INT len = chars_in_text ((unsigned char *) string, nbytes), opoint;
 +      ptrdiff_t len = chars_in_text ((unsigned char *) string, nbytes), opoint;
        insert_1_both (string, len, nbytes, 1, 1, 1);
        opoint = PT - len;
        signal_after_change (opoint, 0, len);
  /* Subroutine used by the insert functions above.  */
  
  void
 -insert_1 (const char *string, EMACS_INT nbytes,
 +insert_1 (const char *string, ptrdiff_t nbytes,
          int inherit, int prepare, int before_markers)
  {
    insert_1_both (string, chars_in_text ((unsigned char *) string, nbytes),
     which combine in this way.  Otherwise, return 0.  */
  
  int
 -count_combining_before (const unsigned char *string, EMACS_INT length,
 -                      EMACS_INT pos, EMACS_INT pos_byte)
 +count_combining_before (const unsigned char *string, ptrdiff_t length,
 +                      ptrdiff_t pos, ptrdiff_t pos_byte)
  {
    int len, combining_bytes;
    const unsigned char *p;
  
  int
  count_combining_after (const unsigned char *string,
 -                     EMACS_INT length, EMACS_INT pos, EMACS_INT pos_byte)
 +                     ptrdiff_t length, ptrdiff_t pos, ptrdiff_t pos_byte)
  {
 -  EMACS_INT opos_byte = pos_byte;
 -  EMACS_INT i;
 -  EMACS_INT bytes;
 +  ptrdiff_t opos_byte = pos_byte;
 +  ptrdiff_t i;
 +  ptrdiff_t bytes;
    unsigned char *bufp;
  
    if (NILP (current_buffer->enable_multibyte_characters))
  
  void
  insert_1_both (const char *string,
 -             EMACS_INT nchars, EMACS_INT nbytes,
 +             ptrdiff_t nchars, ptrdiff_t nbytes,
               int inherit, int prepare, int before_markers)
  {
    if (nchars == 0)
     without insert noticing.  */
  
  void
 -insert_from_string (Lisp_Object string, EMACS_INT pos, EMACS_INT pos_byte,
 -                  EMACS_INT length, EMACS_INT length_byte, int inherit)
 +insert_from_string (Lisp_Object string, ptrdiff_t pos, ptrdiff_t pos_byte,
 +                  ptrdiff_t length, ptrdiff_t length_byte, int inherit)
  {
 -  EMACS_INT opoint = PT;
 +  ptrdiff_t opoint = PT;
  
    if (SCHARS (string) == 0)
      return;
  
  void
  insert_from_string_before_markers (Lisp_Object string,
 -                                 EMACS_INT pos, EMACS_INT pos_byte,
 -                                 EMACS_INT length, EMACS_INT length_byte,
 +                                 ptrdiff_t pos, ptrdiff_t pos_byte,
 +                                 ptrdiff_t length, ptrdiff_t length_byte,
                                   int inherit)
  {
 -  EMACS_INT opoint = PT;
 +  ptrdiff_t opoint = PT;
  
    if (SCHARS (string) == 0)
      return;
  /* Subroutine of the insertion functions above.  */
  
  static void
 -insert_from_string_1 (Lisp_Object string, EMACS_INT pos, EMACS_INT pos_byte,
 -                    EMACS_INT nchars, EMACS_INT nbytes,
 +insert_from_string_1 (Lisp_Object string, ptrdiff_t pos, ptrdiff_t pos_byte,
 +                    ptrdiff_t nchars, ptrdiff_t nbytes,
                      int inherit, int before_markers)
  {
    struct gcpro gcpro1;
 -  EMACS_INT outgoing_nbytes = nbytes;
 +  ptrdiff_t outgoing_nbytes = nbytes;
    INTERVAL intervals;
  
    /* Make OUTGOING_NBYTES describe the text
     starting at GPT_ADDR.  */
  
  void
 -insert_from_gap (EMACS_INT nchars, EMACS_INT nbytes)
 +insert_from_gap (ptrdiff_t nchars, ptrdiff_t nbytes)
  {
    if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
      nchars = nbytes;
  
  void
  insert_from_buffer (struct buffer *buf,
 -                  EMACS_INT charpos, EMACS_INT nchars, int inherit)
 +                  ptrdiff_t charpos, ptrdiff_t nchars, int inherit)
  {
 -  EMACS_INT opoint = PT;
 +  ptrdiff_t opoint = PT;
  
    insert_from_buffer_1 (buf, charpos, nchars, inherit);
    signal_after_change (opoint, 0, PT - opoint);
  
  static void
  insert_from_buffer_1 (struct buffer *buf,
 -                    EMACS_INT from, EMACS_INT nchars, int inherit)
 +                    ptrdiff_t from, ptrdiff_t nchars, int inherit)
  {
 -  EMACS_INT chunk, chunk_expanded;
 -  EMACS_INT from_byte = buf_charpos_to_bytepos (buf, from);
 -  EMACS_INT to_byte = buf_charpos_to_bytepos (buf, from + nchars);
 -  EMACS_INT incoming_nbytes = to_byte - from_byte;
 -  EMACS_INT outgoing_nbytes = incoming_nbytes;
 +  ptrdiff_t chunk, chunk_expanded;
 +  ptrdiff_t from_byte = buf_charpos_to_bytepos (buf, from);
 +  ptrdiff_t to_byte = buf_charpos_to_bytepos (buf, from + nchars);
 +  ptrdiff_t incoming_nbytes = to_byte - from_byte;
 +  ptrdiff_t outgoing_nbytes = incoming_nbytes;
    INTERVAL intervals;
  
    /* Make OUTGOING_NBYTES describe the text
      outgoing_nbytes = nchars;
    else if (NILP (BVAR (buf, enable_multibyte_characters)))
      {
 -      EMACS_INT outgoing_before_gap = 0;
 -      EMACS_INT outgoing_after_gap = 0;
 +      ptrdiff_t outgoing_before_gap = 0;
 +      ptrdiff_t outgoing_after_gap = 0;
  
        if (from < BUF_GPT (buf))
        {
     PREV_TEXT nil means the new text was just inserted.  */
  
  static void
 -adjust_after_replace (EMACS_INT from, EMACS_INT from_byte,
 -                    Lisp_Object prev_text, EMACS_INT len, EMACS_INT len_byte)
 +adjust_after_replace (ptrdiff_t from, ptrdiff_t from_byte,
 +                    Lisp_Object prev_text, ptrdiff_t len, ptrdiff_t len_byte)
  {
 -  EMACS_INT nchars_del = 0, nbytes_del = 0;
 +  ptrdiff_t nchars_del = 0, nbytes_del = 0;
  
  #ifdef BYTE_COMBINING_DEBUG
    if (count_combining_before (GPT_ADDR, len_byte, from, from_byte)
     - FROM) may be incorrect, the correct length is NEWLEN.  */
  
  void
 -adjust_after_insert (EMACS_INT from, EMACS_INT from_byte,
 -                   EMACS_INT to, EMACS_INT to_byte, EMACS_INT newlen)
 +adjust_after_insert (ptrdiff_t from, ptrdiff_t from_byte,
 +                   ptrdiff_t to, ptrdiff_t to_byte, ptrdiff_t newlen)
  {
 -  EMACS_INT len = to - from, len_byte = to_byte - from_byte;
 +  ptrdiff_t len = to - from, len_byte = to_byte - from_byte;
  
    if (GPT != to)
      move_gap_both (to, to_byte);
     But if MARKERS is 0, don't relocate markers.  */
  
  void
 -replace_range (EMACS_INT from, EMACS_INT to, Lisp_Object new,
 +replace_range (ptrdiff_t from, ptrdiff_t to, Lisp_Object new,
               int prepare, int inherit, int markers)
  {
 -  EMACS_INT inschars = SCHARS (new);
 -  EMACS_INT insbytes = SBYTES (new);
 -  EMACS_INT from_byte, to_byte;
 -  EMACS_INT nbytes_del, nchars_del;
 +  ptrdiff_t inschars = SCHARS (new);
 +  ptrdiff_t insbytes = SBYTES (new);
 +  ptrdiff_t from_byte, to_byte;
 +  ptrdiff_t nbytes_del, nchars_del;
    struct gcpro gcpro1;
    INTERVAL intervals;
 -  EMACS_INT outgoing_insbytes = insbytes;
 +  ptrdiff_t outgoing_insbytes = insbytes;
    Lisp_Object deletion;
  
    CHECK_MARKERS ();
  
    if (prepare)
      {
 -      EMACS_INT range_length = to - from;
 +      ptrdiff_t range_length = to - from;
        prepare_to_modify_buffer (from, to, &from);
        to = from + range_length;
      }
     prepare_to_modify_buffer and never call signal_after_change.  */
  
  void
 -replace_range_2 (EMACS_INT from, EMACS_INT from_byte,
 -               EMACS_INT to, EMACS_INT to_byte,
 -               const char *ins, EMACS_INT inschars, EMACS_INT insbytes,
 +replace_range_2 (ptrdiff_t from, ptrdiff_t from_byte,
 +               ptrdiff_t to, ptrdiff_t to_byte,
 +               const char *ins, ptrdiff_t inschars, ptrdiff_t insbytes,
                 int markers)
  {
 -  EMACS_INT nbytes_del, nchars_del;
 +  ptrdiff_t nbytes_del, nchars_del;
  
    CHECK_MARKERS ();
  
     If TO comes before FROM, we delete nothing.  */
  
  void
 -del_range (EMACS_INT from, EMACS_INT to)
 +del_range (ptrdiff_t from, ptrdiff_t to)
  {
    del_range_1 (from, to, 1, 0);
  }
     RET_STRING says to return the deleted text. */
  
  Lisp_Object
 -del_range_1 (EMACS_INT from, EMACS_INT to, int prepare, int ret_string)
 +del_range_1 (ptrdiff_t from, ptrdiff_t to, int prepare, int ret_string)
  {
 -  EMACS_INT from_byte, to_byte;
 +  ptrdiff_t from_byte, to_byte;
    Lisp_Object deletion;
    struct gcpro gcpro1;
  
  
    if (prepare)
      {
 -      EMACS_INT range_length = to - from;
 +      ptrdiff_t range_length = to - from;
        prepare_to_modify_buffer (from, to, &from);
        to = min (ZV, from + range_length);
      }
  /* Like del_range_1 but args are byte positions, not char positions.  */
  
  void
 -del_range_byte (EMACS_INT from_byte, EMACS_INT to_byte, int prepare)
 +del_range_byte (ptrdiff_t from_byte, ptrdiff_t to_byte, int prepare)
  {
 -  EMACS_INT from, to;
 +  ptrdiff_t from, to;
  
    /* Make args be valid */
    if (from_byte < BEGV_BYTE)
  
    if (prepare)
      {
 -      EMACS_INT old_from = from, old_to = Z - to;
 -      EMACS_INT range_length = to - from;
 +      ptrdiff_t old_from = from, old_to = Z - to;
 +      ptrdiff_t range_length = to - from;
        prepare_to_modify_buffer (from, to, &from);
        to = from + range_length;
  
     and bytepos.  */
  
  void
 -del_range_both (EMACS_INT from, EMACS_INT from_byte,
 -              EMACS_INT to, EMACS_INT to_byte, int prepare)
 +del_range_both (ptrdiff_t from, ptrdiff_t from_byte,
 +              ptrdiff_t to, ptrdiff_t to_byte, int prepare)
  {
    /* Make args be valid */
    if (from_byte < BEGV_BYTE)
  
    if (prepare)
      {
 -      EMACS_INT old_from = from, old_to = Z - to;
 -      EMACS_INT range_length = to - from;
 +      ptrdiff_t old_from = from, old_to = Z - to;
 +      ptrdiff_t range_length = to - from;
        prepare_to_modify_buffer (from, to, &from);
        to = from + range_length;
  
     If RET_STRING is true, the deleted area is returned as a string. */
  
  Lisp_Object
 -del_range_2 (EMACS_INT from, EMACS_INT from_byte,
 -           EMACS_INT to, EMACS_INT to_byte, int ret_string)
 +del_range_2 (ptrdiff_t from, ptrdiff_t from_byte,
 +           ptrdiff_t to, ptrdiff_t to_byte, int ret_string)
  {
 -  register EMACS_INT nbytes_del, nchars_del;
 +  register ptrdiff_t nbytes_del, nchars_del;
    Lisp_Object deletion;
  
    CHECK_MARKERS ();
     Otherwise set CHARS_MODIFF to the new value of MODIFF.  */
  
  void
 -modify_region (struct buffer *buffer, EMACS_INT start, EMACS_INT end,
 +modify_region (struct buffer *buffer, ptrdiff_t start, ptrdiff_t end,
               int preserve_chars_modiff)
  {
    struct buffer *old_buffer = current_buffer;
     by holding its value temporarily in a marker.  */
  
  void
 -prepare_to_modify_buffer (EMACS_INT start, EMACS_INT end,
 -                        EMACS_INT *preserve_ptr)
 +prepare_to_modify_buffer (ptrdiff_t start, ptrdiff_t end,
 +                        ptrdiff_t *preserve_ptr)
  {
    struct buffer *base_buffer;
  
          : (!NILP (Vselect_active_regions)
             && !NILP (Vtransient_mark_mode))))
      {
 -      EMACS_INT b = XMARKER (BVAR (current_buffer, mark))->charpos;
 -      EMACS_INT e = PT;
 +      ptrdiff_t b = XMARKER (BVAR (current_buffer, mark))->charpos;
 +      ptrdiff_t e = PT;
        if (b < e)
        Vsaved_region_selection = make_buffer_string (b, e, 0);
        else if (b > e)
@@@ -1958,14 -1954,14 +1954,14 @@@ reset_var_on_error (Lisp_Object val
     by holding its value temporarily in a marker.  */
  
  static void
 -signal_before_change (EMACS_INT start_int, EMACS_INT end_int,
 -                    EMACS_INT *preserve_ptr)
 +signal_before_change (ptrdiff_t start_int, ptrdiff_t end_int,
 +                    ptrdiff_t *preserve_ptr)
  {
    Lisp_Object start, end;
    Lisp_Object start_marker, end_marker;
    Lisp_Object preserve_marker;
    struct gcpro gcpro1, gcpro2, gcpro3;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    if (inhibit_modification_hooks)
      return;
     after the change.  */
  
  void
 -signal_after_change (EMACS_INT charpos, EMACS_INT lendel, EMACS_INT lenins)
 +signal_after_change (ptrdiff_t charpos, ptrdiff_t lendel, ptrdiff_t lenins)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    if (inhibit_modification_hooks)
      return;
  
@@@ -2119,9 -2115,9 +2115,9 @@@ DEFUN ("combine-after-change-execute", 
         doc: /* This function is for use internally in `combine-after-change-calls'.  */)
    (void)
  {
 -  int count = SPECPDL_INDEX ();
 -  EMACS_INT beg, end, change;
 -  EMACS_INT begpos, endpos;
 +  ptrdiff_t count = SPECPDL_INDEX ();
 +  ptrdiff_t beg, end, change;
 +  ptrdiff_t begpos, endpos;
    Lisp_Object tail;
  
    if (NILP (combine_after_change_list))
         tail = XCDR (tail))
      {
        Lisp_Object elt;
 -      EMACS_INT thisbeg, thisend, thischange;
 +      ptrdiff_t thisbeg, thisend, thischange;
  
        /* Extract the info from the next element.  */
        elt = XCAR (tail);
diff --combined src/intervals.c
@@@ -223,7 -223,7 +223,7 @@@ traverse_intervals_noorder (INTERVAL tr
     Pass FUNCTION two args: an interval, and ARG.  */
  
  void
 -traverse_intervals (INTERVAL tree, EMACS_INT position,
 +traverse_intervals (INTERVAL tree, ptrdiff_t position,
                    void (*function) (INTERVAL, Lisp_Object), Lisp_Object arg)
  {
    while (!NULL_INTERVAL_P (tree))
@@@ -313,7 -313,7 +313,7 @@@ rotate_right (INTERVAL interval
  {
    INTERVAL i;
    INTERVAL B = interval->left;
 -  EMACS_INT old_total = interval->total_length;
 +  ptrdiff_t old_total = interval->total_length;
  
    /* Deal with any Parent of A;  make it point to B.  */
    if (! ROOT_INTERVAL_P (interval))
@@@ -360,7 -360,7 +360,7 @@@ rotate_left (INTERVAL interval
  {
    INTERVAL i;
    INTERVAL B = interval->right;
 -  EMACS_INT old_total = interval->total_length;
 +  ptrdiff_t old_total = interval->total_length;
  
    /* Deal with any parent of A;  make it point to B.  */
    if (! ROOT_INTERVAL_P (interval))
  static INTERVAL
  balance_an_interval (INTERVAL i)
  {
 -  register EMACS_INT old_diff, new_diff;
 +  register ptrdiff_t old_diff, new_diff;
  
    while (1)
      {
@@@ -499,11 -499,11 +499,11 @@@ balance_intervals (INTERVAL tree
     it is still a root after this operation.  */
  
  INTERVAL
 -split_interval_right (INTERVAL interval, EMACS_INT offset)
 +split_interval_right (INTERVAL interval, ptrdiff_t offset)
  {
    INTERVAL new = make_interval ();
 -  EMACS_INT position = interval->position;
 -  EMACS_INT new_length = LENGTH (interval) - offset;
 +  ptrdiff_t position = interval->position;
 +  ptrdiff_t new_length = LENGTH (interval) - offset;
  
    new->position = position + offset;
    SET_INTERVAL_PARENT (new, interval);
     it is still a root after this operation.  */
  
  INTERVAL
 -split_interval_left (INTERVAL interval, EMACS_INT offset)
 +split_interval_left (INTERVAL interval, ptrdiff_t offset)
  {
    INTERVAL new = make_interval ();
 -  EMACS_INT new_length = offset;
 +  ptrdiff_t new_length = offset;
  
    new->position = interval->position;
    interval->position = interval->position + offset;
@@@ -610,11 -610,11 +610,11 @@@ interval_start_pos (INTERVAL source
     will update this cache based on the result of find_interval.  */
  
  INTERVAL
 -find_interval (register INTERVAL tree, register EMACS_INT position)
 +find_interval (register INTERVAL tree, register ptrdiff_t position)
  {
    /* The distance from the left edge of the subtree at TREE
                      to POSITION.  */
 -  register EMACS_INT relative_position;
 +  register ptrdiff_t relative_position;
  
    if (NULL_INTERVAL_P (tree))
      return NULL_INTERVAL;
@@@ -667,7 -667,7 +667,7 @@@ INTERVA
  next_interval (register INTERVAL interval)
  {
    register INTERVAL i = interval;
 -  register EMACS_INT next_position;
 +  register ptrdiff_t next_position;
  
    if (NULL_INTERVAL_P (i))
      return NULL_INTERVAL;
@@@ -742,7 -742,7 +742,7 @@@ previous_interval (register INTERVAL in
     To speed up the process, we assume that the ->position of
     I and all its parents is already uptodate.  */
  INTERVAL
 -update_interval (register INTERVAL i, EMACS_INT pos)
 +update_interval (register INTERVAL i, ptrdiff_t pos)
  {
    if (NULL_INTERVAL_P (i))
      return NULL_INTERVAL;
              i = i->right;             /* Move to the right child */
            }
          else if (NULL_PARENT (i))
 -          error ("Point %"pI"d after end of properties", pos);
 +          error ("Point %"pD"d after end of properties", pos);
          else
              i = INTERVAL_PARENT (i);
          continue;
     to the root.  */
  
  static INTERVAL
 -adjust_intervals_for_insertion (INTERVAL tree, EMACS_INT position,
 -                              EMACS_INT length)
 +adjust_intervals_for_insertion (INTERVAL tree, ptrdiff_t position,
 +                              ptrdiff_t length)
  {
 -  register EMACS_INT relative_position;
 +  register ptrdiff_t relative_position;
    register INTERVAL this;
  
    if (TOTAL_LENGTH (tree) == 0)       /* Paranoia */
  
  static INTERVAL
  adjust_intervals_for_insertion (INTERVAL tree,
 -                              EMACS_INT position, EMACS_INT length)
 +                              ptrdiff_t position, ptrdiff_t length)
  {
    register INTERVAL i;
    register INTERVAL temp;
    int eobp = 0;
    Lisp_Object parent;
 -  EMACS_INT offset;
 +  ptrdiff_t offset;
  
    if (TOTAL_LENGTH (tree) == 0)       /* Paranoia */
      abort ();
          Lisp_Object pleft, pright;
          struct interval newi;
  
+         RESET_INTERVAL (&newi);
          pleft = NULL_INTERVAL_P (prev) ? Qnil : prev->plist;
          pright = NULL_INTERVAL_P (i) ? Qnil : i->plist;
          newi.plist = merge_properties_sticky (pleft, pright);
@@@ -1225,7 -1226,7 +1226,7 @@@ static INTERVA
  delete_node (register INTERVAL i)
  {
    register INTERVAL migrate, this;
 -  register EMACS_INT migrate_amt;
 +  register ptrdiff_t migrate_amt;
  
    if (NULL_INTERVAL_P (i->left))
      return i->right;
@@@ -1258,7 -1259,7 +1259,7 @@@ static voi
  delete_interval (register INTERVAL i)
  {
    register INTERVAL parent;
 -  EMACS_INT amt = LENGTH (i);
 +  ptrdiff_t amt = LENGTH (i);
  
    if (amt > 0)                        /* Only used on zero-length intervals now.  */
      abort ();
     Do this by recursing down TREE to the interval in question, and
     deleting the appropriate amount of text.  */
  
 -static EMACS_INT
 -interval_deletion_adjustment (register INTERVAL tree, register EMACS_INT from,
 -                            register EMACS_INT amount)
 +static ptrdiff_t
 +interval_deletion_adjustment (register INTERVAL tree, register ptrdiff_t from,
 +                            register ptrdiff_t amount)
  {
 -  register EMACS_INT relative_position = from;
 +  register ptrdiff_t relative_position = from;
  
    if (NULL_INTERVAL_P (tree))
      return 0;
    /* Left branch.  */
    if (relative_position < LEFT_TOTAL_LENGTH (tree))
      {
 -      EMACS_INT subtract = interval_deletion_adjustment (tree->left,
 +      ptrdiff_t subtract = interval_deletion_adjustment (tree->left,
                                                         relative_position,
                                                         amount);
        tree->total_length -= subtract;
    else if (relative_position >= (TOTAL_LENGTH (tree)
                                 - RIGHT_TOTAL_LENGTH (tree)))
      {
 -      EMACS_INT subtract;
 +      ptrdiff_t subtract;
  
        relative_position -= (tree->total_length
                            - RIGHT_TOTAL_LENGTH (tree));
    else
      {
        /* How much can we delete from this interval?  */
 -      EMACS_INT my_amount = ((tree->total_length
 +      ptrdiff_t my_amount = ((tree->total_length
                               - RIGHT_TOTAL_LENGTH (tree))
                              - relative_position);
  
  
  static void
  adjust_intervals_for_deletion (struct buffer *buffer,
 -                             EMACS_INT start, EMACS_INT length)
 +                             ptrdiff_t start, ptrdiff_t length)
  {
 -  register EMACS_INT left_to_delete = length;
 +  register ptrdiff_t left_to_delete = length;
    register INTERVAL tree = BUF_INTERVALS (buffer);
    Lisp_Object parent;
 -  EMACS_INT offset;
 +  ptrdiff_t offset;
  
    GET_INTERVAL_OBJECT (parent, tree);
    offset = (BUFFERP (parent) ? BUF_BEG (XBUFFER (parent)) : 0);
     adjust_intervals_for_deletion) from a non-static inline function.  */
  
  void
 -offset_intervals (struct buffer *buffer, EMACS_INT start, EMACS_INT length)
 +offset_intervals (struct buffer *buffer, ptrdiff_t start, ptrdiff_t length)
  {
    if (NULL_INTERVAL_P (BUF_INTERVALS (buffer)) || length == 0)
      return;
      adjust_intervals_for_insertion (BUF_INTERVALS (buffer), start, length);
    else
      {
 -      IF_LINT (if (length < - TYPE_MAXIMUM (EMACS_INT)) abort ();)
 +      IF_LINT (if (length < - TYPE_MAXIMUM (ptrdiff_t)) abort ();)
        adjust_intervals_for_deletion (buffer, start, -length);
      }
  }
  static INTERVAL
  merge_interval_right (register INTERVAL i)
  {
 -  register EMACS_INT absorb = LENGTH (i);
 +  register ptrdiff_t absorb = LENGTH (i);
    register INTERVAL successor;
  
    /* Zero out this interval.  */
  INTERVAL
  merge_interval_left (register INTERVAL i)
  {
 -  register EMACS_INT absorb = LENGTH (i);
 +  register ptrdiff_t absorb = LENGTH (i);
    register INTERVAL predecessor;
  
    /* Zero out this interval.  */
@@@ -1602,7 -1603,7 +1603,7 @@@ reproduce_tree_obj (INTERVAL source, Li
     interval.  */
  
  static INTERVAL
 -make_new_interval (INTERVAL intervals, EMACS_INT start, EMACS_INT length)
 +make_new_interval (INTERVAL intervals, ptrdiff_t start, ptrdiff_t length)
  {
    INTERVAL slot;
  
     text...  */
  
  void
 -graft_intervals_into_buffer (INTERVAL source, EMACS_INT position,
 -                           EMACS_INT length, struct buffer *buffer,
 +graft_intervals_into_buffer (INTERVAL source, ptrdiff_t position,
 +                           ptrdiff_t length, struct buffer *buffer,
                             int inherit)
  {
    register INTERVAL under, over, this;
    register INTERVAL tree;
 -  EMACS_INT over_used;
 +  ptrdiff_t over_used;
  
    tree = BUF_INTERVALS (buffer);
  
@@@ -1862,7 -1863,7 +1863,7 @@@ lookup_char_property (Lisp_Object plist
  
  void
  temp_set_point_both (struct buffer *buffer,
 -                   EMACS_INT charpos, EMACS_INT bytepos)
 +                   ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    /* In a single-byte buffer, the two positions must be equal.  */
    if (BUF_ZV (buffer) == BUF_ZV_BYTE (buffer)
  /* Set point "temporarily", without checking any text properties.  */
  
  void
 -temp_set_point (struct buffer *buffer, EMACS_INT charpos)
 +temp_set_point (struct buffer *buffer, ptrdiff_t charpos)
  {
    temp_set_point_both (buffer, charpos,
                       buf_charpos_to_bytepos (buffer, charpos));
     before an intangible character, move to an ok place.  */
  
  void
 -set_point (EMACS_INT charpos)
 +set_point (ptrdiff_t charpos)
  {
    set_point_both (charpos, buf_charpos_to_bytepos (current_buffer, charpos));
  }
     Note that `stickiness' is determined by overlay marker insertion types,
     if the invisible property comes from an overlay.  */
  
 -static EMACS_INT
 -adjust_for_invis_intang (EMACS_INT pos, EMACS_INT test_offs, EMACS_INT adj,
 +static ptrdiff_t
 +adjust_for_invis_intang (ptrdiff_t pos, ptrdiff_t test_offs, ptrdiff_t adj,
                         int test_intang)
  {
    Lisp_Object invis_propval, invis_overlay;
     before an intangible character, move to an ok place.  */
  
  void
 -set_point_both (EMACS_INT charpos, EMACS_INT bytepos)
 +set_point_both (ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    register INTERVAL to, from, toprev, fromprev;
 -  EMACS_INT buffer_point;
 -  EMACS_INT old_position = PT;
 +  ptrdiff_t buffer_point;
 +  ptrdiff_t old_position = PT;
    /* This ensures that we move forward past intangible text when the
       initial position is the same as the destination, in the rare
       instances where this is important, e.g. in line-move-finish
       (simple.el).  */
    int backwards = (charpos < old_position ? 1 : 0);
    int have_overlays;
 -  EMACS_INT original_position;
 +  ptrdiff_t original_position;
  
    BVAR (current_buffer, point_before_scroll) = Qnil;
  
     segment that reaches all the way to point.  */
  
  void
 -move_if_not_intangible (EMACS_INT position)
 +move_if_not_intangible (ptrdiff_t position)
  {
    Lisp_Object pos;
    Lisp_Object intangible_propval;
     nil means the current buffer. */
  
  int
 -get_property_and_range (EMACS_INT pos, Lisp_Object prop, Lisp_Object *val,
 -                      EMACS_INT *start, EMACS_INT *end, Lisp_Object object)
 +get_property_and_range (ptrdiff_t pos, Lisp_Object prop, Lisp_Object *val,
 +                      ptrdiff_t *start, ptrdiff_t *end, Lisp_Object object)
  {
    INTERVAL i, prev, next;
  
     POSITION must be in the accessible part of BUFFER.  */
  
  Lisp_Object
 -get_local_map (register EMACS_INT position, register struct buffer *buffer,
 +get_local_map (register ptrdiff_t position, register struct buffer *buffer,
               Lisp_Object type)
  {
    Lisp_Object prop, lispy_position, lispy_buffer;
 -  EMACS_INT old_begv, old_zv, old_begv_byte, old_zv_byte;
 +  ptrdiff_t old_begv, old_zv, old_begv_byte, old_zv_byte;
  
    /* Perhaps we should just change `position' to the limit.  */
    if (position > BUF_ZV (buffer) || position < BUF_BEGV (buffer))
     The new interval tree has no parent and has a starting-position of 0.  */
  
  INTERVAL
 -copy_intervals (INTERVAL tree, EMACS_INT start, EMACS_INT length)
 +copy_intervals (INTERVAL tree, ptrdiff_t start, ptrdiff_t length)
  {
    register INTERVAL i, new, t;
 -  register EMACS_INT got, prevlen;
 +  register ptrdiff_t got, prevlen;
  
    if (NULL_INTERVAL_P (tree) || length <= 0)
      return NULL_INTERVAL;
  
  void
  copy_intervals_to_string (Lisp_Object string, struct buffer *buffer,
 -                        EMACS_INT position, EMACS_INT length)
 +                        ptrdiff_t position, ptrdiff_t length)
  {
    INTERVAL interval_copy = copy_intervals (BUF_INTERVALS (buffer),
                                           position, length);
@@@ -2389,8 -2390,8 +2390,8 @@@ in
  compare_string_intervals (Lisp_Object s1, Lisp_Object s2)
  {
    INTERVAL i1, i2;
 -  EMACS_INT pos = 0;
 -  EMACS_INT end = SCHARS (s1);
 +  ptrdiff_t pos = 0;
 +  ptrdiff_t end = SCHARS (s1);
  
    i1 = find_interval (STRING_INTERVALS (s1), 0);
    i2 = find_interval (STRING_INTERVALS (s2), 0);
    while (pos < end)
      {
        /* Determine how far we can go before we reach the end of I1 or I2.  */
 -      EMACS_INT len1 = (i1 != 0 ? INTERVAL_LAST_POS (i1) : end) - pos;
 -      EMACS_INT len2 = (i2 != 0 ? INTERVAL_LAST_POS (i2) : end) - pos;
 -      EMACS_INT distance = min (len1, len2);
 +      ptrdiff_t len1 = (i1 != 0 ? INTERVAL_LAST_POS (i1) : end) - pos;
 +      ptrdiff_t len2 = (i2 != 0 ? INTERVAL_LAST_POS (i2) : end) - pos;
 +      ptrdiff_t distance = min (len1, len2);
  
        /* If we ever find a mismatch between the strings,
         they differ.  */
  
  static void
  set_intervals_multibyte_1 (INTERVAL i, int multi_flag,
 -                         EMACS_INT start, EMACS_INT start_byte,
 -                         EMACS_INT end, EMACS_INT end_byte)
 +                         ptrdiff_t start, ptrdiff_t start_byte,
 +                         ptrdiff_t end, ptrdiff_t end_byte)
  {
    /* Fix the length of this interval.  */
    if (multi_flag)
    /* Recursively fix the length of the subintervals.  */
    if (i->left)
      {
 -      EMACS_INT left_end, left_end_byte;
 +      ptrdiff_t left_end, left_end_byte;
  
        if (multi_flag)
        {
 -        EMACS_INT temp;
 +        ptrdiff_t temp;
          left_end_byte = start_byte + LEFT_TOTAL_LENGTH (i);
          left_end = BYTE_TO_CHAR (left_end_byte);
  
      }
    if (i->right)
      {
 -      EMACS_INT right_start_byte, right_start;
 +      ptrdiff_t right_start_byte, right_start;
  
        if (multi_flag)
        {
 -        EMACS_INT temp;
 +        ptrdiff_t temp;
  
          right_start_byte = end_byte - RIGHT_TOTAL_LENGTH (i);
          right_start = BYTE_TO_CHAR (right_start_byte);
diff --combined src/keyboard.c
@@@ -122,7 -122,7 +122,7 @@@ static Lisp_Object recent_keys
     actually mean something.
     It's easier to staticpro a single Lisp_Object than an array.  */
  Lisp_Object this_command_keys;
 -int this_command_key_count;
 +ptrdiff_t this_command_key_count;
  
  /* 1 after calling Freset_this_command_lengths.
     Usually it is 0.  */
@@@ -135,16 -135,16 +135,16 @@@ static int raw_keybuf_count
  
  #define GROW_RAW_KEYBUF                                                       \
   if (raw_keybuf_count == ASIZE (raw_keybuf))                          \
 -   raw_keybuf = larger_vector (raw_keybuf, raw_keybuf_count * 2, Qnil)  \
 +   raw_keybuf = larger_vector (raw_keybuf, 1, -1)
  
  /* Number of elements of this_command_keys
     that precede this key sequence.  */
 -static int this_single_command_key_start;
 +static ptrdiff_t this_single_command_key_start;
  
  /* Record values of this_command_key_count and echo_length ()
     before this command was read.  */
 -static int before_command_key_count;
 -static int before_command_echo_length;
 +static ptrdiff_t before_command_key_count;
 +static ptrdiff_t before_command_echo_length;
  
  /* For longjmp to where kbd input is being done.  */
  
@@@ -208,20 -208,20 +208,20 @@@ EMACS_INT command_loop_level
  Lisp_Object unread_switch_frame;
  
  /* Last size recorded for a current buffer which is not a minibuffer.  */
 -static EMACS_INT last_non_minibuf_size;
 +static ptrdiff_t last_non_minibuf_size;
  
  /* Total number of times read_char has returned, modulo UINTMAX_MAX + 1.  */
  uintmax_t num_input_events;
  
  /* Value of num_nonmacro_input_events as of last auto save.  */
  
 -static int last_auto_save;
 +static EMACS_INT last_auto_save;
  
  /* This is like Vthis_command, except that commands never set it.  */
  Lisp_Object real_this_command;
  
  /* The value of point when the last command was started.  */
 -static EMACS_INT last_point_position;
 +static ptrdiff_t last_point_position;
  
  /* The buffer that was current when the last command was started.  */
  static Lisp_Object last_point_position_buffer;
@@@ -377,7 -377,7 +377,7 @@@ EMACS_TIME timer_check (void)
  
  static void record_menu_key (Lisp_Object c);
  static void echo_now (void);
 -static int echo_length (void);
 +static ptrdiff_t echo_length (void);
  
  static Lisp_Object Qpolling_period;
  
@@@ -448,9 -448,9 +448,9 @@@ static Lisp_Object make_lispy_movement 
                                          Lisp_Object, Lisp_Object,
                                        Time);
  #endif
 -static Lisp_Object modify_event_symbol (EMACS_INT, unsigned, Lisp_Object,
 +static Lisp_Object modify_event_symbol (ptrdiff_t, int, Lisp_Object,
                                          Lisp_Object, const char *const *,
 -                                        Lisp_Object *, EMACS_INT);
 +                                        Lisp_Object *, ptrdiff_t);
  static Lisp_Object make_lispy_switch_frame (Lisp_Object);
  static int help_char_p (Lisp_Object);
  static void save_getcjmp (jmp_buf);
@@@ -615,7 -615,7 +615,7 @@@ echo_now (void
  {
    if (!current_kboard->immediate_echo)
      {
 -      int i;
 +      ptrdiff_t i;
        current_kboard->immediate_echo = 1;
  
        for (i = 0; i < this_command_key_count; i++)
@@@ -673,7 -673,7 +673,7 @@@ cancel_echoing (void
  
  /* Return the length of the current echo string.  */
  
 -static int
 +static ptrdiff_t
  echo_length (void)
  {
    return (STRINGP (KVAR (current_kboard, echo_string))
     switches frames while entering a key sequence.  */
  
  static void
 -echo_truncate (EMACS_INT nchars)
 +echo_truncate (ptrdiff_t nchars)
  {
    if (STRINGP (KVAR (current_kboard, echo_string)))
      KVAR (current_kboard, echo_string)
@@@ -715,7 -715,9 +715,7 @@@ add_command_key (Lisp_Object key
  #endif
  
    if (this_command_key_count >= ASIZE (this_command_keys))
 -    this_command_keys = larger_vector (this_command_keys,
 -                                     2 * ASIZE (this_command_keys),
 -                                     Qnil);
 +    this_command_keys = larger_vector (this_command_keys, 1, -1);
  
    ASET (this_command_keys, this_command_key_count, key);
    ++this_command_key_count;
  Lisp_Object
  recursive_edit_1 (void)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object val;
  
    if (command_loop_level > 0)
@@@ -793,7 -795,7 +793,7 @@@ Alternatively, `(throw 'exit t)' makes 
  This function is called by the editor initialization to begin editing.  */)
    (void)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object buffer;
  
    /* If we enter while input is blocked, don't lock up here.
@@@ -1198,6 -1200,12 +1198,12 @@@ This also exits all active minibuffers
    Fthrow (Qtop_level, Qnil);
  }
  
+ static void user_error (const char*) NO_RETURN;
+ static void user_error (const char *msg)
+ {
+   xsignal1 (Quser_error, build_string (msg));
+ }
  static Lisp_Object Fexit_recursive_edit (void) NO_RETURN;
  DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
         doc: /* Exit from the innermost recursive edit or minibuffer.  */)
    if (command_loop_level > 0 || minibuf_level > 0)
      Fthrow (Qexit, Qnil);
  
-   error ("No recursive edit is in progress");
+   user_error ("No recursive edit is in progress");
  }
  
  static Lisp_Object Fabort_recursive_edit (void) NO_RETURN;
@@@ -1217,7 -1225,7 +1223,7 @@@ DEFUN ("abort-recursive-edit", Fabort_r
    if (command_loop_level > 0 || minibuf_level > 0)
      Fthrow (Qexit, Qt);
  
-   error ("No recursive edit is in progress");
+   user_error ("No recursive edit is in progress");
  }
  \f
  #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
@@@ -1254,7 -1262,7 +1260,7 @@@ Normally, mouse motion is ignored
  usage: (track-mouse BODY...)  */)
    (Lisp_Object args)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object val;
  
    record_unwind_protect (tracking_off, do_mouse_tracking);
@@@ -1305,7 -1313,7 +1311,7 @@@ some_mouse_moved (void
  static int read_key_sequence (Lisp_Object *, int, Lisp_Object,
                                int, int, int);
  void safe_run_hooks (Lisp_Object);
 -static void adjust_point_for_property (EMACS_INT, int);
 +static void adjust_point_for_property (ptrdiff_t, int);
  
  /* Cancel hourglass from protect_unwind.
     ARG is not used.  */
@@@ -1329,7 -1337,7 +1335,7 @@@ command_loop_1 (void
    Lisp_Object cmd;
    Lisp_Object keybuf[30];
    int i;
 -  int prev_modiff = 0;
 +  EMACS_INT prev_modiff = 0;
    struct buffer *prev_buffer = NULL;
  #if 0 /* This shouldn't be necessary anymore.  --lorentey  */
    int was_locked = single_kboard;
        {
          /* Bind inhibit-quit to t so that C-g gets read in
             rather than quitting back to the minibuffer.  */
 -        int count = SPECPDL_INDEX ();
 +        ptrdiff_t count = SPECPDL_INDEX ();
          specbind (Qinhibit_quit, Qt);
  
          sit_for (Vminibuffer_message_timeout, 0, 2);
          /* Here for a command that isn't executed directly.  */
  
  #ifdef HAVE_WINDOW_SYSTEM
 -            int scount = SPECPDL_INDEX ();
 +            ptrdiff_t scount = SPECPDL_INDEX ();
  
              if (display_hourglass_p
                  && NILP (Vexecuting_kbd_macro))
                  && NILP (Fmemq (Vthis_command,
                                  Vselection_inhibit_update_commands)))
                {
 -                EMACS_INT beg =
 +                ptrdiff_t beg =
                    XINT (Fmarker_position (BVAR (current_buffer, mark)));
 -                EMACS_INT end = PT;
 +                ptrdiff_t end = PT;
                  if (beg < end)
                    call2 (Qx_set_selection, QPRIMARY,
                           make_buffer_string (beg, end, 0));
     LAST_PT is the last position of point.  */
  
  static void
 -adjust_point_for_property (EMACS_INT last_pt, int modified)
 +adjust_point_for_property (ptrdiff_t last_pt, int modified)
  {
 -  EMACS_INT beg, end;
 +  ptrdiff_t beg, end;
    Lisp_Object val, overlay, tmp;
    /* When called after buffer modification, we should temporarily
       suppress the point adjustment for automatic composition so that a
       user can keep inserting another character at point or keep
       deleting characters around point.  */
    int check_composition = ! modified, check_display = 1, check_invisible = 1;
 -  EMACS_INT orig_pt = PT;
 +  ptrdiff_t orig_pt = PT;
  
    /* FIXME: cycling is probably not necessary because these properties
       can't be usefully combined anyway.  */
@@@ -1935,7 -1943,7 +1941,7 @@@ safe_run_hooks (Lisp_Object hook
    /* FIXME: our `internal_condition_case' does not provide any way to pass data
       to its body or to its handlers other than via globals such as
       dynamically-bound variables ;-)  */
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    specbind (Qinhibit_quit, hook);
  
    run_hook_with_args (1, &hook, safe_run_hook_funcall);
@@@ -2273,7 -2281,7 +2279,7 @@@ read_char (int commandflag, ptrdiff_t n
           int *used_mouse_menu, struct timeval *end_time)
  {
    volatile Lisp_Object c;
 -  int jmpcount;
 +  ptrdiff_t jmpcount;
    jmp_buf local_getcjmp;
    jmp_buf save_jump;
    volatile int key_already_recorded = 0;
    if (INTERACTIVE && NILP (c))
      {
        int delay_level;
 -      EMACS_INT buffer_size;
 +      ptrdiff_t buffer_size;
  
        /* Slow down auto saves logarithmically in size of current buffer,
         and garbage collect while we're at it.  */
          && XINT (Vauto_save_timeout) > 0)
        {
          Lisp_Object tem0;
 -        int timeout = delay_level * XFASTINT (Vauto_save_timeout) / 4;
 -
 +        EMACS_INT timeout = (delay_level
 +                             * min (XFASTINT (Vauto_save_timeout) / 4,
 +                                    MOST_POSITIVE_FIXNUM / delay_level));
          save_getcjmp (save_jump);
          restore_getcjmp (local_getcjmp);
          tem0 = sit_for (make_number (timeout), 1, 1);
        struct buffer *prev_buffer = current_buffer;
  #if 0 /* This shouldn't be necessary anymore. --lorentey  */
        int was_locked = single_kboard;
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        record_single_kboard_state ();
  #endif
  
       own stuff with the echo area.  */
    if (!CONSP (c)
        || (!(EQ (Qhelp_echo, XCAR (c)))
-         && !(EQ (Qswitch_frame, XCAR (c)))))
+         && !(EQ (Qswitch_frame, XCAR (c)))
+         /* Don't wipe echo area for select window events: These might
+            get delayed via `mouse-autoselect-window' (Bug#11304).  */
+         && !(EQ (Qselect_window, XCAR (c)))))
      {
        if (!NILP (echo_area_buffer[0]))
-       safe_run_hooks (Qecho_area_clear_hook);
-       clear_message (1, 0);
+       {
+         safe_run_hooks (Qecho_area_clear_hook);
+         clear_message (1, 0);
+       }
      }
  
   reread_for_input_method:
        && ' ' <= XINT (c) && XINT (c) < 256 && XINT (c) != 127)
      {
        Lisp_Object keys;
 -      int key_count, key_count_reset;
 +      ptrdiff_t key_count;
 +      int key_count_reset;
        struct gcpro gcpro1;
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
  
        /* Save the echo status.  */
        int saved_immediate_echo = current_kboard->immediate_echo;
    /* Process the help character specially if enabled */
    if (!NILP (Vhelp_form) && help_char_p (c))
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
  
        help_form_saved_window_configs
        = Fcons (Fcurrent_window_configuration (Qnil),
@@@ -3301,7 -3312,7 +3312,7 @@@ record_char (Lisp_Object c
  
    if (!recorded)
      {
 -      total_keys++;
 +      total_keys += total_keys < NUM_RECENT_KEYS;
        ASET (recent_keys, recent_keys_index, c);
        if (++recent_keys_index >= NUM_RECENT_KEYS)
        recent_keys_index = 0;
@@@ -3670,7 -3681,7 +3681,7 @@@ kbd_buffer_unget_event (register struc
  
  void
  gen_help_event (Lisp_Object help, Lisp_Object frame, Lisp_Object window,
 -              Lisp_Object object, EMACS_INT pos)
 +              Lisp_Object object, ptrdiff_t pos)
  {
    struct input_event event;
  
@@@ -3775,7 -3786,6 +3786,6 @@@ kbd_buffer_get_event (KBOARD **kbp
                        int *used_mouse_menu,
                        struct timeval *end_time)
  {
-   register int c;
    Lisp_Object obj;
  
  #ifdef subprocesses
      }
  #endif        /* subprocesses */
  
+ #ifndef HAVE_DBUS  /* We want to read D-Bus events in batch mode.  */
    if (noninteractive
        /* In case we are running as a daemon, only do this before
         detaching from the terminal.  */
        || (IS_DAEMON && daemon_pipe[1] >= 0))
      {
-       c = getchar ();
+       int c = getchar ();
        XSETINT (obj, c);
        *kbp = current_kboard;
        return obj;
      }
+ #endif        /* ! HAVE_DBUS  */
  
    /* Wait until there is input available.  */
    for (;;)
@@@ -4453,7 -4465,7 +4465,7 @@@ timer_check_2 (void
        {
          if (NILP (vector[0]))
            {
 -            int count = SPECPDL_INDEX ();
 +            ptrdiff_t count = SPECPDL_INDEX ();
              Lisp_Object old_deactivate_mark = Vdeactivate_mark;
  
              /* Mark the timer as triggered to prevent problems if the lisp
@@@ -5164,7 -5176,7 +5176,7 @@@ make_lispy_position (struct frame *f, L
        /* It's a click in window WINDOW at frame coordinates (X,Y)  */
        struct window *w = XWINDOW (window);
        Lisp_Object string_info = Qnil;
 -      EMACS_INT textpos = -1;
 +      ptrdiff_t textpos = -1;
        int col = -1, row = -1;
        int dx  = -1, dy  = -1;
        int width = -1, height = -1;
        else if (part == ON_MODE_LINE || part == ON_HEADER_LINE)
        {
          Lisp_Object string;
 -        EMACS_INT charpos;
 +        ptrdiff_t charpos;
  
          posn = (part == ON_MODE_LINE) ? Qmode_line : Qheader_line;
          /* Note that mode_line_string takes COL, ROW as pixels and
        else if (part == ON_LEFT_MARGIN || part == ON_RIGHT_MARGIN)
        {
          Lisp_Object string;
 -        EMACS_INT charpos;
 +        ptrdiff_t charpos;
  
          posn = (part == ON_LEFT_MARGIN) ? Qleft_margin : Qright_margin;
          col = wx;
@@@ -5439,7 -5451,7 +5451,7 @@@ make_lispy_event (struct input_event *e
                                      Qfunction_key,
                                      KVAR (current_kboard, Vsystem_key_alist),
                                      0, &KVAR (current_kboard, system_key_syms),
 -                                    TYPE_MAXIMUM (EMACS_INT));
 +                                    PTRDIFF_MAX);
        }
  
        return modify_event_symbol (event->code - FUNCTION_KEY_OFFSET,
  
        if (button >= ASIZE (button_down_location))
          {
 +          ptrdiff_t incr = button - ASIZE (button_down_location) + 1;
            button_down_location = larger_vector (button_down_location,
 -                                                button + 1, Qnil);
 -          mouse_syms = larger_vector (mouse_syms, button + 1, Qnil);
 +                                                incr, -1);
 +          mouse_syms = larger_vector (mouse_syms, incr, -1);
          }
  
        start_pos_ptr = &AREF (button_down_location, button);
        event->modifiers &= ~up_modifier;
  
        if (event->code >= ASIZE (mouse_syms))
 -          mouse_syms = larger_vector (mouse_syms, event->code + 1, Qnil);
 +          mouse_syms = larger_vector (mouse_syms,
 +                                    event->code - ASIZE (mouse_syms) + 1,
 +                                    -1);
  
        /* Get the symbol we should use for the mouse click.  */
        head = modify_event_symbol (event->code,
  
        if (button >= ASIZE (button_down_location))
          {
 +          ptrdiff_t incr = button - ASIZE (button_down_location) + 1;
            button_down_location = larger_vector (button_down_location,
 -                                                button + 1, Qnil);
 -          mouse_syms = larger_vector (mouse_syms, button + 1, Qnil);
 +                                                incr, -1);
 +          mouse_syms = larger_vector (mouse_syms, incr, -1);
          }
  
        start_pos_ptr = &AREF (button_down_location, button);
@@@ -6084,10 -6092,10 +6096,10 @@@ make_lispy_switch_frame (Lisp_Object fr
     This doesn't use any caches.  */
  
  static int
 -parse_modifiers_uncached (Lisp_Object symbol, EMACS_INT *modifier_end)
 +parse_modifiers_uncached (Lisp_Object symbol, ptrdiff_t *modifier_end)
  {
    Lisp_Object name;
 -  EMACS_INT i;
 +  ptrdiff_t i;
    int modifiers;
  
    CHECK_SYMBOL (symbol);
    modifiers = 0;
    name = SYMBOL_NAME (symbol);
  
 -  for (i = 0; i+2 <= SBYTES (name); )
 +  for (i = 0; i < SBYTES (name) - 1; )
      {
 -      EMACS_INT this_mod_end = 0;
 +      ptrdiff_t this_mod_end = 0;
        int this_mod = 0;
  
        /* See if the name continues with a modifier word.
@@@ -6294,7 -6302,7 +6306,7 @@@ parse_modifiers (Lisp_Object symbol
      return elements;
    else
      {
 -      EMACS_INT end;
 +      ptrdiff_t end;
        int modifiers = parse_modifiers_uncached (symbol, &end);
        Lisp_Object unmodified;
        Lisp_Object mask;
@@@ -6460,9 -6468,9 +6472,9 @@@ reorder_modifiers (Lisp_Object symbol
     in the symbol's name.  */
  
  static Lisp_Object
 -modify_event_symbol (EMACS_INT symbol_num, unsigned int modifiers, Lisp_Object symbol_kind,
 +modify_event_symbol (ptrdiff_t symbol_num, int modifiers, Lisp_Object symbol_kind,
                     Lisp_Object name_alist_or_stem, const char *const *name_table,
 -                   Lisp_Object *symbol_table, EMACS_INT table_size)
 +                   Lisp_Object *symbol_table, ptrdiff_t table_size)
  {
    Lisp_Object value;
    Lisp_Object symbol_int;
        if (NILP (value))
        {
          char buf[sizeof "key-" + INT_STRLEN_BOUND (EMACS_INT)];
 -        sprintf (buf, "key-%"pI"d", symbol_num);
 +        sprintf (buf, "key-%"pD"d", symbol_num);
          value = intern (buf);
        }
  
@@@ -7173,6 -7181,7 +7185,7 @@@ tty_read_avail_input (struct terminal *
    return nread;
  }
  \f
+ #if defined SYNC_INPUT || defined SIGIO
  static void
  handle_async_input (void)
  {
    --handling_signal;
  #endif
  }
+ #endif /* SYNC_INPUT || SIGIO */
  
  #ifdef SYNC_INPUT
  void
@@@ -7566,7 -7576,7 +7580,7 @@@ menu_bar_items (Lisp_Object old
      int i = menu_bar_items_index;
      if (i + 4 > ASIZE (menu_bar_items_vector))
        menu_bar_items_vector =
 -      larger_vector (menu_bar_items_vector, 2 * i, Qnil);
 +      larger_vector (menu_bar_items_vector, 4, -1);
      /* Add this item.  */
      XVECTOR (menu_bar_items_vector)->contents[i++] = Qnil;
      XVECTOR (menu_bar_items_vector)->contents[i++] = Qnil;
@@@ -7637,7 -7647,7 +7651,7 @@@ menu_bar_item (Lisp_Object key, Lisp_Ob
      {
        /* If vector is too small, get a bigger one.  */
        if (i + 4 > ASIZE (menu_bar_items_vector))
 -      menu_bar_items_vector = larger_vector (menu_bar_items_vector, 2 * i, Qnil);
 +      menu_bar_items_vector = larger_vector (menu_bar_items_vector, 4, -1);
        /* Add this item.  */
        XVECTOR (menu_bar_items_vector)->contents[i++] = key;
        XVECTOR (menu_bar_items_vector)->contents[i++]
@@@ -7681,7 -7691,7 +7695,7 @@@ eval_dyn (Lisp_Object form
  Lisp_Object
  menu_item_eval_property (Lisp_Object sexpr)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object val;
    specbind (Qinhibit_redisplay, Qt);
    val = internal_condition_case_1 (eval_dyn, sexpr, Qerror,
@@@ -8406,14 -8416,13 +8420,14 @@@ static voi
  append_tool_bar_item (void)
  {
    Lisp_Object *to, *from;
 +  ptrdiff_t incr =
 +    (ntool_bar_items
 +     - (ASIZE (tool_bar_items_vector) - TOOL_BAR_ITEM_NSLOTS));
  
    /* Enlarge tool_bar_items_vector if necessary.  */
 -  if (ntool_bar_items + TOOL_BAR_ITEM_NSLOTS
 -      >= ASIZE (tool_bar_items_vector))
 +  if (0 < incr)
      tool_bar_items_vector
 -      = larger_vector (tool_bar_items_vector,
 -                     2 * ASIZE (tool_bar_items_vector), Qnil);
 +      = larger_vector (tool_bar_items_vector, incr, -1);
  
    /* Append entries from tool_bar_item_properties to the end of
       tool_bar_items_vector.  */
@@@ -8998,15 -9007,15 +9012,15 @@@ read_key_sequence (Lisp_Object *keybuf
                   int fix_current_buffer)
  {
    Lisp_Object from_string;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    /* How many keys there are in the current key sequence.  */
    int t;
  
    /* The length of the echo buffer when we started reading, and
       the length of this_command_keys when we started reading.  */
 -  int echo_start IF_LINT (= 0);
 -  int keys_start;
 +  ptrdiff_t echo_start IF_LINT (= 0);
 +  ptrdiff_t keys_start;
  
    /* The number of keymaps we're scanning right now, and the number of
       keymaps we have allocated space for.  */
         while those allow us to restart the entire key sequence,
         echo_local_start and keys_local_start allow us to throw away
         just one key.  */
 -      int echo_local_start IF_LINT (= 0);
 +      ptrdiff_t echo_local_start IF_LINT (= 0);
        int keys_local_start;
        ptrdiff_t local_first_binding;
  
@@@ -10150,7 -10159,7 +10164,7 @@@ will read just one key sequence.  */
    Lisp_Object keybuf[30];
    register int i;
    struct gcpro gcpro1;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    if (!NILP (prompt))
      CHECK_STRING (prompt);
@@@ -10207,7 -10216,7 +10221,7 @@@ DEFUN ("read-key-sequence-vector", Frea
    Lisp_Object keybuf[30];
    register int i;
    struct gcpro gcpro1;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    if (!NILP (prompt))
      CHECK_STRING (prompt);
@@@ -10341,146 -10350,6 +10355,6 @@@ a special event, so ignore the prefix a
  
  
  \f
- DEFUN ("execute-extended-command", Fexecute_extended_command, Sexecute_extended_command,
-        1, 1, "P",
-        doc: /* Read function name, then read its arguments and call it.
- To pass a numeric argument to the command you are invoking with, specify
- the numeric argument to this command.
- Noninteractively, the argument PREFIXARG is the prefix argument to
- give to the command you invoke, if it asks for an argument.  */)
-   (Lisp_Object prefixarg)
- {
-   Lisp_Object function;
-   ptrdiff_t saved_last_point_position;
-   Lisp_Object saved_keys, saved_last_point_position_buffer;
-   Lisp_Object bindings, value;
-   struct gcpro gcpro1, gcpro2, gcpro3;
- #ifdef HAVE_WINDOW_SYSTEM
-   /* The call to Fcompleting_read will start and cancel the hourglass,
-      but if the hourglass was already scheduled, this means that no
-      hourglass will be shown for the actual M-x command itself.
-      So we restart it if it is already scheduled.  Note that checking
-      hourglass_shown_p is not enough,  normally the hourglass is not shown,
-      just scheduled to be shown.  */
-   int hstarted = hourglass_started ();
- #endif
-   saved_keys = Fvector (this_command_key_count,
-                       XVECTOR (this_command_keys)->contents);
-   saved_last_point_position_buffer = last_point_position_buffer;
-   saved_last_point_position = last_point_position;
-   GCPRO3 (saved_keys, prefixarg, saved_last_point_position_buffer);
-   function = call0 (intern ("read-extended-command"));
- #ifdef HAVE_WINDOW_SYSTEM
-   if (hstarted) start_hourglass ();
- #endif
-   if (STRINGP (function) && SCHARS (function) == 0)
-     error ("No command name given");
-   /* Set this_command_keys to the concatenation of saved_keys and
-      function, followed by a RET.  */
-   {
-     Lisp_Object *keys;
-     int i;
-     this_command_key_count = 0;
-     this_command_key_count_reset = 0;
-     this_single_command_key_start = 0;
-     keys = XVECTOR (saved_keys)->contents;
-     for (i = 0; i < ASIZE (saved_keys); i++)
-       add_command_key (keys[i]);
-     for (i = 0; i < SCHARS (function); i++)
-       add_command_key (Faref (function, make_number (i)));
-     add_command_key (make_number ('\015'));
-   }
-   last_point_position = saved_last_point_position;
-   last_point_position_buffer = saved_last_point_position_buffer;
-   UNGCPRO;
-   function = Fintern (function, Qnil);
-   KVAR (current_kboard, Vprefix_arg) = prefixarg;
-   Vthis_command = function;
-   real_this_command = function;
-   /* If enabled, show which key runs this command.  */
-   if (!NILP (Vsuggest_key_bindings)
-       && NILP (Vexecuting_kbd_macro)
-       && SYMBOLP (function))
-     bindings = Fwhere_is_internal (function, Voverriding_local_map,
-                                  Qt, Qnil, Qnil);
-   else
-     bindings = Qnil;
-   value = Qnil;
-   GCPRO3 (bindings, value, function);
-   value = Fcommand_execute (function, Qt, Qnil, Qnil);
-   /* If the command has a key binding, print it now.  */
-   if (!NILP (bindings)
-       && ! (VECTORP (bindings) && EQ (Faref (bindings, make_number (0)),
-                                     Qmouse_movement)))
-     {
-       /* But first wait, and skip the message if there is input.  */
-       Lisp_Object waited;
-       /* If this command displayed something in the echo area;
-        wait a few seconds, then display our suggestion message.  */
-       if (NILP (echo_area_buffer[0]))
-       waited = sit_for (make_number (0), 0, 2);
-       else if (NUMBERP (Vsuggest_key_bindings))
-       waited = sit_for (Vsuggest_key_bindings, 0, 2);
-       else
-       waited = sit_for (make_number (2), 0, 2);
-       if (!NILP (waited) && ! CONSP (Vunread_command_events))
-       {
-         Lisp_Object binding;
-         char *newmessage;
-         int message_p = push_message ();
-         ptrdiff_t count = SPECPDL_INDEX ();
-         ptrdiff_t newmessage_len, newmessage_alloc;
-         USE_SAFE_ALLOCA;
-         record_unwind_protect (pop_message_unwind, Qnil);
-         binding = Fkey_description (bindings, Qnil);
-         newmessage_alloc =
-           (sizeof "You can run the command `' with "
-            + SBYTES (SYMBOL_NAME (function)) + SBYTES (binding));
-         SAFE_ALLOCA (newmessage, char *, newmessage_alloc);
-         newmessage_len =
-           esprintf (newmessage, "You can run the command `%s' with %s",
-                     SDATA (SYMBOL_NAME (function)),
-                     SDATA (binding));
-         message2 (newmessage,
-                   newmessage_len,
-                   STRING_MULTIBYTE (binding));
-         if (NUMBERP (Vsuggest_key_bindings))
-           waited = sit_for (Vsuggest_key_bindings, 0, 2);
-         else
-           waited = sit_for (make_number (2), 0, 2);
-         if (!NILP (waited) && message_p)
-           restore_message ();
-         SAFE_FREE ();
-         unbind_to (count, Qnil);
-       }
-     }
-   RETURN_UNGCPRO (value);
- }
\f
  /* Return nonzero if input events are pending.  */
  
  int
@@@ -10775,7 -10644,7 +10649,7 @@@ Some operating systems cannot stop the 
  On such systems, Emacs starts a subshell instead of suspending.  */)
    (Lisp_Object stuffstring)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int old_height, old_width;
    int width, height;
    struct gcpro gcpro1;
@@@ -10831,7 -10700,7 +10705,7 @@@ stuff_buffered_input (Lisp_Object stuff
  
    if (STRINGP (stuffstring))
      {
 -      register EMACS_INT count;
 +      register ptrdiff_t count;
  
        p = SDATA (stuffstring);
        count = SBYTES (stuffstring);
@@@ -11791,7 -11660,6 +11665,6 @@@ syms_of_keyboard (void
    defsubr (&Sset_quit_char);
    defsubr (&Sset_input_mode);
    defsubr (&Scurrent_input_mode);
-   defsubr (&Sexecute_extended_command);
    defsubr (&Sposn_at_point);
    defsubr (&Sposn_at_x_y);
  
@@@ -12195,12 -12063,6 +12068,6 @@@ If this variable is non-nil, `delayed-w
  immediately after running `post-command-hook'.  */);
    Vdelayed_warnings_list = Qnil;
  
-   DEFVAR_LISP ("suggest-key-bindings", Vsuggest_key_bindings,
-              doc: /* Non-nil means show the equivalent key-binding when M-x command has one.
- The value can be a length of time to show the message for.
- If the value is non-nil and not a number, we wait 2 seconds.  */);
-   Vsuggest_key_bindings = Qt;
    DEFVAR_LISP ("timer-list", Vtimer_list,
               doc: /* List of active absolute time timers in order of increasing time.  */);
    Vtimer_list = Qnil;
@@@ -12396,7 -12258,7 +12263,7 @@@ keys_of_keyboard (void
  }
  
  /* Mark the pointers in the kboard objects.
-    Called by the Fgarbage_collector.  */
+    Called by Fgarbage_collect.  */
  void
  mark_kboards (void)
  {
diff --combined src/keymap.c
@@@ -1117,12 -1117,12 +1117,12 @@@ binding is altered.  If there is no bin
  binding KEY to DEF is added at the front of KEYMAP.  */)
    (Lisp_Object keymap, Lisp_Object key, Lisp_Object def)
  {
 -  register int idx;
 +  register ptrdiff_t idx;
    register Lisp_Object c;
    register Lisp_Object cmd;
    int metized = 0;
    int meta_bit;
 -  int length;
 +  ptrdiff_t length;
    struct gcpro gcpro1, gcpro2, gcpro3;
  
    GCPRO3 (keymap, key, def);
    if (VECTORP (def) && ASIZE (def) > 0 && CONSP (AREF (def, 0)))
      { /* DEF is apparently an XEmacs-style keyboard macro.  */
        Lisp_Object tmp = Fmake_vector (make_number (ASIZE (def)), Qnil);
 -      int i = ASIZE (def);
 +      ptrdiff_t i = ASIZE (def);
        while (--i >= 0)
        {
          Lisp_Object defi = AREF (def, i);
@@@ -1274,10 -1274,10 +1274,10 @@@ third optional argument ACCEPT-DEFAULT 
  recognize the default bindings, just as `read-key-sequence' does.  */)
    (Lisp_Object keymap, Lisp_Object key, Lisp_Object accept_default)
  {
 -  register int idx;
 +  register ptrdiff_t idx;
    register Lisp_Object cmd;
    register Lisp_Object c;
 -  int length;
 +  ptrdiff_t length;
    int t_ok = !NILP (accept_default);
    struct gcpro gcpro1, gcpro2;
  
@@@ -1527,19 -1527,6 +1527,19 @@@ current_minor_maps (Lisp_Object **modep
    return i;
  }
  
 +/* Return the offset of POSITION, a click position, in the style of
 +   the respective argument of Fkey_binding.  */
 +static ptrdiff_t
 +click_position (Lisp_Object position)
 +{
 +  EMACS_INT pos = (INTEGERP (position) ? XINT (position)
 +                 : MARKERP (position) ? marker_position (position)
 +                 : PT);
 +  if (! (BEGV <= pos && pos <= ZV))
 +    args_out_of_range (Fcurrent_buffer (), position);
 +  return pos;
 +}
 +
  DEFUN ("current-active-maps", Fcurrent_active_maps, Scurrent_active_maps,
         0, 2, 0,
         doc: /* Return a list of the currently active keymaps.
@@@ -1548,7 -1535,7 +1548,7 @@@ OLP if non-nil indicates that we shoul
  like in the respective argument of `key-binding'. */)
    (Lisp_Object olp, Lisp_Object position)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    Lisp_Object keymaps = Fcons (current_global_map, Qnil);
  
      {
        Lisp_Object *maps;
        int nmaps, i;
 -      EMACS_INT pt
 -      = INTEGERP (position) ? XINT (position)
 -      : MARKERP (position) ? marker_position (position)
 -      : PT;
 +      ptrdiff_t pt = click_position (position);
        /* This usually returns the buffer's local map,
         but that can be overridden by a `local-map' property.  */
        Lisp_Object local_map = get_local_map (pt, current_buffer, Qlocal_map);
@@@ -1914,10 -1904,10 +1914,10 @@@ accessible_keymaps_1 (Lisp_Object key, 
    while (!NILP (tem = Frassq (cmd, maps)))
      {
        Lisp_Object prefix = XCAR (tem);
 -      int lim = XINT (Flength (XCAR (tem)));
 +      ptrdiff_t lim = XINT (Flength (XCAR (tem)));
        if (lim <= XINT (Flength (thisseq)))
        { /* This keymap was already seen with a smaller prefix.  */
 -        int i = 0;
 +        ptrdiff_t i = 0;
          while (i < lim && EQ (Faref (prefix, make_number (i)),
                                Faref (thisseq, make_number (i))))
            i++;
@@@ -1970,7 -1960,7 +1970,7 @@@ then the value includes only maps for p
    (Lisp_Object keymap, Lisp_Object prefix)
  {
    Lisp_Object maps, tail;
 -  int prefixlen = XINT (Flength (prefix));
 +  EMACS_INT prefixlen = XFASTINT (Flength (prefix));
  
    /* no need for gcpro because we don't autoload any keymaps.  */
  
@@@ -2058,25 -2048,20 +2058,25 @@@ For example, [?\C-x ?l] is converted in
  The `kbd' macro is an approximate inverse of this.  */)
    (Lisp_Object keys, Lisp_Object prefix)
  {
 -  int len = 0;
 -  int i, i_byte;
 +  ptrdiff_t len = 0;
 +  EMACS_INT i;
 +  ptrdiff_t i_byte;
    Lisp_Object *args;
 -  int size = XINT (Flength (keys));
 +  EMACS_INT size = XINT (Flength (keys));
    Lisp_Object list;
    Lisp_Object sep = build_string (" ");
    Lisp_Object key;
 +  Lisp_Object result;
    int add_meta = 0;
 +  USE_SAFE_ALLOCA;
  
    if (!NILP (prefix))
      size += XINT (Flength (prefix));
  
    /* This has one extra element at the end that we don't pass to Fconcat.  */
 -  args = (Lisp_Object *) alloca (size * 4 * sizeof (Lisp_Object));
 +  if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (Lisp_Object) / 4 < size)
 +    memory_full (SIZE_MAX);
 +  SAFE_ALLOCA_LISP (args, size * 4);
  
    /* In effect, this computes
       (mapconcat 'single-key-description keys " ")
        if (add_meta)
        {
          args[len] = Fsingle_key_description (meta_prefix_char, Qnil);
 -        len += 2;
 +        result = Fconcat (len + 1, args);
        }
        else if (len == 0)
 -      return empty_unibyte_string;
 -      return Fconcat (len - 1, args);
 +      result = empty_unibyte_string;
 +      else
 +      result = Fconcat (len - 1, args);
 +      SAFE_FREE ();
 +      return result;
      }
  
    if (STRINGP (list))
@@@ -2368,7 -2350,7 +2368,7 @@@ See Info node `(elisp)Describing Charac
    char str[6];
    int c;
  
 -  CHECK_NUMBER (character);
 +  CHECK_CHARACTER (character);
  
    c = XINT (character);
    if (!ASCII_CHAR_P (c))
@@@ -2391,8 -2373,8 +2391,8 @@@ static int where_is_preferred_modifier
  static int
  preferred_sequence_p (Lisp_Object seq)
  {
 -  int i;
 -  int len = XINT (Flength (seq));
 +  EMACS_INT i;
 +  EMACS_INT len = XFASTINT (Flength (seq));
    int result = 1;
  
    for (i = 0; i < len; i++)
@@@ -2571,7 -2553,8 +2571,8 @@@ where_is_internal (Lisp_Object definiti
  DEFUN ("where-is-internal", Fwhere_is_internal, Swhere_is_internal, 1, 5, 0,
         doc: /* Return list of keys that invoke DEFINITION.
  If KEYMAP is a keymap, search only KEYMAP and the global keymap.
- If KEYMAP is nil, search all the currently active keymaps.
+ If KEYMAP is nil, search all the currently active keymaps, except
+  for `overriding-local-map' (which is ignored).
  If KEYMAP is a list of keymaps, search only those keymaps.
  
  If optional 3rd arg FIRSTONLY is non-nil, return the first key sequence found,
@@@ -2586,9 -2569,17 +2587,17 @@@ If optional 4th arg NOINDIRECT is non-n
  to other keymaps or slots.  This makes it possible to search for an
  indirect definition itself.
  
- If optional 5th arg NO-REMAP is non-nil, don't search for key sequences
- that invoke a command which is remapped to DEFINITION, but include the
- remapped command in the returned list.  */)
+ The optional 5th arg NO-REMAP alters how command remapping is handled:
+ - If another command OTHER-COMMAND is remapped to DEFINITION, normally
+   search for the bindings of OTHER-COMMAND and include them in the
+   returned list.  But if NO-REMAP is non-nil, include the vector
+   [remap OTHER-COMMAND] in the returned list instead, without
+   searching for those other bindings.
+ - If DEFINITION is remapped to OTHER-COMMAND, normally return the
+   bindings for OTHER-COMMAND.  But if NO-REMAP is non-nil, return the
+   bindings for DEFINITION instead, ignoring its remapping.  */)
    (Lisp_Object definition, Lisp_Object keymap, Lisp_Object firstonly, Lisp_Object noindirect, Lisp_Object no_remap)
  {
    /* The keymaps in which to search.  */
@@@ -3109,7 -3100,7 +3118,7 @@@ static voi
  describe_command (Lisp_Object definition, Lisp_Object args)
  {
    register Lisp_Object tem1;
 -  EMACS_INT column = current_column ();
 +  ptrdiff_t column = current_column ();
    int description_column;
  
    /* If column 16 is no good, go to col 32;
@@@ -3392,7 -3383,7 +3401,7 @@@ This is text showing the elements of ve
  DESCRIBER is the output function used; nil means use `princ'.  */)
    (Lisp_Object vector, Lisp_Object describer)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    if (NILP (describer))
      describer = intern ("princ");
    specbind (Qstandard_output, Fcurrent_buffer ());
diff --combined src/lisp.h
@@@ -41,25 -41,36 +41,36 @@@ extern void check_cons_list (void)
     Build with CFLAGS='-DWIDE_EMACS_INT' to try them out.  */
  /* #undef WIDE_EMACS_INT */
  
- /* These are default choices for the types to use.  */
+ /* EMACS_INT - signed integer wide enough to hold an Emacs value
+    EMACS_INT_MAX - maximum value of EMACS_INT; can be used in #if
+    pI - printf length modifier for EMACS_INT
+    EMACS_UINT - unsigned variant of EMACS_INT */
  #ifndef EMACS_INT
- # if BITS_PER_LONG < BITS_PER_LONG_LONG && defined WIDE_EMACS_INT
+ # if LONG_MAX < LLONG_MAX && defined WIDE_EMACS_INT
  #  define EMACS_INT long long
- #  define BITS_PER_EMACS_INT BITS_PER_LONG_LONG
+ #  define EMACS_INT_MAX LLONG_MAX
  #  define pI "ll"
- # elif BITS_PER_INT < BITS_PER_LONG
+ # elif INT_MAX < LONG_MAX
  #  define EMACS_INT long
- #  define BITS_PER_EMACS_INT BITS_PER_LONG
+ #  define EMACS_INT_MAX LONG_MAX
  #  define pI "l"
  # else
  #  define EMACS_INT int
- #  define BITS_PER_EMACS_INT BITS_PER_INT
+ #  define EMACS_INT_MAX INT_MAX
  #  define pI ""
  # endif
  #endif
- #ifndef EMACS_UINT
- # define EMACS_UINT unsigned EMACS_INT
- #endif
+ #define EMACS_UINT unsigned EMACS_INT
+ /* Number of bits in some machine integer types.  */
+ enum
+   {
+     BITS_PER_CHAR      = CHAR_BIT,
+     BITS_PER_SHORT     = CHAR_BIT * sizeof (short),
+     BITS_PER_INT       = CHAR_BIT * sizeof (int),
+     BITS_PER_LONG      = CHAR_BIT * sizeof (long int),
+     BITS_PER_EMACS_INT = CHAR_BIT * sizeof (EMACS_INT)
+   };
  
  /* printmax_t and uprintmax_t are types for printing large integers.
     These are the widest integers that are supported for printing.
@@@ -164,13 -175,13 +175,13 @@@ extern int suppress_checking EXTERNALLY
     variable VAR of type TYPE with the added requirement that it be
     TYPEBITS-aligned.  */
  
- #ifndef GCTYPEBITS
  #define GCTYPEBITS 3
- #endif
- #ifndef VALBITS
  #define VALBITS (BITS_PER_EMACS_INT - GCTYPEBITS)
- #endif
+ /* The maximum value that can be stored in a EMACS_INT, assuming all
+    bits other than the type bits contribute to a nonnegative signed value.
+    This can be used in #if, e.g., '#if VAL_MAX < UINTPTR_MAX' below.  */
+ #define VAL_MAX (EMACS_INT_MAX >> (GCTYPEBITS - 1))
  
  #ifndef NO_DECL_ALIGN
  # ifndef DECL_ALIGN
       || defined DARWIN_OS || defined __sun)
  /* We also need to be able to specify mult-of-8 alignment on static vars.  */
  # if defined DECL_ALIGN
- /* On hosts where VALBITS is greater than the pointer width in bits,
+ /* On hosts where pointers-as-ints do not exceed VAL_MAX,
     USE_LSB_TAG is:
      a. unnecessary, because the top bits of an EMACS_INT are unused, and
      b. slower, because it typically requires extra masking.
     So, define USE_LSB_TAG only on hosts where it might be useful.  */
- #  if UINTPTR_MAX >> VALBITS != 0
+ #  if VAL_MAX < UINTPTR_MAX
  #   define USE_LSB_TAG
  #  endif
  # endif
@@@ -395,13 -406,14 +406,13 @@@ typedef EMACS_INT Lisp_Object
  #define LISP_MAKE_RVALUE(o) (0+(o))
  #endif /* USE_LISP_UNION_TYPE */
  
 -/* In the size word of a vector, this bit means the vector has been marked.
 -   (Shift -1 left, not 1, to avoid provoking overflow diagnostics.)  */
 +/* In the size word of a vector, this bit means the vector has been marked.  */
  
 -#define ARRAY_MARK_FLAG ((EMACS_INT) -1 << (BITS_PER_EMACS_INT - 1))
 +#define ARRAY_MARK_FLAG PTRDIFF_MIN
  
  /* In the size word of a struct Lisp_Vector, this bit means it's really
     some other vector-like object.  */
 -#define PSEUDOVECTOR_FLAG ((EMACS_INT) 1 << (BITS_PER_EMACS_INT - 2))
 +#define PSEUDOVECTOR_FLAG (PTRDIFF_MAX - PTRDIFF_MAX / 2)
  
  /* In a pseudovector, the size field actually contains a word with one
     PSEUDOVECTOR_FLAG bit set, and exactly one of the following bits to
@@@ -474,10 -486,11 +485,11 @@@ enum pvec_typ
       (var) = (type) | (intptr_t) (ptr))
  
  #define XPNTR(a) ((intptr_t) ((a) & ~TYPEMASK))
+ #define XUNTAG(a, type) ((intptr_t) ((a) - (type)))
  
  #else  /* not USE_LSB_TAG */
  
- #define VALMASK ((((EMACS_INT) 1) << VALBITS) - 1)
+ #define VALMASK VAL_MAX
  
  /* One need to override this if there must be high bits set in data space
     (doing the result of the below & ((1 << (GCTYPE + 1)) - 1) would work
@@@ -580,6 -593,13 +592,13 @@@ extern Lisp_Object make_number (EMACS_I
  # define XSETFASTINT(a, b) (XSETINT (a, b))
  #endif
  
+ /* Extract the pointer value of the Lisp object A, under the
+    assumption that A's type is TYPE.  This is a fallback
+    implementation if nothing faster is available.  */
+ #ifndef XUNTAG
+ # define XUNTAG(a, type) XPNTR (a)
+ #endif
  #define EQ(x, y) (XHASH (x) == XHASH (y))
  
  /* Number of bits in a fixnum, including the sign bit.  */
  #define FIXNUM_OVERFLOW_P(i) \
    (! ((0 <= (i) || MOST_NEGATIVE_FIXNUM <= (i)) && (i) <= MOST_POSITIVE_FIXNUM))
  
 +static inline ptrdiff_t
 +clip_to_bounds (ptrdiff_t lower, EMACS_INT num, ptrdiff_t upper)
 +{
 +  return num < lower ? lower : num <= upper ? num : upper;
 +}
 +
  /* Extract a value or address from a Lisp_Object.  */
  
- #define XCONS(a) (eassert (CONSP (a)), (struct Lisp_Cons *) XPNTR (a))
- #define XVECTOR(a) (eassert (VECTORLIKEP (a)), (struct Lisp_Vector *) XPNTR (a))
- #define XSTRING(a) (eassert (STRINGP (a)), (struct Lisp_String *) XPNTR (a))
- #define XSYMBOL(a) (eassert (SYMBOLP (a)), (struct Lisp_Symbol *) XPNTR (a))
- #define XFLOAT(a) (eassert (FLOATP (a)), (struct Lisp_Float *) XPNTR (a))
+ #define XCONS(a)   (eassert (CONSP (a)), \
+                   (struct Lisp_Cons *) XUNTAG (a, Lisp_Cons))
+ #define XVECTOR(a) (eassert (VECTORLIKEP (a)), \
+                   (struct Lisp_Vector *) XUNTAG (a, Lisp_Vectorlike))
+ #define XSTRING(a) (eassert (STRINGP (a)), \
+                   (struct Lisp_String *) XUNTAG (a, Lisp_String))
+ #define XSYMBOL(a) (eassert (SYMBOLP (a)), \
+                   (struct Lisp_Symbol *) XUNTAG (a, Lisp_Symbol))
+ #define XFLOAT(a)  (eassert (FLOATP (a)), \
+                   (struct Lisp_Float *) XUNTAG (a, Lisp_Float))
  
  /* Misc types.  */
  
- #define XMISC(a)   ((union Lisp_Misc *) XPNTR (a))
+ #define XMISC(a)      ((union Lisp_Misc *) XUNTAG (a, Lisp_Misc))
  #define XMISCANY(a)   (eassert (MISCP (a)), &(XMISC (a)->u_any))
  #define XMISCTYPE(a)   (XMISCANY (a)->type)
  #define XMARKER(a)    (eassert (MARKERP (a)), &(XMISC (a)->u_marker))
  
  /* Pseudovector types.  */
  
- #define XPROCESS(a) (eassert (PROCESSP (a)), (struct Lisp_Process *) XPNTR (a))
- #define XWINDOW(a) (eassert (WINDOWP (a)), (struct window *) XPNTR (a))
- #define XTERMINAL(a) (eassert (TERMINALP (a)), (struct terminal *) XPNTR (a))
- #define XSUBR(a) (eassert (SUBRP (a)), (struct Lisp_Subr *) XPNTR (a))
- #define XBUFFER(a) (eassert (BUFFERP (a)), (struct buffer *) XPNTR (a))
- #define XCHAR_TABLE(a) (eassert (CHAR_TABLE_P (a)), (struct Lisp_Char_Table *) XPNTR (a))
- #define XSUB_CHAR_TABLE(a) (eassert (SUB_CHAR_TABLE_P (a)), (struct Lisp_Sub_Char_Table *) XPNTR (a))
- #define XBOOL_VECTOR(a) (eassert (BOOL_VECTOR_P (a)), (struct Lisp_Bool_Vector *) XPNTR (a))
+ #define XPROCESS(a) (eassert (PROCESSP (a)), \
+                    (struct Lisp_Process *) XUNTAG (a, Lisp_Vectorlike))
+ #define XWINDOW(a) (eassert (WINDOWP (a)), \
+                   (struct window *) XUNTAG (a, Lisp_Vectorlike))
+ #define XTERMINAL(a) (eassert (TERMINALP (a)), \
+                     (struct terminal *) XUNTAG (a, Lisp_Vectorlike))
+ #define XSUBR(a) (eassert (SUBRP (a)), \
+                 (struct Lisp_Subr *) XUNTAG (a, Lisp_Vectorlike))
+ #define XBUFFER(a) (eassert (BUFFERP (a)), \
+                   (struct buffer *) XUNTAG (a, Lisp_Vectorlike))
+ #define XCHAR_TABLE(a) (eassert (CHAR_TABLE_P (a)), \
+                       (struct Lisp_Char_Table *) XUNTAG (a, Lisp_Vectorlike))
+ #define XSUB_CHAR_TABLE(a) (eassert (SUB_CHAR_TABLE_P (a)), \
+                           ((struct Lisp_Sub_Char_Table *) \
+                            XUNTAG (a, Lisp_Vectorlike)))
+ #define XBOOL_VECTOR(a) (eassert (BOOL_VECTOR_P (a)), \
+                        ((struct Lisp_Bool_Vector *) \
+                         XUNTAG (a, Lisp_Vectorlike)))
  
  /* Construct a Lisp_Object from a value or address.  */
  
  /* The cast to struct vectorlike_header * avoids aliasing issues.  */
  #define XSETPSEUDOVECTOR(a, b, code) \
    XSETTYPED_PSEUDOVECTOR(a, b,       \
-                        ((struct vectorlike_header *) XPNTR (a))->size, \
+                        (((struct vectorlike_header *) \
+                          XUNTAG (a, Lisp_Vectorlike)) \
+                         ->size),                      \
                         code)
  #define XSETTYPED_PSEUDOVECTOR(a, b, size, code)                      \
    (XSETVECTOR (a, b),                                                 \
@@@ -816,7 -847,7 +852,7 @@@ struct Lisp_Con
  #ifdef GC_CHECK_STRING_BYTES
  
  struct Lisp_String;
 -extern EMACS_INT string_bytes (struct Lisp_String *);
 +extern ptrdiff_t string_bytes (struct Lisp_String *);
  #define STRING_BYTES(S) string_bytes ((S))
  
  #else /* not GC_CHECK_STRING_BYTES */
  
  struct Lisp_String
    {
 -    EMACS_INT size;
 -    EMACS_INT size_byte;
 +    ptrdiff_t size;
 +    ptrdiff_t size_byte;
      INTERVAL intervals;               /* text properties in this string */
      unsigned char *data;
    };
     <http://debbugs.gnu.org/cgi/bugreport.cgi?bug=8546>.  */
  struct vectorlike_header
    {
 -    EMACS_INT size;
 +    ptrdiff_t size;
  
      /* Pointer to the next vector-like object.  It is generally a buffer or a
         Lisp_Vector alias, so for convenience it is a union instead of a
@@@ -1073,7 -1104,7 +1109,7 @@@ struct Lisp_Bool_Vecto
  
  struct Lisp_Subr
    {
 -    EMACS_INT size;
 +    ptrdiff_t size;
      union {
        Lisp_Object (*a0) (void);
        Lisp_Object (*a1) (Lisp_Object);
@@@ -1260,7 -1291,7 +1296,7 @@@ struct Lisp_Hash_Tabl
       a special way (e.g. because of weakness).  */
  
    /* Number of key/value entries in the table.  */
 -  EMACS_INT count;
 +  ptrdiff_t count;
  
    /* Vector of keys and values.  The key of item I is found at index
       2 * I, the value is found at index 2 * I + 1.
  
  
  #define XHASH_TABLE(OBJ) \
-      ((struct Lisp_Hash_Table *) XPNTR (OBJ))
+      ((struct Lisp_Hash_Table *) XUNTAG (OBJ, Lisp_Vectorlike))
  
  #define XSET_HASH_TABLE(VAR, PTR) \
       (XSETPSEUDOVECTOR (VAR, PTR, PVEC_HASH_TABLE))
@@@ -1375,12 -1406,12 +1411,12 @@@ struct Lisp_Marke
       That would also allow to preserve it ordered.  */
    struct Lisp_Marker *next;
    /* This is the char position where the marker points.  */
 -  EMACS_INT charpos;
 +  ptrdiff_t charpos;
    /* This is the byte position.
       It's mostly used as a charpos<->bytepos cache (i.e. it's not directly
       used to implement the functionality of markers, but rather to (ab)use
       markers as a cache for char<->byte mappings).  */
 -  EMACS_INT bytepos;
 +  ptrdiff_t bytepos;
  };
  
  /* Forwarding pointer to an int variable.
@@@ -1639,24 -1670,18 +1675,24 @@@ typedef struct 
     encodes a char code in the lower CHARACTERBITS bits and a (very small)
     face-id in the upper bits, or it may be a cons (CHAR . FACE-ID).  */
  
 -#define GLYPH_CODE_CHAR(gc) \
 -  (CONSP (gc) ? XINT (XCAR (gc)) : INTEGERP (gc) ? (XINT (gc) & ((1 << CHARACTERBITS)-1)) : 0)
 +#define GLYPH_CODE_P(gc)                                              \
 +  (CONSP (gc)                                                         \
 +   ? (CHARACTERP (XCAR (gc))                                          \
 +      && RANGED_INTEGERP (0, XCDR (gc), MAX_FACE_ID))                 \
 +   : (RANGED_INTEGERP                                                 \
 +      (0, gc,                                                         \
 +       (MAX_FACE_ID < TYPE_MAXIMUM (EMACS_INT) >> CHARACTERBITS               \
 +      ? ((EMACS_INT) MAX_FACE_ID << CHARACTERBITS) | MAX_CHAR         \
 +      : TYPE_MAXIMUM (EMACS_INT)))))
  
 -#define GLYPH_CODE_FACE(gc) \
 -  (CONSP (gc) ? XINT (XCDR (gc)) : INTEGERP (gc) ? (XINT (gc) >> CHARACTERBITS) : DEFAULT_FACE_ID)
 +/* The following are valid only if GLYPH_CODE_P (gc).  */
  
 -/* Return 1 if glyph code from display vector contains valid character code.  */
 -#define GLYPH_CODE_CHAR_VALID_P(gc) CHAR_VALID_P (GLYPH_CODE_CHAR (gc))
 +#define GLYPH_CODE_CHAR(gc) \
 +  (CONSP (gc) ? XINT (XCAR (gc)) : XINT (gc) & ((1 << CHARACTERBITS) - 1))
  
 -#define GLYPH_CODE_P(gc) ((CONSP (gc) && INTEGERP (XCAR (gc)) && INTEGERP (XCDR (gc))) || INTEGERP (gc))
 +#define GLYPH_CODE_FACE(gc) \
 +  (CONSP (gc) ? XINT (XCDR (gc)) : XINT (gc) >> CHARACTERBITS)
  
 -/* Only called when GLYPH_CODE_P (gc) is true.  */
  #define SET_GLYPH_FROM_GLYPH_CODE(glyph, gc)                          \
    do                                                                  \
      {                                                                 \
@@@ -1716,9 -1741,7 +1752,9 @@@ typedef struct 
  #define RANGED_INTEGERP(lo, x, hi) \
    (INTEGERP (x) && (lo) <= XINT (x) && XINT (x) <= (hi))
  #define TYPE_RANGED_INTEGERP(type, x) \
 -  RANGED_INTEGERP (TYPE_MINIMUM (type), x, TYPE_MAXIMUM (type))
 +  (TYPE_SIGNED (type)                                                 \
 +   ? RANGED_INTEGERP (TYPE_MINIMUM (type), x, TYPE_MAXIMUM (type))    \
 +   : RANGED_INTEGERP (0, x, TYPE_MAXIMUM (type)))
  
  #define INTEGERP(x) (LISP_INT_TAG_P (XTYPE ((x))))
  #define SYMBOLP(x) (XTYPE ((x)) == Lisp_Symbol)
     code is CODE.  */
  #define TYPED_PSEUDOVECTORP(x, t, code)                               \
    (VECTORLIKEP (x)                                            \
-    && (((((struct t *) XPNTR (x))->size                               \
+    && (((((struct t *) XUNTAG (x, Lisp_Vectorlike))->size     \
         & (PSEUDOVECTOR_FLAG | (code))))                       \
         == (PSEUDOVECTOR_FLAG | (code))))
  
  #define CHECK_NATNUM(x) \
    CHECK_TYPE (NATNUMP (x), Qwholenump, x)
  
 +#define CHECK_RANGED_INTEGER(lo, x, hi)                                       \
 +  do {                                                                        \
 +    CHECK_NUMBER (x);                                                 \
 +    if (! ((lo) <= XINT (x) && XINT (x) <= (hi)))                     \
 +      args_out_of_range_3                                             \
 +      (x,                                                             \
 +       make_number ((lo) < 0 && (lo) < MOST_NEGATIVE_FIXNUM           \
 +                    ? MOST_NEGATIVE_FIXNUM                            \
 +                    : (lo)),                                          \
 +       make_number (min (hi, MOST_POSITIVE_FIXNUM)));                 \
 +  } while (0)
 +#define CHECK_TYPE_RANGED_INTEGER(type, x) \
 +  do {                                                                        \
 +    if (TYPE_SIGNED (type))                                           \
 +      CHECK_RANGED_INTEGER (TYPE_MINIMUM (type), x, TYPE_MAXIMUM (type)); \
 +    else                                                              \
 +      CHECK_RANGED_INTEGER (0, x, TYPE_MAXIMUM (type));                       \
 +  } while (0)
 +
  #define CHECK_MARKER(x) \
    CHECK_TYPE (MARKERP (x), Qmarkerp, x)
  
@@@ -2078,9 -2082,9 +2114,9 @@@ struct specbindin
  
  extern struct specbinding *specpdl;
  extern struct specbinding *specpdl_ptr;
 -extern EMACS_INT specpdl_size;
 +extern ptrdiff_t specpdl_size;
  
 -#define SPECPDL_INDEX()       ((int) (specpdl_ptr - specpdl))
 +#define SPECPDL_INDEX()       (specpdl_ptr - specpdl)
  
  /* Everything needed to describe an active condition case.  */
  struct handler
@@@ -2133,8 -2137,8 +2169,8 @@@ struct catchta
    jmp_buf jmp;
    struct backtrace *backlist;
    struct handler *handlerlist;
 -  int lisp_eval_depth;
 -  int pdlcount;
 +  EMACS_INT lisp_eval_depth;
 +  ptrdiff_t pdlcount;
    int poll_suppress_count;
    int interrupt_input_blocked;
    struct byte_stack *byte_stack;
@@@ -2409,7 -2413,7 +2445,7 @@@ extern Lisp_Object Qerror, Qquit, Qargs
  extern Lisp_Object Qvoid_variable, Qvoid_function;
  extern Lisp_Object Qinvalid_read_syntax;
  extern Lisp_Object Qinvalid_function, Qwrong_number_of_arguments, Qno_catch;
- extern Lisp_Object Qend_of_file, Qarith_error, Qmark_inactive;
+ extern Lisp_Object Quser_error, Qend_of_file, Qarith_error, Qmark_inactive;
  extern Lisp_Object Qbeginning_of_buffer, Qend_of_buffer, Qbuffer_read_only;
  extern Lisp_Object Qtext_read_only;
  extern Lisp_Object Qinteractive_form;
@@@ -2540,8 -2544,8 +2576,8 @@@ EXFUN (Fread_coding_system, 2)
  EXFUN (Fread_non_nil_coding_system, 1);
  EXFUN (Ffind_operation_coding_system, MANY);
  EXFUN (Fdecode_coding_string, 4);
 -extern Lisp_Object detect_coding_system (const unsigned char *, EMACS_INT,
 -                                         EMACS_INT, int, int, Lisp_Object);
 +extern Lisp_Object detect_coding_system (const unsigned char *, ptrdiff_t,
 +                                         ptrdiff_t, int, int, Lisp_Object);
  extern void init_coding (void);
  extern void init_coding_once (void);
  extern void syms_of_coding (void);
  /* Defined in character.c */
  EXFUN (Fchar_width, 1);
  EXFUN (Fstring, MANY);
 -extern EMACS_INT chars_in_text (const unsigned char *, EMACS_INT);
 -extern EMACS_INT multibyte_chars_in_text (const unsigned char *, EMACS_INT);
 +extern ptrdiff_t chars_in_text (const unsigned char *, ptrdiff_t);
 +extern ptrdiff_t multibyte_chars_in_text (const unsigned char *, ptrdiff_t);
  extern int multibyte_char_to_unibyte (int);
  extern int multibyte_char_to_unibyte_safe (int);
  extern void init_character_once (void);
@@@ -2577,7 -2581,7 +2613,7 @@@ extern void syms_of_syntax (void)
  extern Lisp_Object QCrehash_size, QCrehash_threshold;
  enum { NEXT_ALMOST_PRIME_LIMIT = 11 };
  extern EMACS_INT next_almost_prime (EMACS_INT);
 -extern Lisp_Object larger_vector (Lisp_Object, EMACS_INT, Lisp_Object);
 +extern Lisp_Object larger_vector (Lisp_Object, ptrdiff_t, ptrdiff_t);
  extern void sweep_weak_hash_tables (void);
  extern Lisp_Object Qcursor_in_echo_area;
  extern Lisp_Object Qstring_lessp;
@@@ -2609,8 -2613,8 +2645,8 @@@ EXFUN (Fstring_as_multibyte, 1)
  EXFUN (Fstring_as_unibyte, 1);
  EXFUN (Fstring_to_multibyte, 1);
  EXFUN (Fsubstring, 3);
 -extern Lisp_Object substring_both (Lisp_Object, EMACS_INT, EMACS_INT,
 -                                 EMACS_INT, EMACS_INT);
 +extern Lisp_Object substring_both (Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                                 ptrdiff_t, ptrdiff_t);
  EXFUN (Fnth, 2);
  EXFUN (Fnthcdr, 2);
  EXFUN (Fmemq, 2);
@@@ -2638,8 -2642,8 +2674,8 @@@ extern Lisp_Object nconc2 (Lisp_Object
  extern Lisp_Object assq_no_quit (Lisp_Object, Lisp_Object);
  extern Lisp_Object assoc_no_quit (Lisp_Object, Lisp_Object);
  extern void clear_string_char_byte_cache (void);
 -extern EMACS_INT string_char_to_byte (Lisp_Object, EMACS_INT);
 -extern EMACS_INT string_byte_to_char (Lisp_Object, EMACS_INT);
 +extern ptrdiff_t string_char_to_byte (Lisp_Object, ptrdiff_t);
 +extern ptrdiff_t string_byte_to_char (Lisp_Object, ptrdiff_t);
  extern Lisp_Object string_to_multibyte (Lisp_Object);
  extern Lisp_Object string_make_unibyte (Lisp_Object);
  EXFUN (Fcopy_alist, 1);
@@@ -2677,48 -2681,48 +2713,48 @@@ extern void init_image (void)
  
  /* Defined in insdel.c */
  extern Lisp_Object Qinhibit_modification_hooks;
 -extern void move_gap (EMACS_INT);
 -extern void move_gap_both (EMACS_INT, EMACS_INT);
 +extern void move_gap (ptrdiff_t);
 +extern void move_gap_both (ptrdiff_t, ptrdiff_t);
  extern void buffer_overflow (void) NO_RETURN;
 -extern void make_gap (EMACS_INT);
 -extern EMACS_INT copy_text (const unsigned char *, unsigned char *,
 -                          EMACS_INT, int, int);
 +extern void make_gap (ptrdiff_t);
 +extern ptrdiff_t copy_text (const unsigned char *, unsigned char *,
 +                          ptrdiff_t, int, int);
  extern int count_combining_before (const unsigned char *,
 -                                 EMACS_INT, EMACS_INT, EMACS_INT);
 +                                 ptrdiff_t, ptrdiff_t, ptrdiff_t);
  extern int count_combining_after (const unsigned char *,
 -                                EMACS_INT, EMACS_INT, EMACS_INT);
 -extern void insert (const char *, EMACS_INT);
 -extern void insert_and_inherit (const char *, EMACS_INT);
 -extern void insert_1 (const char *, EMACS_INT, int, int, int);
 -extern void insert_1_both (const char *, EMACS_INT, EMACS_INT,
 +                                ptrdiff_t, ptrdiff_t, ptrdiff_t);
 +extern void insert (const char *, ptrdiff_t);
 +extern void insert_and_inherit (const char *, ptrdiff_t);
 +extern void insert_1 (const char *, ptrdiff_t, int, int, int);
 +extern void insert_1_both (const char *, ptrdiff_t, ptrdiff_t,
                           int, int, int);
 -extern void insert_from_gap (EMACS_INT, EMACS_INT);
 -extern void insert_from_string (Lisp_Object, EMACS_INT, EMACS_INT,
 -                              EMACS_INT, EMACS_INT, int);
 -extern void insert_from_buffer (struct buffer *, EMACS_INT, EMACS_INT, int);
 +extern void insert_from_gap (ptrdiff_t, ptrdiff_t);
 +extern void insert_from_string (Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                              ptrdiff_t, ptrdiff_t, int);
 +extern void insert_from_buffer (struct buffer *, ptrdiff_t, ptrdiff_t, int);
  extern void insert_char (int);
  extern void insert_string (const char *);
 -extern void insert_before_markers (const char *, EMACS_INT);
 -extern void insert_before_markers_and_inherit (const char *, EMACS_INT);
 -extern void insert_from_string_before_markers (Lisp_Object, EMACS_INT,
 -                                             EMACS_INT, EMACS_INT,
 -                                             EMACS_INT, int);
 -extern void del_range (EMACS_INT, EMACS_INT);
 -extern Lisp_Object del_range_1 (EMACS_INT, EMACS_INT, int, int);
 -extern void del_range_byte (EMACS_INT, EMACS_INT, int);
 -extern void del_range_both (EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT, int);
 -extern Lisp_Object del_range_2 (EMACS_INT, EMACS_INT,
 -                              EMACS_INT, EMACS_INT, int);
 -extern void modify_region (struct buffer *, EMACS_INT, EMACS_INT, int);
 -extern void prepare_to_modify_buffer (EMACS_INT, EMACS_INT, EMACS_INT *);
 -extern void signal_after_change (EMACS_INT, EMACS_INT, EMACS_INT);
 -extern void adjust_after_insert (EMACS_INT, EMACS_INT, EMACS_INT,
 -                               EMACS_INT, EMACS_INT);
 -extern void adjust_markers_for_delete (EMACS_INT, EMACS_INT,
 -                                     EMACS_INT, EMACS_INT);
 -extern void replace_range (EMACS_INT, EMACS_INT, Lisp_Object, int, int, int);
 -extern void replace_range_2 (EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT,
 -                           const char *, EMACS_INT, EMACS_INT, int);
 +extern void insert_before_markers (const char *, ptrdiff_t);
 +extern void insert_before_markers_and_inherit (const char *, ptrdiff_t);
 +extern void insert_from_string_before_markers (Lisp_Object, ptrdiff_t,
 +                                             ptrdiff_t, ptrdiff_t,
 +                                             ptrdiff_t, int);
 +extern void del_range (ptrdiff_t, ptrdiff_t);
 +extern Lisp_Object del_range_1 (ptrdiff_t, ptrdiff_t, int, int);
 +extern void del_range_byte (ptrdiff_t, ptrdiff_t, int);
 +extern void del_range_both (ptrdiff_t, ptrdiff_t, ptrdiff_t, ptrdiff_t, int);
 +extern Lisp_Object del_range_2 (ptrdiff_t, ptrdiff_t,
 +                              ptrdiff_t, ptrdiff_t, int);
 +extern void modify_region (struct buffer *, ptrdiff_t, ptrdiff_t, int);
 +extern void prepare_to_modify_buffer (ptrdiff_t, ptrdiff_t, ptrdiff_t *);
 +extern void signal_after_change (ptrdiff_t, ptrdiff_t, ptrdiff_t);
 +extern void adjust_after_insert (ptrdiff_t, ptrdiff_t, ptrdiff_t,
 +                               ptrdiff_t, ptrdiff_t);
 +extern void adjust_markers_for_delete (ptrdiff_t, ptrdiff_t,
 +                                     ptrdiff_t, ptrdiff_t);
 +extern void replace_range (ptrdiff_t, ptrdiff_t, Lisp_Object, int, int, int);
 +extern void replace_range_2 (ptrdiff_t, ptrdiff_t, ptrdiff_t, ptrdiff_t,
 +                           const char *, ptrdiff_t, ptrdiff_t, int);
  extern void syms_of_insdel (void);
  
  /* Defined in dispnew.c */
@@@ -2726,7 -2730,6 +2762,7 @@@ extern Lisp_Object selected_frame
  extern Lisp_Object Vwindow_system;
  EXFUN (Fding, 1);
  EXFUN (Fredraw_frame, 1);
 +void duration_to_sec_usec (double, int *, int *);
  EXFUN (Fsleep_for, 2);
  EXFUN (Fredisplay, 1);
  extern Lisp_Object sit_for (Lisp_Object, int, int);
@@@ -2748,7 -2751,7 +2784,7 @@@ extern Lisp_Object QCdata, QCfile
  extern Lisp_Object QCmap;
  extern Lisp_Object Qrisky_local_variable;
  extern struct frame *last_glyphless_glyph_frame;
 -extern unsigned last_glyphless_glyph_face_id;
 +extern int last_glyphless_glyph_face_id;
  extern int last_glyphless_glyph_merged_face_id;
  extern int noninteractive_need_newline;
  extern Lisp_Object echo_area_buffer[2];
@@@ -2764,15 -2767,15 +2800,15 @@@ extern void clear_message (int, int)
  extern void message (const char *, ...) ATTRIBUTE_FORMAT_PRINTF (1, 2);
  extern void message1 (const char *);
  extern void message1_nolog (const char *);
 -extern void message2 (const char *, EMACS_INT, int);
 -extern void message2_nolog (const char *, EMACS_INT, int);
 -extern void message3 (Lisp_Object, EMACS_INT, int);
 -extern void message3_nolog (Lisp_Object, EMACS_INT, int);
 -extern void message_dolog (const char *, EMACS_INT, int, int);
 +extern void message2 (const char *, ptrdiff_t, int);
 +extern void message2_nolog (const char *, ptrdiff_t, int);
 +extern void message3 (Lisp_Object, ptrdiff_t, int);
 +extern void message3_nolog (Lisp_Object, ptrdiff_t, int);
 +extern void message_dolog (const char *, ptrdiff_t, int, int);
  extern void message_with_string (const char *, Lisp_Object, int);
  extern void message_log_maybe_newline (void);
  extern void update_echo_area (void);
 -extern void truncate_echo_area (EMACS_INT);
 +extern void truncate_echo_area (ptrdiff_t);
  extern void redisplay (void);
  extern void redisplay_preserve_echo_area (int);
  extern void prepare_menu_bars (void);
@@@ -2781,14 -2784,14 +2817,14 @@@ void set_frame_cursor_types (struct fra
  extern void syms_of_xdisp (void);
  extern void init_xdisp (void);
  extern Lisp_Object safe_eval (Lisp_Object);
 -extern int pos_visible_p (struct window *, EMACS_INT, int *,
 +extern int pos_visible_p (struct window *, ptrdiff_t, int *,
                            int *, int *, int *, int *, int *);
  
  /* Defined in xsettings.c */
  extern void syms_of_xsettings (void);
  
  /* Defined in vm-limit.c.  */
- extern void memory_warnings (POINTER_TYPE *, void (*warnfun) (const char *));
+ extern void memory_warnings (void *, void (*warnfun) (const char *));
  
  /* Defined in alloc.c */
  extern void check_pure_size (void);
@@@ -2797,7 -2800,7 +2833,7 @@@ extern void reset_malloc_hooks (void)
  extern void uninterrupt_malloc (void);
  extern void malloc_warning (const char *);
  extern void memory_full (size_t) NO_RETURN;
 -extern void buffer_memory_full (EMACS_INT) NO_RETURN;
 +extern void buffer_memory_full (ptrdiff_t) NO_RETURN;
  extern int survives_gc_p (Lisp_Object);
  extern void mark_object (Lisp_Object);
  #if defined REL_ALLOC && !defined SYSTEM_MALLOC
@@@ -2822,26 -2825,26 +2858,26 @@@ EXFUN (Fmake_marker, 0)
  extern void string_overflow (void) NO_RETURN;
  EXFUN (Fmake_string, 2);
  extern Lisp_Object build_string (const char *);
 -extern Lisp_Object make_string (const char *, EMACS_INT);
 -extern Lisp_Object make_unibyte_string (const char *, EMACS_INT);
 -extern Lisp_Object make_multibyte_string (const char *, EMACS_INT, EMACS_INT);
 +extern Lisp_Object make_string (const char *, ptrdiff_t);
 +extern Lisp_Object make_unibyte_string (const char *, ptrdiff_t);
 +extern Lisp_Object make_multibyte_string (const char *, ptrdiff_t, ptrdiff_t);
  extern Lisp_Object make_event_array (int, Lisp_Object *);
  extern Lisp_Object make_uninit_string (EMACS_INT);
  extern Lisp_Object make_uninit_multibyte_string (EMACS_INT, EMACS_INT);
 -extern Lisp_Object make_string_from_bytes (const char *, EMACS_INT, EMACS_INT);
 +extern Lisp_Object make_string_from_bytes (const char *, ptrdiff_t, ptrdiff_t);
  extern Lisp_Object make_specified_string (const char *,
 -                                        EMACS_INT, EMACS_INT, int);
 +                                        ptrdiff_t, ptrdiff_t, int);
  EXFUN (Fpurecopy, 1);
 -extern Lisp_Object make_pure_string (const char *, EMACS_INT, EMACS_INT, int);
 +extern Lisp_Object make_pure_string (const char *, ptrdiff_t, ptrdiff_t, int);
  extern Lisp_Object make_pure_c_string (const char *data);
  extern Lisp_Object pure_cons (Lisp_Object, Lisp_Object);
 -extern Lisp_Object make_pure_vector (EMACS_INT);
 +extern Lisp_Object make_pure_vector (ptrdiff_t);
  EXFUN (Fgarbage_collect, 0);
  EXFUN (Fmake_byte_code, MANY);
  EXFUN (Fmake_bool_vector, 2);
  extern Lisp_Object Qchar_table_extra_slots;
  extern struct Lisp_Vector *allocate_vector (EMACS_INT);
 -extern struct Lisp_Vector *allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag);
 +extern struct Lisp_Vector *allocate_pseudovector (int memlen, int lisplen, int tag);
  #define ALLOCATE_PSEUDOVECTOR(typ,field,tag)                          \
    ((typ*)                                                             \
     allocate_pseudovector                                              \
@@@ -2855,7 -2858,7 +2891,7 @@@ extern int gc_in_progress
  extern int abort_on_gc;
  extern Lisp_Object make_float (double);
  extern void display_malloc_warning (void);
 -extern int inhibit_garbage_collection (void);
 +extern ptrdiff_t inhibit_garbage_collection (void);
  extern Lisp_Object make_save_value (void *, ptrdiff_t);
  extern void free_marker (Lisp_Object);
  extern void free_cons (struct Lisp_Cons *);
@@@ -2947,7 -2950,7 +2983,7 @@@ EXFUN (Fread_event, 3)
  extern Lisp_Object check_obarray (Lisp_Object);
  extern Lisp_Object intern (const char *);
  extern Lisp_Object intern_c_string (const char *);
 -extern Lisp_Object oblookup (Lisp_Object, const char *, EMACS_INT, EMACS_INT);
 +extern Lisp_Object oblookup (Lisp_Object, const char *, ptrdiff_t, ptrdiff_t);
  #define LOADHIST_ATTACH(x) \
    do {                                                                        \
      if (initialized) Vcurrent_load_list = Fcons (x, Vcurrent_load_list); \
@@@ -3024,7 -3027,7 +3060,7 @@@ extern Lisp_Object internal_condition_c
  extern Lisp_Object internal_condition_case_n (Lisp_Object (*) (ptrdiff_t, Lisp_Object *), ptrdiff_t, Lisp_Object *, Lisp_Object, Lisp_Object (*) (Lisp_Object));
  extern void specbind (Lisp_Object, Lisp_Object);
  extern void record_unwind_protect (Lisp_Object (*) (Lisp_Object), Lisp_Object);
 -extern Lisp_Object unbind_to (int, Lisp_Object);
 +extern Lisp_Object unbind_to (ptrdiff_t, Lisp_Object);
  extern void error (const char *, ...) NO_RETURN ATTRIBUTE_FORMAT_PRINTF (1, 2);
  extern void verror (const char *, va_list)
    NO_RETURN ATTRIBUTE_FORMAT_PRINTF (1, 0);
@@@ -3076,9 -3079,10 +3112,9 @@@ EXFUN (Fuser_login_name, 1)
  EXFUN (Fsystem_name, 0);
  EXFUN (Fcurrent_time, 0);
  EXFUN (Fget_internal_run_time, 0);
 -extern EMACS_INT clip_to_bounds (EMACS_INT, EMACS_INT, EMACS_INT);
 -extern Lisp_Object make_buffer_string (EMACS_INT, EMACS_INT, int);
 -extern Lisp_Object make_buffer_string_both (EMACS_INT, EMACS_INT, EMACS_INT,
 -                                          EMACS_INT, int);
 +extern Lisp_Object make_buffer_string (ptrdiff_t, ptrdiff_t, int);
 +extern Lisp_Object make_buffer_string_both (ptrdiff_t, ptrdiff_t, ptrdiff_t,
 +                                          ptrdiff_t, int);
  extern void init_editfns (void);
  const char *get_system_name (void);
  extern void syms_of_editfns (void);
@@@ -3092,12 -3096,12 +3128,12 @@@ extern void nsberror (Lisp_Object) NO_R
  EXFUN (Fset_buffer_multibyte, 1);
  EXFUN (Foverlay_start, 1);
  EXFUN (Foverlay_end, 1);
 -extern void adjust_overlays_for_insert (EMACS_INT, EMACS_INT);
 -extern void adjust_overlays_for_delete (EMACS_INT, EMACS_INT);
 -extern void fix_start_end_in_overlays (EMACS_INT, EMACS_INT);
 +extern void adjust_overlays_for_insert (ptrdiff_t, ptrdiff_t);
 +extern void adjust_overlays_for_delete (ptrdiff_t, ptrdiff_t);
 +extern void fix_start_end_in_overlays (ptrdiff_t, ptrdiff_t);
  extern void report_overlay_modification (Lisp_Object, Lisp_Object, int,
                                           Lisp_Object, Lisp_Object, Lisp_Object);
 -extern int overlay_touches_p (EMACS_INT);
 +extern int overlay_touches_p (ptrdiff_t);
  extern Lisp_Object Vbuffer_alist;
  EXFUN (Fget_buffer, 1);
  EXFUN (Fget_buffer_create, 1);
@@@ -3131,17 -3135,17 +3167,17 @@@ EXFUN (Fmarker_position, 1)
  EXFUN (Fmarker_buffer, 1);
  EXFUN (Fcopy_marker, 2);
  EXFUN (Fset_marker, 3);
 -extern EMACS_INT marker_position (Lisp_Object);
 -extern EMACS_INT marker_byte_position (Lisp_Object);
 +extern ptrdiff_t marker_position (Lisp_Object);
 +extern ptrdiff_t marker_byte_position (Lisp_Object);
  extern void clear_charpos_cache (struct buffer *);
 -extern EMACS_INT charpos_to_bytepos (EMACS_INT);
 -extern EMACS_INT buf_charpos_to_bytepos (struct buffer *, EMACS_INT);
 -extern EMACS_INT buf_bytepos_to_charpos (struct buffer *, EMACS_INT);
 +extern ptrdiff_t charpos_to_bytepos (ptrdiff_t);
 +extern ptrdiff_t buf_charpos_to_bytepos (struct buffer *, ptrdiff_t);
 +extern ptrdiff_t buf_bytepos_to_charpos (struct buffer *, ptrdiff_t);
  extern void unchain_marker (struct Lisp_Marker *marker);
  extern Lisp_Object set_marker_restricted (Lisp_Object, Lisp_Object, Lisp_Object);
 -extern Lisp_Object set_marker_both (Lisp_Object, Lisp_Object, EMACS_INT, EMACS_INT);
 +extern Lisp_Object set_marker_both (Lisp_Object, Lisp_Object, ptrdiff_t, ptrdiff_t);
  extern Lisp_Object set_marker_restricted_both (Lisp_Object, Lisp_Object,
 -                                               EMACS_INT, EMACS_INT);
 +                                               ptrdiff_t, ptrdiff_t);
  extern void syms_of_marker (void);
  
  /* Defined in fileio.c */
@@@ -3190,18 -3194,18 +3226,18 @@@ struct re_registers
  extern struct re_pattern_buffer *compile_pattern (Lisp_Object,
                                                  struct re_registers *,
                                                  Lisp_Object, int, int);
 -extern EMACS_INT fast_string_match (Lisp_Object, Lisp_Object);
 -extern EMACS_INT fast_c_string_match_ignore_case (Lisp_Object, const char *);
 -extern EMACS_INT fast_string_match_ignore_case (Lisp_Object, Lisp_Object);
 -extern EMACS_INT fast_looking_at (Lisp_Object, EMACS_INT, EMACS_INT,
 -                                  EMACS_INT, EMACS_INT, Lisp_Object);
 -extern EMACS_INT scan_buffer (int, EMACS_INT, EMACS_INT, EMACS_INT,
 -                            EMACS_INT *, int);
 -extern EMACS_INT scan_newline (EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT,
 +extern ptrdiff_t fast_string_match (Lisp_Object, Lisp_Object);
 +extern ptrdiff_t fast_c_string_match_ignore_case (Lisp_Object, const char *);
 +extern ptrdiff_t fast_string_match_ignore_case (Lisp_Object, Lisp_Object);
 +extern ptrdiff_t fast_looking_at (Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                                  ptrdiff_t, ptrdiff_t, Lisp_Object);
 +extern ptrdiff_t scan_buffer (int, ptrdiff_t, ptrdiff_t, ptrdiff_t,
 +                            ptrdiff_t *, int);
 +extern EMACS_INT scan_newline (ptrdiff_t, ptrdiff_t, ptrdiff_t, ptrdiff_t,
                               EMACS_INT, int);
 -extern EMACS_INT find_next_newline (EMACS_INT, int);
 -extern EMACS_INT find_next_newline_no_quit (EMACS_INT, EMACS_INT);
 -extern EMACS_INT find_before_next_newline (EMACS_INT, EMACS_INT, EMACS_INT);
 +extern ptrdiff_t find_next_newline (ptrdiff_t, int);
 +extern ptrdiff_t find_next_newline_no_quit (ptrdiff_t, ptrdiff_t);
 +extern ptrdiff_t find_before_next_newline (ptrdiff_t, ptrdiff_t, ptrdiff_t);
  extern void syms_of_search (void);
  extern void clear_regexp_cache (void);
  
@@@ -3287,9 -3291,9 +3323,9 @@@ extern void keys_of_keyboard (void)
  EXFUN (Fvertical_motion, 2);
  EXFUN (Findent_to, 2);
  EXFUN (Fmove_to_column, 2);
 -extern EMACS_INT current_column (void);
 +extern ptrdiff_t current_column (void);
  extern void invalidate_current_column (void);
 -extern int indented_beyond_p (EMACS_INT, EMACS_INT, EMACS_INT);
 +extern int indented_beyond_p (ptrdiff_t, ptrdiff_t, EMACS_INT);
  extern void syms_of_indent (void);
  
  /* Defined in frame.c */
@@@ -3421,12 -3425,12 +3457,12 @@@ extern Lisp_Object Qapply
  extern Lisp_Object Qinhibit_read_only;
  EXFUN (Fundo_boundary, 0);
  extern void truncate_undo_list (struct buffer *);
 -extern void record_marker_adjustment (Lisp_Object, EMACS_INT);
 -extern void record_insert (EMACS_INT, EMACS_INT);
 -extern void record_delete (EMACS_INT, Lisp_Object);
 +extern void record_marker_adjustment (Lisp_Object, ptrdiff_t);
 +extern void record_insert (ptrdiff_t, ptrdiff_t);
 +extern void record_delete (ptrdiff_t, Lisp_Object);
  extern void record_first_change (void);
 -extern void record_change (EMACS_INT, EMACS_INT);
 -extern void record_property_change (EMACS_INT, EMACS_INT,
 +extern void record_change (ptrdiff_t, ptrdiff_t);
 +extern void record_property_change (ptrdiff_t, ptrdiff_t,
                                    Lisp_Object, Lisp_Object,
                                      Lisp_Object);
  extern void syms_of_undo (void);
@@@ -3472,8 -3476,8 +3508,8 @@@ extern void init_sys_modes (struct tty_
  extern void reset_sys_modes (struct tty_display_info *);
  extern void init_all_sys_modes (void);
  extern void reset_all_sys_modes (void);
 -extern void wait_for_termination (int);
 -extern void interruptible_wait_for_termination (int);
 +extern void wait_for_termination (pid_t);
 +extern void interruptible_wait_for_termination (pid_t);
  extern void flush_pending_output (int);
  extern void child_setup_tty (int);
  extern void setup_pty (int);
@@@ -3482,8 -3486,8 +3518,8 @@@ extern EMACS_INT get_random (void)
  extern void seed_random (long);
  extern int emacs_open (const char *, int, int);
  extern int emacs_close (int);
 -extern EMACS_INT emacs_read (int, char *, EMACS_INT);
 -extern EMACS_INT emacs_write (int, const char *, EMACS_INT);
 +extern ptrdiff_t emacs_read (int, char *, ptrdiff_t);
 +extern ptrdiff_t emacs_write (int, const char *, ptrdiff_t);
  enum { READLINK_BUFSIZE = 1024 };
  extern char *emacs_readlink (const char *, char [READLINK_BUFSIZE]);
  
@@@ -3604,9 -3608,9 +3640,9 @@@ extern int initialized
  
  extern int immediate_quit;        /* Nonzero means ^G can quit instantly */
  
- extern POINTER_TYPE *xmalloc (size_t);
- extern POINTER_TYPE *xrealloc (POINTER_TYPE *, size_t);
- extern void xfree (POINTER_TYPE *);
+ extern void *xmalloc (size_t);
+ extern void *xrealloc (void *, size_t);
+ extern void xfree (void *);
  extern void *xnmalloc (ptrdiff_t, ptrdiff_t);
  extern void *xnrealloc (void *, ptrdiff_t, ptrdiff_t);
  extern void *xpalloc (void *, ptrdiff_t *, ptrdiff_t, ptrdiff_t, ptrdiff_t);
@@@ -3710,7 -3714,7 +3746,7 @@@ extern void init_system_name (void)
  extern Lisp_Object safe_alloca_unwind (Lisp_Object);
  
  #define USE_SAFE_ALLOCA                       \
 -  int sa_count = (int) SPECPDL_INDEX (), sa_must_free = 0
 +  ptrdiff_t sa_count = SPECPDL_INDEX (); int sa_must_free = 0
  
  /* SAFE_ALLOCA allocates a simple buffer.  */
  
diff --combined src/lread.c
@@@ -24,7 -24,7 +24,7 @@@ along with GNU Emacs.  If not, see <htt
  #include <sys/stat.h>
  #include <sys/file.h>
  #include <errno.h>
- #include <limits.h>   /* for CHAR_BIT */
+ #include <limits.h>   /* For CHAR_BIT.  */
  #include <setjmp.h>
  #include "lisp.h"
  #include "intervals.h"
@@@ -109,9 -109,9 +109,9 @@@ static FILE *instream
  static int read_pure;
  
  /* For use within read-from-string (this reader is non-reentrant!!)  */
 -static EMACS_INT read_from_string_index;
 -static EMACS_INT read_from_string_index_byte;
 -static EMACS_INT read_from_string_limit;
 +static ptrdiff_t read_from_string_index;
 +static ptrdiff_t read_from_string_index_byte;
 +static ptrdiff_t read_from_string_limit;
  
  /* Number of characters read in the current call to Fread or
     Fread_from_string. */
@@@ -209,7 -209,7 +209,7 @@@ readchar (Lisp_Object readcharfun, int 
      {
        register struct buffer *inbuffer = XBUFFER (readcharfun);
  
 -      EMACS_INT pt_byte = BUF_PT_BYTE (inbuffer);
 +      ptrdiff_t pt_byte = BUF_PT_BYTE (inbuffer);
  
        if (pt_byte >= BUF_ZV_BYTE (inbuffer))
        return -1;
      {
        register struct buffer *inbuffer = XMARKER (readcharfun)->buffer;
  
 -      EMACS_INT bytepos = marker_byte_position (readcharfun);
 +      ptrdiff_t bytepos = marker_byte_position (readcharfun);
  
        if (bytepos >= BUF_ZV_BYTE (inbuffer))
        return -1;
@@@ -372,8 -372,8 +372,8 @@@ unreadchar (Lisp_Object readcharfun, in
    else if (BUFFERP (readcharfun))
      {
        struct buffer *b = XBUFFER (readcharfun);
 -      EMACS_INT charpos = BUF_PT (b);
 -      EMACS_INT bytepos = BUF_PT_BYTE (b);
 +      ptrdiff_t charpos = BUF_PT (b);
 +      ptrdiff_t bytepos = BUF_PT_BYTE (b);
  
        if (! NILP (BVAR (b, enable_multibyte_characters)))
        BUF_DEC_POS (b, bytepos);
    else if (MARKERP (readcharfun))
      {
        struct buffer *b = XMARKER (readcharfun)->buffer;
 -      EMACS_INT bytepos = XMARKER (readcharfun)->bytepos;
 +      ptrdiff_t bytepos = XMARKER (readcharfun)->bytepos;
  
        XMARKER (readcharfun)->charpos--;
        if (! NILP (BVAR (b, enable_multibyte_characters)))
@@@ -608,11 -608,8 +608,11 @@@ read_filtered_event (int no_switch_fram
        int sec, usec;
        double duration = extract_float (seconds);
  
 -      sec  = (int) duration;
 -      usec = (duration - sec) * 1000000;
 +      if (0 < duration)
 +      duration_to_sec_usec (duration, &sec, &usec);
 +      else
 +      sec = usec = 0;
 +
        EMACS_GET_TIME (end_time);
        EMACS_SET_SECS_USECS (wait_time, sec, usec);
        EMACS_ADD_TIME (end_time, end_time, wait_time);
@@@ -1025,7 -1022,7 +1025,7 @@@ Return t if the file exists and loads s
  {
    register FILE *stream;
    register int fd = -1;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3;
    Lisp_Object found, efound, hist_file_name;
    /* 1 means we printed the ".el is newer" message.  */
  openp (Lisp_Object path, Lisp_Object str, Lisp_Object suffixes, Lisp_Object *storeptr, Lisp_Object predicate)
  {
    register int fd;
 -  EMACS_INT fn_size = 100;
 +  ptrdiff_t fn_size = 100;
    char buf[100];
    register char *fn = buf;
    int absolute = 0;
 -  EMACS_INT want_length;
 +  ptrdiff_t want_length;
    Lisp_Object filename;
    struct stat st;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
    Lisp_Object string, tail, encoded_fn;
 -  EMACS_INT max_suffix_len = 0;
 +  ptrdiff_t max_suffix_len = 0;
  
    CHECK_STRING (str);
  
                {
                  /* Check that we can access or open it.  */
                  if (NATNUMP (predicate))
 -                  fd = (access (pfn, XFASTINT (predicate)) == 0) ? 1 : -1;
 +                  fd = (((XFASTINT (predicate) & ~INT_MAX) == 0
 +                         && access (pfn, XFASTINT (predicate)) == 0)
 +                        ? 1 : -1);
                  else
                    fd = emacs_open (pfn, O_RDONLY, 0);
  
@@@ -1700,7 -1695,7 +1700,7 @@@ readevalloop (Lisp_Object readcharfun
  {
    register int c;
    register Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    struct buffer *b = 0;
    int continue_reading_p;
    continue_reading_p = 1;
    while (continue_reading_p)
      {
 -      int count1 = SPECPDL_INDEX ();
 +      ptrdiff_t count1 = SPECPDL_INDEX ();
  
        if (b != 0 && NILP (BVAR (b, name)))
        error ("Reading from killed buffer");
@@@ -1877,7 -1872,7 +1877,7 @@@ DO-ALLOW-PRINT, if non-nil, specifies t
  This function preserves the position of point.  */)
    (Lisp_Object buffer, Lisp_Object printflag, Lisp_Object filename, Lisp_Object unibyte, Lisp_Object do_allow_print)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object tem, buf;
  
    if (NILP (buffer))
@@@ -1922,7 -1917,7 +1922,7 @@@ This function does not move point.  */
    (Lisp_Object start, Lisp_Object end, Lisp_Object printflag, Lisp_Object read_function)
  {
    /* FIXME: Do the eval-sexp-add-defvars dance!  */
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object tem, cbuf;
  
    cbuf = Fcurrent_buffer ();
@@@ -2000,7 -1995,7 +2000,7 @@@ read_internal_start (Lisp_Object stream
    if (STRINGP (stream)
        || ((CONSP (stream) && STRINGP (XCAR (stream)))))
      {
 -      EMACS_INT startval, endval;
 +      ptrdiff_t startval, endval;
        Lisp_Object string;
  
        if (STRINGP (stream))
        else
        {
          CHECK_NUMBER (end);
 -        endval = XINT (end);
 -        if (endval < 0 || endval > SCHARS (string))
 +        if (! (0 <= XINT (end) && XINT (end) <= SCHARS (string)))
            args_out_of_range (string, end);
 +        endval = XINT (end);
        }
  
        if (NILP (start))
        else
        {
          CHECK_NUMBER (start);
 -        startval = XINT (start);
 -        if (startval < 0 || startval > endval)
 +        if (! (0 <= XINT (start) && XINT (start) <= endval))
            args_out_of_range (string, start);
 +        startval = XINT (start);
        }
        read_from_string_index = startval;
        read_from_string_index_byte = string_char_to_byte (string, startval);
@@@ -2503,17 -2498,16 +2503,17 @@@ read1 (register Lisp_Object readcharfun
              if (c == '[')
                {
                  Lisp_Object tmp;
 -                EMACS_INT depth, size;
 +                int depth;
 +                ptrdiff_t size;
  
                  tmp = read_vector (readcharfun, 0);
 -                if (!INTEGERP (AREF (tmp, 0)))
 +                size = ASIZE (tmp);
 +                if (size == 0)
 +                  error ("Invalid size char-table");
 +                if (! RANGED_INTEGERP (1, AREF (tmp, 0), 3))
                    error ("Invalid depth in char-table");
                  depth = XINT (AREF (tmp, 0));
 -                if (depth < 1 || depth > 3)
 -                  error ("Invalid depth in char-table");
 -                size = ASIZE (tmp) - 2;
 -                if (chartab_size [depth] != size)
 +                if (chartab_size[depth] != size - 2)
                    error ("Invalid size char-table");
                  XSETPVECTYPE (XVECTOR (tmp), PVEC_SUB_CHAR_TABLE);
                  return tmp;
          }
        {
          Lisp_Object name, result;
 -        EMACS_INT nbytes = p - read_buffer;
 -        EMACS_INT nchars
 +        ptrdiff_t nbytes = p - read_buffer;
 +        ptrdiff_t nchars
            = (multibyte
               ? multibyte_chars_in_text ((unsigned char *) read_buffer,
                                          nbytes)
@@@ -3894,7 -3888,7 +3894,7 @@@ OBARRAY defaults to the value of the va
     Also store the bucket number in oblookup_last_bucket_number.  */
  
  Lisp_Object
 -oblookup (Lisp_Object obarray, register const char *ptr, EMACS_INT size, EMACS_INT size_byte)
 +oblookup (Lisp_Object obarray, register const char *ptr, ptrdiff_t size, ptrdiff_t size_byte)
  {
    size_t hash;
    size_t obsize;
@@@ -3996,10 -3990,12 +3996,12 @@@ init_obarray (void
    /* XSYMBOL (Qnil)->function = Qunbound; */
    SET_SYMBOL_VAL (XSYMBOL (Qnil), Qnil);
    XSYMBOL (Qnil)->constant = 1;
+   XSYMBOL (Qnil)->declared_special = 1;
    XSYMBOL (Qnil)->plist = Qnil;
  
    Qt = intern_c_string ("t");
    SET_SYMBOL_VAL (XSYMBOL (Qt), Qt);
+   XSYMBOL (Qnil)->declared_special = 1;
    XSYMBOL (Qt)->constant = 1;
  
    /* Qt is correct even if CANNOT_DUMP.  loadup.el will set to nil at end.  */
diff --combined src/print.c
@@@ -55,10 -55,10 +55,10 @@@ static Lisp_Object Qfloat_output_format
  #endif
  
  /* Avoid actual stack overflow in print.  */
 -static int print_depth;
 +static ptrdiff_t print_depth;
  
  /* Level of nesting inside outputting backquote in new style.  */
 -static int new_backquote_output;
 +static ptrdiff_t new_backquote_output;
  
  /* Detect most circularities to print finite output.  */
  #define PRINT_CIRCLE 200
@@@ -69,11 -69,11 +69,11 @@@ static Lisp_Object being_printed[PRINT_
  static char *print_buffer;
  
  /* Size allocated in print_buffer.  */
 -static EMACS_INT print_buffer_size;
 +static ptrdiff_t print_buffer_size;
  /* Chars stored in print_buffer.  */
 -static EMACS_INT print_buffer_pos;
 +static ptrdiff_t print_buffer_pos;
  /* Bytes stored in print_buffer.  */
 -static EMACS_INT print_buffer_pos_byte;
 +static ptrdiff_t print_buffer_pos_byte;
  
  Lisp_Object Qprint_escape_newlines;
  static Lisp_Object Qprint_escape_multibyte, Qprint_escape_nonascii;
@@@ -86,7 -86,7 +86,7 @@@
       N    the object has been printed so we can refer to it as #N#.
     print_number_index holds the largest N already used.
     N has to be striclty larger than 0 since we need to distinguish -N.  */
 -static int print_number_index;
 +static ptrdiff_t print_number_index;
  static void print_interval (INTERVAL interval, Lisp_Object printcharfun);
  
  /* GDB resets this to zero on W32 to disable OutputDebugString calls.  */
@@@ -104,9 -104,9 +104,9 @@@ int print_output_debug_flag EXTERNALLY_
  
  #define PRINTDECLARE                                                  \
     struct buffer *old = current_buffer;                                       \
 -   EMACS_INT old_point = -1, start_point = -1;                                \
 -   EMACS_INT old_point_byte = -1, start_point_byte = -1;              \
 -   int specpdl_count = SPECPDL_INDEX ();                              \
 +   ptrdiff_t old_point = -1, start_point = -1;                                \
 +   ptrdiff_t old_point_byte = -1, start_point_byte = -1;              \
 +   ptrdiff_t specpdl_count = SPECPDL_INDEX ();                                \
     int free_print_buffer = 0;                                         \
     int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));        \
     Lisp_Object original
       }                                                                        \
     if (MARKERP (printcharfun))                                                \
       {                                                                        \
 -       EMACS_INT marker_pos;                                          \
 +       ptrdiff_t marker_pos;                                          \
         if (! XMARKER (printcharfun)->buffer)                          \
           error ("Marker does not point anywhere");                    \
         if (XMARKER (printcharfun)->buffer != current_buffer)          \
         }                                                              \
         else                                                           \
         {                                                              \
 -         ptrdiff_t new_size = 1000;                                   \
 +         int new_size = 1000;                                         \
           print_buffer = (char *) xmalloc (new_size);                  \
           print_buffer_size = new_size;                                \
           free_print_buffer = 1;                                       \
@@@ -233,10 -233,15 +233,10 @@@ printchar (unsigned int ch, Lisp_Objec
  
        if (NILP (fun))
        {
 -        if (print_buffer_size - len <= print_buffer_pos_byte)
 -          {
 -            ptrdiff_t new_size;
 -            if (STRING_BYTES_BOUND / 2 < print_buffer_size)
 -              string_overflow ();
 -            new_size = print_buffer_size * 2;
 -            print_buffer = (char *) xrealloc (print_buffer, new_size);
 -            print_buffer_size = new_size;
 -          }
 +        ptrdiff_t incr = len - (print_buffer_size - print_buffer_pos_byte);
 +        if (0 < incr)
 +          print_buffer =
 +            xpalloc (print_buffer, &print_buffer_size, incr, -1, 1);
          memcpy (print_buffer + print_buffer_pos_byte, str, len);
          print_buffer_pos += 1;
          print_buffer_pos_byte += len;
     to data in a Lisp string.  Otherwise that is not safe.  */
  
  static void
 -strout (const char *ptr, EMACS_INT size, EMACS_INT size_byte,
 +strout (const char *ptr, ptrdiff_t size, ptrdiff_t size_byte,
        Lisp_Object printcharfun)
  {
    if (size < 0)
  
    if (NILP (printcharfun))
      {
 -      if (print_buffer_size - size_byte < print_buffer_pos_byte)
 -      {
 -        ptrdiff_t new_size;
 -        if (STRING_BYTES_BOUND / 2 - size_byte < print_buffer_size)
 -          string_overflow ();
 -        new_size = print_buffer_size * 2 + size_byte;
 -        print_buffer = (char *) xrealloc (print_buffer, new_size);
 -        print_buffer_size = new_size;
 -      }
 +      ptrdiff_t incr = size_byte - (print_buffer_size - print_buffer_pos_byte);
 +      if (0 < incr)
 +      print_buffer = xpalloc (print_buffer, &print_buffer_size, incr, -1, 1);
        memcpy (print_buffer + print_buffer_pos_byte, ptr, size_byte);
        print_buffer_pos += size;
        print_buffer_pos_byte += size_byte;
    else
      {
        /* PRINTCHARFUN is a Lisp function.  */
 -      EMACS_INT i = 0;
 +      ptrdiff_t i = 0;
  
        if (size == size_byte)
        {
@@@ -358,7 -369,7 +358,7 @@@ print_string (Lisp_Object string, Lisp_
  {
    if (EQ (printcharfun, Qt) || NILP (printcharfun))
      {
 -      EMACS_INT chars;
 +      ptrdiff_t chars;
  
        if (print_escape_nonascii)
        string = string_escape_byte8 (string);
             convert STRING to a multibyte string containing the same
             character codes.  */
          Lisp_Object newstr;
 -        EMACS_INT bytes;
 +        ptrdiff_t bytes;
  
          chars = SBYTES (string);
          bytes = count_size_as_multibyte (SDATA (string), chars);
        if (EQ (printcharfun, Qt))
        {
          /* Output to echo area.  */
 -        EMACS_INT nbytes = SBYTES (string);
 +        ptrdiff_t nbytes = SBYTES (string);
          char *buffer;
  
          /* Copy the string contents so that relocation of STRING by
      {
        /* Otherwise, string may be relocated by printing one char.
         So re-fetch the string address for each character.  */
 -      EMACS_INT i;
 -      EMACS_INT size = SCHARS (string);
 -      EMACS_INT size_byte = SBYTES (string);
 +      ptrdiff_t i;
 +      ptrdiff_t size = SCHARS (string);
 +      ptrdiff_t size_byte = SBYTES (string);
        struct gcpro gcpro1;
        GCPRO1 (string);
        if (size == size_byte)
@@@ -487,7 -498,7 +487,7 @@@ write_string_1 (const char *data, int s
  void
  temp_output_buffer_setup (const char *bufname)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    register struct buffer *old = current_buffer;
    register Lisp_Object buf;
  
@@@ -591,7 -602,7 +591,7 @@@ A printed representation of an object i
    Lisp_Object printcharfun;
    /* struct gcpro gcpro1, gcpro2; */
    Lisp_Object save_deactivate_mark;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct buffer *previous;
  
    specbind (Qinhibit_modification_hooks, Qt);
@@@ -717,7 -728,7 +717,7 @@@ to make it write to the debugging outpu
    (Lisp_Object character)
  {
    CHECK_NUMBER (character);
 -  putc ((int) XINT (character), stderr);
 +  putc (XINT (character) & 0xFF, stderr);
  
  #ifdef WINDOWSNT
    /* Send the output to a debugger (nothing happens if there isn't one).  */
@@@ -854,7 -865,6 +854,6 @@@ print_error_message (Lisp_Object data, 
  {
    Lisp_Object errname, errmsg, file_error, tail;
    struct gcpro gcpro1;
-   int i;
  
    if (context != 0)
      write_string_1 (context, -1, stream);
    if (!NILP (caller) && SYMBOLP (caller))
      {
        Lisp_Object cname = SYMBOL_NAME (caller);
 -      char *name = alloca (SBYTES (cname));
 +      char *name;
 +      USE_SAFE_ALLOCA;
 +      SAFE_ALLOCA (name, char *, SBYTES (cname));
        memcpy (name, SDATA (cname), SBYTES (cname));
        message_dolog (name, SBYTES (cname), 0, 0);
        message_dolog (": ", 2, 0, 0);
 +      SAFE_FREE ();
      }
  
    errname = Fcar (data);
      }
    else
      {
-       Lisp_Object error_conditions;
+       Lisp_Object error_conditions = Fget (errname, Qerror_conditions);
        errmsg = Fget (errname, Qerror_message);
-       error_conditions = Fget (errname, Qerror_conditions);
        file_error = Fmemq (Qfile_error, error_conditions);
      }
  
    if (!NILP (file_error) && CONSP (tail))
      errmsg = XCAR (tail), tail = XCDR (tail);
  
-   if (STRINGP (errmsg))
-     Fprinc (errmsg, stream);
-   else
-     write_string_1 ("peculiar error", -1, stream);
-   for (i = 0; CONSP (tail); tail = XCDR (tail), i = 1)
-     {
-       Lisp_Object obj;
-       write_string_1 (i ? ", " : ": ", 2, stream);
-       obj = XCAR (tail);
-       if (!NILP (file_error) || EQ (errname, Qend_of_file))
-       Fprinc (obj, stream);
-       else
-       Fprin1 (obj, stream);
-     }
+   {
+     const char *sep = ": ";
+     if (!STRINGP (errmsg))
+       write_string_1 ("peculiar error", -1, stream);
+     else if (SCHARS (errmsg))
+       Fprinc (errmsg, stream);
+     else
+       sep = NULL;
+     for (; CONSP (tail); tail = XCDR (tail), sep = ", ")
+       {
+       Lisp_Object obj;
+       
+       if (sep)
+         write_string_1 (sep, 2, stream);
+       obj = XCAR (tail);
+       if (!NILP (file_error)
+           || EQ (errname, Qend_of_file) || EQ (errname, Quser_error))
+         Fprinc (obj, stream);
+       else
+         Fprin1 (obj, stream);
+       }
+   }
  
    UNGCPRO;
  }
@@@ -1084,7 -1098,7 +1090,7 @@@ print (Lisp_Object obj, register Lisp_O
             Maybe a better way to do that is to copy elements to
             a new hash table.  */
          struct Lisp_Hash_Table *h = XHASH_TABLE (Vprint_number_table);
 -        EMACS_INT i;
 +        ptrdiff_t i;
  
          for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
            if (!NILP (HASH_HASH (h, i))
@@@ -1118,7 -1132,7 +1124,7 @@@ static voi
  print_preprocess (Lisp_Object obj)
  {
    int i;
 -  EMACS_INT size;
 +  ptrdiff_t size;
    int loop_count = 0;
    Lisp_Object halftail;
  
@@@ -1261,8 -1275,8 +1267,8 @@@ print_check_string_charset_prop (INTERV
        || ! (print_check_string_result & PRINT_STRING_UNSAFE_CHARSET_FOUND))
      {
        int i, c;
 -      EMACS_INT charpos = interval->position;
 -      EMACS_INT bytepos = string_char_to_byte (string, charpos);
 +      ptrdiff_t charpos = interval->position;
 +      ptrdiff_t bytepos = string_char_to_byte (string, charpos);
        Lisp_Object charset;
  
        charset = XCAR (XCDR (val));
@@@ -1382,10 -1396,10 +1388,10 @@@ print_object (Lisp_Object obj, registe
        print_string (obj, printcharfun);
        else
        {
 -        register EMACS_INT i_byte;
 +        register ptrdiff_t i_byte;
          struct gcpro gcpro1;
          unsigned char *str;
 -        EMACS_INT size_byte;
 +        ptrdiff_t size_byte;
          /* 1 means we must ensure that the next character we output
             cannot be taken as part of a hex character escape.  */
          int need_nonhex = 0;
        register unsigned char *p = SDATA (SYMBOL_NAME (obj));
        register unsigned char *end = p + SBYTES (SYMBOL_NAME (obj));
        register int c;
 -      int i, i_byte;
 -      EMACS_INT size_byte;
 +      ptrdiff_t i, i_byte;
 +      ptrdiff_t size_byte;
        Lisp_Object name;
  
        name = SYMBOL_NAME (obj);
          ptrdiff_t i;
          register unsigned char c;
          struct gcpro gcpro1;
 -        EMACS_INT size_in_chars
 +        ptrdiff_t size_in_chars
            = ((XBOOL_VECTOR (obj)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
               / BOOL_VECTOR_BITS_PER_CHAR);
  
        else if (HASH_TABLE_P (obj))
        {
          struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
 -        int i;
 -        EMACS_INT real_size, size;
 +        ptrdiff_t i;
 +        ptrdiff_t real_size, size;
  #if 0
          strout ("#<hash-table", -1, -1, printcharfun);
          if (SYMBOLP (h->test))
              PRINTCHAR (' ');
              strout (SDATA (SYMBOL_NAME (h->weak)), -1, -1, printcharfun);
              PRINTCHAR (' ');
 -            sprintf (buf, "%"pI"d/%"pI"d", h->count, ASIZE (h->next));
 +            sprintf (buf, "%"pD"d/%"pD"d", h->count, ASIZE (h->next));
              strout (buf, -1, -1, printcharfun);
            }
          sprintf (buf, " %p", h);
          /* Implement a readable output, e.g.:
            #s(hash-table size 2 test equal data (k1 v1 k2 v2)) */
          /* Always print the size. */
 -        sprintf (buf, "#s(hash-table size %"pI"d", ASIZE (h->next));
 +        sprintf (buf, "#s(hash-table size %"pD"d", ASIZE (h->next));
          strout (buf, -1, -1, printcharfun);
  
          if (!NILP (h->test))
        }
        else if (FONTP (obj))
        {
 -        EMACS_INT i;
 +        int i;
  
          if (! FONT_OBJECT_P (obj))
            {
        }
        else
        {
 -        EMACS_INT size = ASIZE (obj);
 +        ptrdiff_t size = ASIZE (obj);
          if (COMPILEDP (obj))
            {
              PRINTCHAR ('#');
          {
            register int i;
            register Lisp_Object tem;
 -          EMACS_INT real_size = size;
 +          ptrdiff_t real_size = size;
  
            /* Don't print more elements than the specified maximum.  */
            if (NATNUMP (Vprint_length)
            strout ("in no buffer", -1, -1, printcharfun);
          else
            {
 -            sprintf (buf, "at %"pI"d", marker_position (obj));
 +            sprintf (buf, "at %"pD"d", marker_position (obj));
              strout (buf, -1, -1, printcharfun);
              strout (" in ", -1, -1, printcharfun);
              print_string (BVAR (XMARKER (obj)->buffer, name), printcharfun);
            strout ("in no buffer", -1, -1, printcharfun);
          else
            {
 -            sprintf (buf, "from %"pI"d to %"pI"d in ",
 +            sprintf (buf, "from %"pD"d to %"pD"d in ",
                       marker_position (OVERLAY_START (obj)),
                       marker_position (OVERLAY_END   (obj)));
              strout (buf, -1, -1, printcharfun);
        if (MISCP (obj))
          sprintf (buf, "(MISC 0x%04x)", (int) XMISCTYPE (obj));
        else if (VECTORLIKEP (obj))
 -        sprintf (buf, "(PVEC 0x%08"pI"x)", ASIZE (obj));
 +        sprintf (buf, "(PVEC 0x%08"pD"x)", ASIZE (obj));
        else
          sprintf (buf, "(0x%02x)", (int) XTYPE (obj));
        strout (buf, -1, -1, printcharfun);
diff --combined src/puresize.h
@@@ -45,13 -45,9 +45,13 @@@ along with GNU Emacs.  If not, see <htt
  
  /* Increase BASE_PURESIZE by a ratio depending on the machine's word size.  */
  #ifndef PURESIZE_RATIO
- #if BITS_PER_EMACS_INT > 32
+ #if EMACS_INT_MAX >> 31 != 0
 +#if PTRDIFF_MAX >> 31 != 0
  #define PURESIZE_RATIO 10/6   /* Don't surround with `()'. */
  #else
 +#define PURESIZE_RATIO 8/6    /* Don't surround with `()'. */
 +#endif
 +#else
  #define PURESIZE_RATIO 1
  #endif
  #endif
diff --combined src/search.c
@@@ -90,16 -90,16 +90,16 @@@ static Lisp_Object Qinvalid_regexp
  /* Error condition used for failing searches.  */
  static Lisp_Object Qsearch_failed;
  
 -static void set_search_regs (EMACS_INT, EMACS_INT);
 +static void set_search_regs (ptrdiff_t, ptrdiff_t);
  static void save_search_regs (void);
 -static EMACS_INT simple_search (EMACS_INT, unsigned char *, EMACS_INT,
 -                              EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT,
 -                                EMACS_INT, EMACS_INT);
 -static EMACS_INT boyer_moore (EMACS_INT, unsigned char *, EMACS_INT,
 -                              Lisp_Object, Lisp_Object, EMACS_INT,
 -                              EMACS_INT, int);
 -static EMACS_INT search_buffer (Lisp_Object, EMACS_INT, EMACS_INT,
 -                                EMACS_INT, EMACS_INT, EMACS_INT, int,
 +static EMACS_INT simple_search (EMACS_INT, unsigned char *, ptrdiff_t,
 +                              ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                                ptrdiff_t, ptrdiff_t);
 +static EMACS_INT boyer_moore (EMACS_INT, unsigned char *, ptrdiff_t,
 +                              Lisp_Object, Lisp_Object, ptrdiff_t,
 +                              ptrdiff_t, int);
 +static EMACS_INT search_buffer (Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                                ptrdiff_t, ptrdiff_t, EMACS_INT, int,
                                  Lisp_Object, Lisp_Object, int);
  static void matcher_overflow (void) NO_RETURN;
  
@@@ -272,8 -272,8 +272,8 @@@ looking_at_1 (Lisp_Object string, int p
  {
    Lisp_Object val;
    unsigned char *p1, *p2;
 -  EMACS_INT s1, s2;
 -  register EMACS_INT i;
 +  ptrdiff_t s1, s2;
 +  register ptrdiff_t i;
    struct re_pattern_buffer *bufp;
  
    if (running_asynch_code)
@@@ -368,10 -368,10 +368,10 @@@ data if you want to preserve them.  */
  static Lisp_Object
  string_match_1 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start, int posix)
  {
 -  EMACS_INT val;
 +  ptrdiff_t val;
    struct re_pattern_buffer *bufp;
 -  EMACS_INT pos, pos_byte;
 -  int i;
 +  EMACS_INT pos;
 +  ptrdiff_t pos_byte, i;
  
    if (running_asynch_code)
      save_search_regs ();
      pos = 0, pos_byte = 0;
    else
      {
 -      EMACS_INT len = SCHARS (string);
 +      ptrdiff_t len = SCHARS (string);
  
        CHECK_NUMBER (start);
        pos = XINT (start);
@@@ -468,10 -468,10 +468,10 @@@ matched by parenthesis constructs in th
     and return the index of the match, or negative on failure.
     This does not clobber the match data.  */
  
 -EMACS_INT
 +ptrdiff_t
  fast_string_match (Lisp_Object regexp, Lisp_Object string)
  {
 -  EMACS_INT val;
 +  ptrdiff_t val;
    struct re_pattern_buffer *bufp;
  
    bufp = compile_pattern (regexp, 0, Qnil,
     This does not clobber the match data.
     We assume that STRING contains single-byte characters.  */
  
 -EMACS_INT
 +ptrdiff_t
  fast_c_string_match_ignore_case (Lisp_Object regexp, const char *string)
  {
 -  EMACS_INT val;
 +  ptrdiff_t val;
    struct re_pattern_buffer *bufp;
    size_t len = strlen (string);
  
  
  /* Like fast_string_match but ignore case.  */
  
 -EMACS_INT
 +ptrdiff_t
  fast_string_match_ignore_case (Lisp_Object regexp, Lisp_Object string)
  {
 -  EMACS_INT val;
 +  ptrdiff_t val;
    struct re_pattern_buffer *bufp;
  
    bufp = compile_pattern (regexp, 0, Vascii_canon_table,
     indices into the string.  This function doesn't modify the match
     data.  */
  
 -EMACS_INT
 -fast_looking_at (Lisp_Object regexp, EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT limit, EMACS_INT limit_byte, Lisp_Object string)
 +ptrdiff_t
 +fast_looking_at (Lisp_Object regexp, ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t limit, ptrdiff_t limit_byte, Lisp_Object string)
  {
    int multibyte;
    struct re_pattern_buffer *buf;
    unsigned char *p1, *p2;
 -  EMACS_INT s1, s2;
 -  EMACS_INT len;
 +  ptrdiff_t s1, s2;
 +  ptrdiff_t len;
  
    if (STRINGP (string))
      {
@@@ -641,9 -641,9 +641,9 @@@ newline_cache_on_off (struct buffer *bu
     If ALLOW_QUIT is non-zero, set immediate_quit.  That's good to do
     except when inside redisplay.  */
  
 -EMACS_INT
 -scan_buffer (register int target, EMACS_INT start, EMACS_INT end,
 -           EMACS_INT count, EMACS_INT *shortage, int allow_quit)
 +ptrdiff_t
 +scan_buffer (register int target, ptrdiff_t start, ptrdiff_t end,
 +           ptrdiff_t count, ptrdiff_t *shortage, int allow_quit)
  {
    struct region_cache *newline_cache;
    int direction;
             the position of the last character before the next such
             obstacle --- the last character the dumb search loop should
             examine.  */
 -      EMACS_INT ceiling_byte = CHAR_TO_BYTE (end) - 1;
 -      EMACS_INT start_byte = CHAR_TO_BYTE (start);
 -      EMACS_INT tem;
 +      ptrdiff_t ceiling_byte = CHAR_TO_BYTE (end) - 1;
 +      ptrdiff_t start_byte = CHAR_TO_BYTE (start);
 +      ptrdiff_t tem;
  
          /* If we're looking for a newline, consult the newline cache
             to see where we can avoid some scanning.  */
      while (start > end)
        {
          /* The last character to check before the next obstacle.  */
 -      EMACS_INT ceiling_byte = CHAR_TO_BYTE (end);
 -      EMACS_INT start_byte = CHAR_TO_BYTE (start);
 -      EMACS_INT tem;
 +      ptrdiff_t ceiling_byte = CHAR_TO_BYTE (end);
 +      ptrdiff_t start_byte = CHAR_TO_BYTE (start);
 +      ptrdiff_t tem;
  
          /* Consult the newline cache, if appropriate.  */
          if (target == '\n' && newline_cache)
     except in special cases.  */
  
  EMACS_INT
 -scan_newline (EMACS_INT start, EMACS_INT start_byte,
 -            EMACS_INT limit, EMACS_INT limit_byte,
 +scan_newline (ptrdiff_t start, ptrdiff_t start_byte,
 +            ptrdiff_t limit, ptrdiff_t limit_byte,
              register EMACS_INT count, int allow_quit)
  {
    int direction = ((count > 0) ? 1 : -1);
    register unsigned char *cursor;
    unsigned char *base;
  
 -  EMACS_INT ceiling;
 +  ptrdiff_t ceiling;
    register unsigned char *ceiling_addr;
  
    int old_immediate_quit = immediate_quit;
    return count * direction;
  }
  
 -EMACS_INT
 -find_next_newline_no_quit (EMACS_INT from, EMACS_INT cnt)
 +ptrdiff_t
 +find_next_newline_no_quit (ptrdiff_t from, ptrdiff_t cnt)
  {
 -  return scan_buffer ('\n', from, 0, cnt, (EMACS_INT *) 0, 0);
 +  return scan_buffer ('\n', from, 0, cnt, (ptrdiff_t *) 0, 0);
  }
  
  /* Like find_next_newline, but returns position before the newline,
     not after, and only search up to TO.  This isn't just
     find_next_newline (...)-1, because you might hit TO.  */
  
 -EMACS_INT
 -find_before_next_newline (EMACS_INT from, EMACS_INT to, EMACS_INT cnt)
 +ptrdiff_t
 +find_before_next_newline (ptrdiff_t from, ptrdiff_t to, ptrdiff_t cnt)
  {
 -  EMACS_INT shortage;
 -  EMACS_INT pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
 +  ptrdiff_t shortage;
 +  ptrdiff_t pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
  
    if (shortage == 0)
      pos--;
@@@ -959,8 -959,7 +959,8 @@@ search_command (Lisp_Object string, Lis
                Lisp_Object count, int direction, int RE, int posix)
  {
    register EMACS_INT np;
 -  EMACS_INT lim, lim_byte;
 +  EMACS_INT lim;
 +  ptrdiff_t lim_byte;
    EMACS_INT n = direction;
  
    if (!NILP (count))
  static int
  trivial_regexp_p (Lisp_Object regexp)
  {
 -  EMACS_INT len = SBYTES (regexp);
 +  ptrdiff_t len = SBYTES (regexp);
    unsigned char *s = SDATA (regexp);
    while (--len >= 0)
      {
@@@ -1100,13 -1099,13 +1100,13 @@@ while (0
  static struct re_registers search_regs_1;
  
  static EMACS_INT
 -search_buffer (Lisp_Object string, EMACS_INT pos, EMACS_INT pos_byte,
 -             EMACS_INT lim, EMACS_INT lim_byte, EMACS_INT n,
 +search_buffer (Lisp_Object string, ptrdiff_t pos, ptrdiff_t pos_byte,
 +             ptrdiff_t lim, ptrdiff_t lim_byte, EMACS_INT n,
               int RE, Lisp_Object trt, Lisp_Object inverse_trt, int posix)
  {
 -  EMACS_INT len = SCHARS (string);
 -  EMACS_INT len_byte = SBYTES (string);
 -  register int i;
 +  ptrdiff_t len = SCHARS (string);
 +  ptrdiff_t len_byte = SBYTES (string);
 +  register ptrdiff_t i;
  
    if (running_asynch_code)
      save_search_regs ();
    if (RE && !(trivial_regexp_p (string) && NILP (Vsearch_spaces_regexp)))
      {
        unsigned char *p1, *p2;
 -      EMACS_INT s1, s2;
 +      ptrdiff_t s1, s2;
        struct re_pattern_buffer *bufp;
  
        bufp = compile_pattern (string,
  
        while (n < 0)
        {
 -        EMACS_INT val;
 +        ptrdiff_t val;
          val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
                             pos_byte - BEGV_BYTE, lim_byte - pos_byte,
                             (NILP (Vinhibit_changing_match_data)
        }
        while (n > 0)
        {
 -        EMACS_INT val;
 +        ptrdiff_t val;
          val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
                             pos_byte - BEGV_BYTE, lim_byte - pos_byte,
                             (NILP (Vinhibit_changing_match_data)
    else                                /* non-RE case */
      {
        unsigned char *raw_pattern, *pat;
 -      EMACS_INT raw_pattern_size;
 -      EMACS_INT raw_pattern_size_byte;
 +      ptrdiff_t raw_pattern_size;
 +      ptrdiff_t raw_pattern_size_byte;
        unsigned char *patbuf;
        int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
        unsigned char *base_pat;
  
  static EMACS_INT
  simple_search (EMACS_INT n, unsigned char *pat,
 -             EMACS_INT len, EMACS_INT len_byte, Lisp_Object trt,
 -             EMACS_INT pos, EMACS_INT pos_byte,
 -             EMACS_INT lim, EMACS_INT lim_byte)
 +             ptrdiff_t len, ptrdiff_t len_byte, Lisp_Object trt,
 +             ptrdiff_t pos, ptrdiff_t pos_byte,
 +             ptrdiff_t lim, ptrdiff_t lim_byte)
  {
    int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
    int forward = n > 0;
    /* Number of buffer bytes matched.  Note that this may be different
       from len_byte in a multibyte buffer.  */
 -  EMACS_INT match_byte;
 +  ptrdiff_t match_byte;
  
    if (lim > pos && multibyte)
      while (n > 0)
        while (1)
          {
            /* Try matching at position POS.  */
 -          EMACS_INT this_pos = pos;
 -          EMACS_INT this_pos_byte = pos_byte;
 -          EMACS_INT this_len = len;
 +          ptrdiff_t this_pos = pos;
 +          ptrdiff_t this_pos_byte = pos_byte;
 +          ptrdiff_t this_len = len;
            unsigned char *p = pat;
            if (pos + len > lim || pos_byte + len_byte > lim_byte)
              goto stop;
        while (1)
          {
            /* Try matching at position POS.  */
 -          EMACS_INT this_pos = pos;
 -          EMACS_INT this_len = len;
 +          ptrdiff_t this_pos = pos;
 +          ptrdiff_t this_len = len;
            unsigned char *p = pat;
  
            if (pos + len > lim)
        while (1)
          {
            /* Try matching at position POS.  */
 -          EMACS_INT this_pos = pos;
 -          EMACS_INT this_pos_byte = pos_byte;
 -          EMACS_INT this_len = len;
 +          ptrdiff_t this_pos = pos;
 +          ptrdiff_t this_pos_byte = pos_byte;
 +          ptrdiff_t this_len = len;
            const unsigned char *p = pat + len_byte;
  
            if (this_pos - len < lim || (pos_byte - len_byte) < lim_byte)
        while (1)
          {
            /* Try matching at position POS.  */
 -          EMACS_INT this_pos = pos - len;
 -          EMACS_INT this_len = len;
 +          ptrdiff_t this_pos = pos - len;
 +          ptrdiff_t this_len = len;
            unsigned char *p = pat;
  
            if (this_pos < lim)
  
  static EMACS_INT
  boyer_moore (EMACS_INT n, unsigned char *base_pat,
 -           EMACS_INT len_byte,
 +           ptrdiff_t len_byte,
             Lisp_Object trt, Lisp_Object inverse_trt,
 -           EMACS_INT pos_byte, EMACS_INT lim_byte,
 +           ptrdiff_t pos_byte, ptrdiff_t lim_byte,
               int char_base)
  {
    int direction = ((n > 0) ? 1 : -1);
 -  register EMACS_INT dirlen;
 -  EMACS_INT limit;
 +  register ptrdiff_t dirlen;
 +  ptrdiff_t limit;
    int stride_for_teases = 0;
    int BM_tab[0400];
    register unsigned char *cursor, *p_limit;
 -  register EMACS_INT i;
 +  register ptrdiff_t i;
    register int j;
    unsigned char *pat, *pat_end;
    int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
       char if reverse) of pattern would align in a possible match.  */
    while (n != 0)
      {
 -      EMACS_INT tail_end;
 +      ptrdiff_t tail_end;
        unsigned char *tail_end_ptr;
  
        /* It's been reported that some (broken) compiler thinks that
              cursor += dirlen - i - direction; /* fix cursor */
              if (i + direction == 0)
                {
 -                EMACS_INT position, start, end;
 +                ptrdiff_t position, start, end;
  
                  cursor -= direction;
  
              pos_byte += dirlen - i - direction;
              if (i + direction == 0)
                {
 -                EMACS_INT position, start, end;
 +                ptrdiff_t position, start, end;
                  pos_byte -= direction;
  
                  position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
     Also clear out the match data for registers 1 and up.  */
  
  static void
 -set_search_regs (EMACS_INT beg_byte, EMACS_INT nbytes)
 +set_search_regs (ptrdiff_t beg_byte, ptrdiff_t nbytes)
  {
 -  int i;
 +  ptrdiff_t i;
  
    if (!NILP (Vinhibit_changing_match_data))
      return;
    XSETBUFFER (last_thing_searched, current_buffer);
  }
  \f
- DEFUN ("word-search-regexp", Fword_search_regexp, Sword_search_regexp, 1, 2, 0,
-        doc: /* Return a regexp which matches words, ignoring punctuation.
- Given STRING, a string of words separated by word delimiters,
- compute a regexp that matches those exact words separated by
- arbitrary punctuation.  If LAX is non-nil, the end of the string
- need not match a word boundary unless it ends in whitespace.
- Used in `word-search-forward', `word-search-backward',
- `word-search-forward-lax', `word-search-backward-lax'.  */)
-   (Lisp_Object string, Lisp_Object lax)
- {
-   register unsigned char *o;
-   register ptrdiff_t i, i_byte, len, punct_count = 0, word_count = 0;
-   Lisp_Object val;
-   int prev_c = 0;
-   EMACS_INT adjust;
-   int whitespace_at_end;
-   CHECK_STRING (string);
-   len = SCHARS (string);
-   for (i = 0, i_byte = 0; i < len; )
-     {
-       int c;
-       FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
-       if (SYNTAX (c) != Sword)
-       {
-         punct_count++;
-         if (SYNTAX (prev_c) == Sword)
-           word_count++;
-       }
-       prev_c = c;
-     }
-   if (SYNTAX (prev_c) == Sword)
-     {
-       word_count++;
-       whitespace_at_end = 0;
-     }
-   else
-     {
-       whitespace_at_end = 1;
-       if (!word_count)
-       return empty_unibyte_string;
-     }
-   adjust = word_count - 1;
-   if (TYPE_MAXIMUM (EMACS_INT) / 5 < adjust)
-     memory_full (SIZE_MAX);
-   adjust = - punct_count + 5 * adjust
-     + ((!NILP (lax) && !whitespace_at_end) ? 2 : 4);
-   if (STRING_MULTIBYTE (string))
-     {
-       if (INT_ADD_OVERFLOW (SBYTES (string), adjust))
-       memory_full (SIZE_MAX);
-       val = make_uninit_multibyte_string (len + adjust,
-                                         SBYTES (string) + adjust);
-     }
-   else
-     {
-       if (INT_ADD_OVERFLOW (len, adjust))
-       memory_full (SIZE_MAX);
-       val = make_uninit_string (len + adjust);
-     }
-   o = SDATA (val);
-   *o++ = '\\';
-   *o++ = 'b';
-   prev_c = 0;
-   for (i = 0, i_byte = 0; i < len; )
-     {
-       int c;
-       ptrdiff_t i_byte_orig = i_byte;
-       FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
-       if (SYNTAX (c) == Sword)
-       {
-         memcpy (o, SDATA (string) + i_byte_orig, i_byte - i_byte_orig);
-         o += i_byte - i_byte_orig;
-       }
-       else if (SYNTAX (prev_c) == Sword && --word_count)
-       {
-         *o++ = '\\';
-         *o++ = 'W';
-         *o++ = '\\';
-         *o++ = 'W';
-         *o++ = '*';
-       }
-       prev_c = c;
-     }
-   if (NILP (lax) || whitespace_at_end)
-     {
-       *o++ = '\\';
-       *o++ = 'b';
-     }
-   return val;
- }
\f
  DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
         "MSearch backward: ",
         doc: /* Search backward from point for STRING.
@@@ -2227,86 -2120,6 +2121,6 @@@ See also the functions `match-beginning
    return search_command (string, bound, noerror, count, 1, 0, 0);
  }
  
- DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
-        "sWord search backward: ",
-        doc: /* Search backward from point for STRING, ignoring differences in punctuation.
- Set point to the beginning of the occurrence found, and return point.
- An optional second argument bounds the search; it is a buffer position.
- The match found must not extend before that position.
- Optional third argument, if t, means if fail just return nil (no error).
-   If not nil and not t, move to limit of search and return nil.
- Optional fourth argument is repeat count--search for successive occurrences.
- Relies on the function `word-search-regexp' to convert a sequence
- of words in STRING to a regexp used to search words without regard
- to punctuation.  */)
-   (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
- {
-   return search_command (Fword_search_regexp (string, Qnil), bound, noerror, count, -1, 1, 0);
- }
- DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
-        "sWord search: ",
-        doc: /* Search forward from point for STRING, ignoring differences in punctuation.
- Set point to the end of the occurrence found, and return point.
- An optional second argument bounds the search; it is a buffer position.
- The match found must not extend after that position.
- Optional third argument, if t, means if fail just return nil (no error).
-   If not nil and not t, move to limit of search and return nil.
- Optional fourth argument is repeat count--search for successive occurrences.
- Relies on the function `word-search-regexp' to convert a sequence
- of words in STRING to a regexp used to search words without regard
- to punctuation.  */)
-   (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
- {
-   return search_command (Fword_search_regexp (string, Qnil), bound, noerror, count, 1, 1, 0);
- }
- DEFUN ("word-search-backward-lax", Fword_search_backward_lax, Sword_search_backward_lax, 1, 4,
-        "sWord search backward: ",
-        doc: /* Search backward from point for STRING, ignoring differences in punctuation.
- Set point to the beginning of the occurrence found, and return point.
- Unlike `word-search-backward', the end of STRING need not match a word
- boundary, unless STRING ends in whitespace.
- An optional second argument bounds the search; it is a buffer position.
- The match found must not extend before that position.
- Optional third argument, if t, means if fail just return nil (no error).
-   If not nil and not t, move to limit of search and return nil.
- Optional fourth argument is repeat count--search for successive occurrences.
- Relies on the function `word-search-regexp' to convert a sequence
- of words in STRING to a regexp used to search words without regard
- to punctuation.  */)
-   (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
- {
-   return search_command (Fword_search_regexp (string, Qt), bound, noerror, count, -1, 1, 0);
- }
- DEFUN ("word-search-forward-lax", Fword_search_forward_lax, Sword_search_forward_lax, 1, 4,
-        "sWord search: ",
-        doc: /* Search forward from point for STRING, ignoring differences in punctuation.
- Set point to the end of the occurrence found, and return point.
- Unlike `word-search-forward', the end of STRING need not match a word
- boundary, unless STRING ends in whitespace.
- An optional second argument bounds the search; it is a buffer position.
- The match found must not extend after that position.
- Optional third argument, if t, means if fail just return nil (no error).
-   If not nil and not t, move to limit of search and return nil.
- Optional fourth argument is repeat count--search for successive occurrences.
- Relies on the function `word-search-regexp' to convert a sequence
- of words in STRING to a regexp used to search words without regard
- to punctuation.  */)
-   (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
- {
-   return search_command (Fword_search_regexp (string, Qt), bound, noerror, count, 1, 1, 0);
- }
  DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
         "sRE search backward: ",
         doc: /* Search backward from point for match for regular expression REGEXP.
@@@ -2432,14 -2245,14 +2246,14 @@@ since only regular expressions have dis
    (Lisp_Object newtext, Lisp_Object fixedcase, Lisp_Object literal, Lisp_Object string, Lisp_Object subexp)
  {
    enum { nochange, all_caps, cap_initial } case_action;
 -  register EMACS_INT pos, pos_byte;
 +  register ptrdiff_t pos, pos_byte;
    int some_multiletter_word;
    int some_lowercase;
    int some_uppercase;
    int some_nonuppercase_initial;
    register int c, prevc;
    ptrdiff_t sub;
 -  EMACS_INT opoint, newpoint;
 +  ptrdiff_t opoint, newpoint;
  
    CHECK_STRING (newtext);
  
    if (NILP (fixedcase))
      {
        /* Decide how to casify by examining the matched text. */
 -      EMACS_INT last;
 +      ptrdiff_t last;
  
        pos = search_regs.start[sub];
        last = search_regs.end[sub];
         if desired.  */
        if (NILP (literal))
        {
 -        EMACS_INT lastpos = 0;
 -        EMACS_INT lastpos_byte = 0;
 +        ptrdiff_t lastpos = 0;
 +        ptrdiff_t lastpos_byte = 0;
          /* We build up the substituted string in ACCUM.  */
          Lisp_Object accum;
          Lisp_Object middle;
 -        EMACS_INT length = SBYTES (newtext);
 +        ptrdiff_t length = SBYTES (newtext);
  
          accum = Qnil;
  
          for (pos_byte = 0, pos = 0; pos_byte < length;)
            {
 -            EMACS_INT substart = -1;
 -            EMACS_INT subend = 0;
 +            ptrdiff_t substart = -1;
 +            ptrdiff_t subend = 0;
              int delbackslash = 0;
  
              FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
                    }
                  else if (c >= '1' && c <= '9')
                    {
 -                    if (search_regs.start[c - '0'] >= 0
 -                        && c <= search_regs.num_regs + '0')
 +                    if (c - '0' < search_regs.num_regs
 +                        && 0 <= search_regs.start[c - '0'])
                        {
                          substart = search_regs.start[c - '0'];
                          subend = search_regs.end[c - '0'];
  
              if (c == '&')
                idx = sub;
 -            else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
 +            else if (c >= '1' && c <= '9' && c - '0' < search_regs.num_regs)
                {
                  if (search_regs.start[c - '0'] >= 1)
                    idx = c - '0';
        {
          if (buf_multibyte)
            {
 -            EMACS_INT nchars =
 +            ptrdiff_t nchars =
                multibyte_chars_in_text (substed, substed_len);
  
              newtext = make_multibyte_string ((char *) substed, nchars,
  
    /* Adjust search data for this change.  */
    {
 -    EMACS_INT oldend = search_regs.end[sub];
 -    EMACS_INT oldstart = search_regs.start[sub];
 -    EMACS_INT change = newpoint - search_regs.end[sub];
 -    int i;
 +    ptrdiff_t oldend = search_regs.end[sub];
 +    ptrdiff_t oldstart = search_regs.start[sub];
 +    ptrdiff_t change = newpoint - search_regs.end[sub];
 +    ptrdiff_t i;
  
      for (i = 0; i < search_regs.num_regs; i++)
        {
@@@ -2910,7 -2723,7 +2724,7 @@@ Return value is undefined if the last s
  {
    Lisp_Object tail, prev;
    Lisp_Object *data;
 -  int i, len;
 +  ptrdiff_t i, len;
  
    if (!NILP (reseat))
      for (tail = reuse; CONSP (tail); tail = XCDR (tail))
    len = 0;
    for (i = 0; i < search_regs.num_regs; i++)
      {
 -      EMACS_INT start = search_regs.start[i];
 +      ptrdiff_t start = search_regs.start[i];
        if (start >= 0)
        {
          if (EQ (last_thing_searched, Qt)
@@@ -3022,13 -2835,11 +2836,13 @@@ If optional arg RESEAT is non-nil, mak
  
    /* Allocate registers if they don't already exist.  */
    {
 -    ptrdiff_t length = XFASTINT (Flength (list)) / 2;
 +    EMACS_INT length = XFASTINT (Flength (list)) / 2;
  
      if (length > search_regs.num_regs)
        {
        ptrdiff_t num_regs = search_regs.num_regs;
 +      if (PTRDIFF_MAX < length)
 +        memory_full (SIZE_MAX);
        search_regs.start =
          xpalloc (search_regs.start, &num_regs, length - num_regs,
                   min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
          }
        else
          {
 -          EMACS_INT from;
 +          Lisp_Object from;
            Lisp_Object m;
  
            m = marker;
              }
  
            CHECK_NUMBER_COERCE_MARKER (marker);
 -          from = XINT (marker);
 +          from = marker;
  
            if (!NILP (reseat) && MARKERP (m))
              {
              XSETFASTINT (marker, 0);
  
            CHECK_NUMBER_COERCE_MARKER (marker);
 -          search_regs.start[i] = from;
 -          search_regs.end[i] = XINT (marker);
 +          if ((XINT (from) < 0
 +               ? TYPE_MINIMUM (regoff_t) <= XINT (from)
 +               : XINT (from) <= TYPE_MAXIMUM (regoff_t))
 +              && (XINT (marker) < 0
 +                  ? TYPE_MINIMUM (regoff_t) <= XINT (marker)
 +                  : XINT (marker) <= TYPE_MAXIMUM (regoff_t)))
 +            {
 +              search_regs.start[i] = XINT (from);
 +              search_regs.end[i] = XINT (marker);
 +            }
 +          else
 +            {
 +              search_regs.start[i] = -1;
 +            }
  
            if (!NILP (reseat) && MARKERP (m))
              {
@@@ -3277,11 -3076,6 +3091,6 @@@ is to bind it with `let' around a smal
    defsubr (&Sposix_string_match);
    defsubr (&Ssearch_forward);
    defsubr (&Ssearch_backward);
-   defsubr (&Sword_search_regexp);
-   defsubr (&Sword_search_forward);
-   defsubr (&Sword_search_backward);
-   defsubr (&Sword_search_forward_lax);
-   defsubr (&Sword_search_backward_lax);
    defsubr (&Sre_search_forward);
    defsubr (&Sre_search_backward);
    defsubr (&Sposix_search_forward);
diff --combined src/sound.c
@@@ -124,9 -124,6 +124,6 @@@ static int parse_sound (Lisp_Object, Li
  #ifndef DEFAULT_SOUND_DEVICE
  #define DEFAULT_SOUND_DEVICE "/dev/dsp"
  #endif
- #ifndef DEFAULT_ALSA_SOUND_DEVICE
- #define DEFAULT_ALSA_SOUND_DEVICE "default"
- #endif
  
  
  /* Structure forward declarations.  */
@@@ -235,11 -232,11 +232,11 @@@ struct sound_devic
  
    /* Return a preferred data size in bytes to be sent to write (below)
       each time.  2048 is used if this is NULL.  */
 -  EMACS_INT (* period_size) (struct sound_device *sd);
 +  ptrdiff_t (* period_size) (struct sound_device *sd);
  
    /* Write NYBTES bytes from BUFFER to device SD.  */
    void (* write) (struct sound_device *sd, const char *buffer,
 -                  EMACS_INT nbytes);
 +                  ptrdiff_t nbytes);
  
    /* A place for devices to store additional data.  */
    void *data;
@@@ -291,7 -288,7 +288,7 @@@ static void vox_configure (struct sound
  static void vox_close (struct sound_device *sd);
  static void vox_choose_format (struct sound_device *, struct sound *);
  static int vox_init (struct sound_device *);
 -static void vox_write (struct sound_device *, const char *, EMACS_INT);
 +static void vox_write (struct sound_device *, const char *, ptrdiff_t);
  static void find_sound_type (struct sound *);
  static u_int32_t le2hl (u_int32_t);
  static u_int16_t le2hs (u_int16_t);
@@@ -600,9 -597,9 +597,9 @@@ wav_play (struct sound *s, struct sound
    else
      {
        char *buffer;
 -      EMACS_INT nbytes = 0;
 -      EMACS_INT blksize = sd->period_size ? sd->period_size (sd) : 2048;
 -      EMACS_INT data_left = header->data_length;
 +      ptrdiff_t nbytes = 0;
 +      ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
 +      ptrdiff_t data_left = header->data_length;
  
        buffer = (char *) alloca (blksize);
        lseek (s->fd, sizeof *header, SEEK_SET);
@@@ -690,9 -687,9 +687,9 @@@ au_play (struct sound *s, struct sound_
               SBYTES (s->data) - header->data_offset);
    else
      {
 -      EMACS_INT blksize = sd->period_size ? sd->period_size (sd) : 2048;
 +      ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
        char *buffer;
 -      EMACS_INT nbytes;
 +      ptrdiff_t nbytes;
  
        /* Seek */
        lseek (s->fd, header->data_offset, SEEK_SET);
@@@ -895,7 -892,7 +892,7 @@@ vox_init (struct sound_device *sd
  /* Write NBYTES bytes from BUFFER to device SD.  */
  
  static void
 -vox_write (struct sound_device *sd, const char *buffer, EMACS_INT nbytes)
 +vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
  {
    if (emacs_write (sd->fd, buffer, nbytes) != nbytes)
      sound_perror ("Error writing to sound device");
  
  /* This driver is available on GNU/Linux. */
  
+ #ifndef DEFAULT_ALSA_SOUND_DEVICE
+ #define DEFAULT_ALSA_SOUND_DEVICE "default"
+ #endif
  static void
  alsa_sound_perror (const char *msg, int err)
  {
@@@ -952,7 -953,7 +953,7 @@@ alsa_open (struct sound_device *sd
      alsa_sound_perror (file, err);
  }
  
 -static EMACS_INT
 +static ptrdiff_t
  alsa_period_size (struct sound_device *sd)
  {
    struct alsa_params *p = (struct alsa_params *) sd->data;
@@@ -1155,13 -1156,13 +1156,13 @@@ alsa_choose_format (struct sound_devic
  /* Write NBYTES bytes from BUFFER to device SD.  */
  
  static void
 -alsa_write (struct sound_device *sd, const char *buffer, EMACS_INT nbytes)
 +alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
  {
    struct alsa_params *p = (struct alsa_params *) sd->data;
  
    /* The the third parameter to snd_pcm_writei is frames, not bytes. */
    int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
 -  EMACS_INT nwritten = 0;
 +  ptrdiff_t nwritten = 0;
    int err;
  
    while (nwritten < nbytes)
@@@ -1348,7 -1349,7 +1349,7 @@@ Internal use only, use `play-sound' ins
    (Lisp_Object sound)
  {
    Lisp_Object attrs[SOUND_ATTR_SENTINEL];
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
  #ifndef WINDOWSNT
    Lisp_Object file;
diff --combined src/sysdep.c
@@@ -52,9 -52,6 +52,6 @@@ along with GNU Emacs.  If not, see <htt
  #define read sys_read
  #define write sys_write
  #include <windows.h>
- #ifndef NULL
- #define NULL 0
- #endif
  #endif /* not WINDOWSNT */
  
  #include <sys/types.h>
@@@ -307,7 -304,7 +304,7 @@@ int wait_debugging EXTERNALLY_VISIBLE
  #ifndef MSDOS
  
  static void
 -wait_for_termination_1 (int pid, int interruptible)
 +wait_for_termination_1 (pid_t pid, int interruptible)
  {
    while (1)
      {
     make sure it will get eliminated (not remain forever as a zombie) */
  
  void
 -wait_for_termination (int pid)
 +wait_for_termination (pid_t pid)
  {
    wait_for_termination_1 (pid, 0);
  }
  
  /* Like the above, but allow keyboard interruption. */
  void
 -interruptible_wait_for_termination (int pid)
 +interruptible_wait_for_termination (pid_t pid)
  {
    wait_for_termination_1 (pid, 1);
  }
@@@ -1913,8 -1910,8 +1910,8 @@@ emacs_close (int fd
  /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
     Return the number of bytes read, which might be less than NBYTE.
     On error, set errno and return -1.  */
 -EMACS_INT
 -emacs_read (int fildes, char *buf, EMACS_INT nbyte)
 +ptrdiff_t
 +emacs_read (int fildes, char *buf, ptrdiff_t nbyte)
  {
    register ssize_t rtnval;
  
  /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
     or if a partial write occurs.  Return the number of bytes written, setting
     errno if this is less than NBYTE.  */
 -EMACS_INT
 -emacs_write (int fildes, const char *buf, EMACS_INT nbyte)
 +ptrdiff_t
 +emacs_write (int fildes, const char *buf, ptrdiff_t nbyte)
  {
    ssize_t rtnval;
 -  EMACS_INT bytes_written;
 +  ptrdiff_t bytes_written;
  
    bytes_written = 0;
  
@@@ -2169,8 -2166,7 +2166,8 @@@ set_file_times (const char *filename, E
  int
  mkdir (char *dpath, int dmode)
  {
 -  int cpid, status, fd;
 +  pid_t cpid;
 +  int status, fd;
    struct stat statbuf;
  
    if (stat (dpath, &statbuf) == 0)
@@@ -2744,10 -2740,7 +2741,10 @@@ system_process_attributes (Lisp_Object 
    char *cmdline = NULL;
    ptrdiff_t cmdsize = 0, cmdline_size;
    unsigned char c;
 -  int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount;
 +  printmax_t proc_id;
 +  int ppid, pgrp, sess, tty, tpgid, thcount;
 +  uid_t uid;
 +  gid_t gid;
    unsigned long long u_time, s_time, cutime, cstime, start;
    long priority, niceness, rss;
    unsigned long minflt, majflt, cminflt, cmajflt, vsize;
    Lisp_Object attrs = Qnil;
    Lisp_Object cmd_str, decoded_cmd, tem;
    struct gcpro gcpro1, gcpro2;
 -  EMACS_INT uid_eint, gid_eint;
  
    CHECK_NUMBER_OR_FLOAT (pid);
 -  proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
 -  sprintf (procfn, "/proc/%u", proc_id);
 +  CONS_TO_INTEGER (pid, pid_t, proc_id);
 +  sprintf (procfn, "/proc/%"pMd, proc_id);
    if (stat (procfn, &st) < 0)
      return attrs;
  
  
    /* euid egid */
    uid = st.st_uid;
 -  /* Use of EMACS_INT stops GCC whining about limited range of data type.  */
 -  uid_eint = uid;
 -  attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
 +  attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
    BLOCK_INPUT;
    pw = getpwuid (uid);
    UNBLOCK_INPUT;
      attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
  
    gid = st.st_gid;
 -  gid_eint = gid;
 -  attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
 +  attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
    BLOCK_INPUT;
    gr = getgrgid (gid);
    UNBLOCK_INPUT;
@@@ -3017,16 -3014,15 +3014,16 @@@ system_process_attributes (Lisp_Object 
    struct psinfo pinfo;
    int fd;
    ssize_t nread;
 -  int proc_id, uid, gid;
 +  printmax_t proc_id;
 +  uid_t uid;
 +  gid_t gid;
    Lisp_Object attrs = Qnil;
    Lisp_Object decoded_cmd, tem;
    struct gcpro gcpro1, gcpro2;
 -  EMACS_INT uid_eint, gid_eint;
  
    CHECK_NUMBER_OR_FLOAT (pid);
 -  proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
 -  sprintf (procfn, "/proc/%u", proc_id);
 +  CONS_TO_INTEGER (pid, pid_t, proc_id);
 +  sprintf (procfn, "/proc/%"pMd, proc_id);
    if (stat (procfn, &st) < 0)
      return attrs;
  
  
    /* euid egid */
    uid = st.st_uid;
 -  /* Use of EMACS_INT stops GCC whining about limited range of data type.  */
 -  uid_eint = uid;
 -  attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
 +  attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
    BLOCK_INPUT;
    pw = getpwuid (uid);
    UNBLOCK_INPUT;
      attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
  
    gid = st.st_gid;
 -  gid_eint = gid;
 -  attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
 +  attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
    BLOCK_INPUT;
    gr = getgrgid (gid);
    UNBLOCK_INPUT;
@@@ -3157,7 -3156,7 +3154,7 @@@ system_process_attributes (Lisp_Object 
    Lisp_Object decoded_comm;
  
    CHECK_NUMBER_OR_FLOAT (pid);
 -  proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
 +  CONS_TO_INTEGER (pid, int, proc_id);
    mib[3] = proc_id;
  
    if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
diff --combined src/term.c
@@@ -1915,7 -1915,8 +1915,7 @@@ produce_special_glyphs (struct it *it, 
        else
        SET_GLYPH_FROM_CHAR (glyph, '\\');
        if (it->dp
 -        && (gc = DISP_CONTINUE_GLYPH (it->dp), GLYPH_CODE_P (gc))
 -        && GLYPH_CODE_CHAR_VALID_P (gc))
 +        && (gc = DISP_CONTINUE_GLYPH (it->dp), GLYPH_CODE_P (gc)))
        {
          /* FIXME: Should we mirror GC for R2L lines?  */
          SET_GLYPH_FROM_GLYPH_CODE (glyph, gc);
        /* Truncation glyph.  */
        SET_GLYPH_FROM_CHAR (glyph, '$');
        if (it->dp
 -        && (gc = DISP_TRUNC_GLYPH (it->dp), GLYPH_CODE_P (gc))
 -        && GLYPH_CODE_CHAR_VALID_P (gc))
 +        && (gc = DISP_TRUNC_GLYPH (it->dp), GLYPH_CODE_P (gc)))
        {
          /* FIXME: Should we mirror GC for R2L lines?  */
          SET_GLYPH_FROM_GLYPH_CODE (glyph, gc);
@@@ -2277,7 -2279,7 +2277,7 @@@ set_tty_color_mode (struct tty_display_
    else
      color_mode = Qnil;
  
 -  mode = INTEGERP (color_mode) ? XINT (color_mode) : 0;
 +  mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
  
    if (mode != tty->previous_color_mode)
      {
@@@ -3599,7 -3601,7 +3599,7 @@@ delete_tty (struct terminal *terminal
  \f
  
  /* Mark the pointers in the tty_display_info objects.
-    Called by the Fgarbage_collector.  */
+    Called by Fgarbage_collect.  */
  
  void
  mark_ttys (void)
diff --combined src/textprop.c
@@@ -23,10 -23,6 +23,6 @@@ along with GNU Emacs.  If not, see <htt
  #include "buffer.h"
  #include "window.h"
  
- #ifndef NULL
- #define NULL (void *)0
- #endif
  /* Test for membership, allowing for t (actually any non-cons) to mean the
     universal set.  */
  
@@@ -124,7 -120,7 +120,7 @@@ INTERVA
  validate_interval_range (Lisp_Object object, Lisp_Object *begin, Lisp_Object *end, int force)
  {
    register INTERVAL i;
 -  EMACS_INT searchpos;
 +  ptrdiff_t searchpos;
  
    CHECK_STRING_OR_BUFFER (object);
    CHECK_NUMBER_COERCE_MARKER (*begin);
      }
    else
      {
 -      EMACS_INT len = SCHARS (object);
 +      ptrdiff_t len = SCHARS (object);
  
        if (! (0 <= XINT (*begin) && XINT (*begin) <= XINT (*end)
             && XINT (*end) <= len))
@@@ -514,10 -510,10 +510,10 @@@ erase_properties (INTERVAL i
     POSITION is BEG-based.  */
  
  INTERVAL
 -interval_of (EMACS_INT position, Lisp_Object object)
 +interval_of (ptrdiff_t position, Lisp_Object object)
  {
    register INTERVAL i;
 -  EMACS_INT beg, end;
 +  ptrdiff_t beg, end;
  
    if (NILP (object))
      XSETBUFFER (object, current_buffer);
@@@ -775,7 -771,7 +771,7 @@@ past position LIMIT; return LIMIT if no
    else
      {
        Lisp_Object initial_value, value;
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
  
        if (! NILP (object))
        CHECK_BUFFER (object);
@@@ -858,7 -854,7 +854,7 @@@ position LIMIT; return LIMIT if nothin
      }
    else
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
  
        if (! NILP (object))
        CHECK_BUFFER (object);
@@@ -1140,7 -1136,7 +1136,7 @@@ Return t if any property value actuall
    (Lisp_Object start, Lisp_Object end, Lisp_Object properties, Lisp_Object object)
  {
    register INTERVAL i, unchanged;
 -  register EMACS_INT s, len;
 +  register ptrdiff_t s, len;
    register int modified = 0;
    struct gcpro gcpro1;
  
           skip it.  */
        if (interval_has_all_properties (properties, i))
        {
 -        EMACS_INT got = (LENGTH (i) - (s - i->position));
 +        ptrdiff_t got = (LENGTH (i) - (s - i->position));
          if (got >= len)
            RETURN_UNGCPRO (Qnil);
          len -= got;
@@@ -1345,7 -1341,7 +1341,7 @@@ voi
  set_text_properties_1 (Lisp_Object start, Lisp_Object end, Lisp_Object properties, Lisp_Object buffer, INTERVAL i)
  {
    register INTERVAL prev_changed = NULL_INTERVAL;
 -  register EMACS_INT s, len;
 +  register ptrdiff_t s, len;
    INTERVAL unchanged;
  
    if (XINT (start) < XINT (end))
@@@ -1438,7 -1434,7 +1434,7 @@@ Use `set-text-properties' if you want t
    (Lisp_Object start, Lisp_Object end, Lisp_Object properties, Lisp_Object object)
  {
    register INTERVAL i, unchanged;
 -  register EMACS_INT s, len;
 +  register ptrdiff_t s, len;
    register int modified = 0;
  
    if (NILP (object))
           it covers the entire region.  */
        if (! interval_has_some_properties (properties, i))
        {
 -        EMACS_INT got = (LENGTH (i) - (s - i->position));
 +        ptrdiff_t got = (LENGTH (i) - (s - i->position));
          if (got >= len)
            return Qnil;
          len -= got;
@@@ -1524,7 -1520,7 +1520,7 @@@ Return t if any property was actually r
    (Lisp_Object start, Lisp_Object end, Lisp_Object list_of_properties, Lisp_Object object)
  {
    register INTERVAL i, unchanged;
 -  register EMACS_INT s, len;
 +  register ptrdiff_t s, len;
    register int modified = 0;
    Lisp_Object properties;
    properties = list_of_properties;
           it covers the entire region.  */
        if (! interval_has_some_properties_list (properties, i))
        {
 -        EMACS_INT got = (LENGTH (i) - (s - i->position));
 +        ptrdiff_t got = (LENGTH (i) - (s - i->position));
          if (got >= len)
            return Qnil;
          len -= got;
@@@ -1634,7 -1630,7 +1630,7 @@@ markers).  If OBJECT is a string, STAR
    (Lisp_Object start, Lisp_Object end, Lisp_Object property, Lisp_Object value, Lisp_Object object)
  {
    register INTERVAL i;
 -  register EMACS_INT e, pos;
 +  register ptrdiff_t e, pos;
  
    if (NILP (object))
      XSETBUFFER (object, current_buffer);
@@@ -1670,7 -1666,7 +1666,7 @@@ markers).  If OBJECT is a string, STAR
    (Lisp_Object start, Lisp_Object end, Lisp_Object property, Lisp_Object value, Lisp_Object object)
  {
    register INTERVAL i;
 -  register EMACS_INT s, e;
 +  register ptrdiff_t s, e;
  
    if (NILP (object))
      XSETBUFFER (object, current_buffer);
@@@ -1780,7 -1776,7 +1776,7 @@@ copy_text_properties (Lisp_Object start
    Lisp_Object res;
    Lisp_Object stuff;
    Lisp_Object plist;
 -  EMACS_INT s, e, e2, p, len;
 +  ptrdiff_t s, e, e2, p, len;
    int modified = 0;
    struct gcpro gcpro1, gcpro2;
  
    {
      Lisp_Object dest_start, dest_end;
  
 +    e = XINT (pos) + (XINT (end) - XINT (start));
 +    if (MOST_POSITIVE_FIXNUM < e)
 +      args_out_of_range (pos, end);
      dest_start = pos;
 -    XSETFASTINT (dest_end, XINT (dest_start) + (XINT (end) - XINT (start)));
 +    XSETFASTINT (dest_end, e);
      /* Apply this to a copy of pos; it will try to increment its arguments,
         which we don't want.  */
      validate_interval_range (dest, &dest_start, &dest_end, soft);
@@@ -1880,12 -1873,12 +1876,12 @@@ text_property_list (Lisp_Object object
    i = validate_interval_range (object, &start, &end, soft);
    if (!NULL_INTERVAL_P (i))
      {
 -      EMACS_INT s = XINT (start);
 -      EMACS_INT e = XINT (end);
 +      ptrdiff_t s = XINT (start);
 +      ptrdiff_t e = XINT (end);
  
        while (s < e)
        {
 -        EMACS_INT interval_end, len;
 +        ptrdiff_t interval_end, len;
          Lisp_Object plist;
  
          interval_end = i->position + LENGTH (i);
@@@ -1963,7 -1956,7 +1959,7 @@@ Lisp_Objec
  extend_property_ranges (Lisp_Object list, Lisp_Object new_end)
  {
    Lisp_Object prev = Qnil, head = list;
 -  EMACS_INT max = XINT (new_end);
 +  ptrdiff_t max = XINT (new_end);
  
    for (; CONSP (list); prev = list, list = XCDR (list))
      {
@@@ -2017,7 -2010,7 +2013,7 @@@ call_mod_hooks (Lisp_Object list, Lisp_
  
  void
  verify_interval_modification (struct buffer *buf,
 -                            EMACS_INT start, EMACS_INT end)
 +                            ptrdiff_t start, ptrdiff_t end)
  {
    register INTERVAL intervals = BUF_INTERVALS (buf);
    register INTERVAL i;
  
    if (start > end)
      {
 -      EMACS_INT temp = start;
 +      ptrdiff_t temp = start;
        start = end;
        end = temp;
      }
diff --combined src/undo.c
@@@ -30,7 -30,7 +30,7 @@@ static struct buffer *last_undo_buffer
  
  /* Position of point last time we inserted a boundary.  */
  static struct buffer *last_boundary_buffer;
 -static EMACS_INT last_boundary_position;
 +static ptrdiff_t last_boundary_position;
  
  Lisp_Object Qinhibit_read_only;
  
@@@ -51,7 -51,7 +51,7 @@@ static Lisp_Object pending_boundary
     undo record that will be added just after this command terminates.  */
  
  static void
 -record_point (EMACS_INT pt)
 +record_point (ptrdiff_t pt)
  {
    int at_boundary;
  
     because we don't need to record the contents.)  */
  
  void
 -record_insert (EMACS_INT beg, EMACS_INT length)
 +record_insert (ptrdiff_t beg, ptrdiff_t length)
  {
    Lisp_Object lbeg, lend;
  
     of the characters in STRING, at location BEG.  */
  
  void
 -record_delete (EMACS_INT beg, Lisp_Object string)
 +record_delete (ptrdiff_t beg, Lisp_Object string)
  {
    Lisp_Object sbeg;
  
     won't be inverted automatically by undoing the buffer modification.  */
  
  void
 -record_marker_adjustment (Lisp_Object marker, EMACS_INT adjustment)
 +record_marker_adjustment (Lisp_Object marker, ptrdiff_t adjustment)
  {
    if (EQ (BVAR (current_buffer, undo_list), Qt))
      return;
     The replacement must not change the number of characters.  */
  
  void
 -record_change (EMACS_INT beg, EMACS_INT length)
 +record_change (ptrdiff_t beg, ptrdiff_t length)
  {
    record_delete (beg, make_buffer_string (beg, beg + length, 1));
    record_insert (beg, length);
@@@ -233,7 -233,7 +233,7 @@@ record_first_change (void
     for LENGTH characters starting at position BEG in BUFFER.  */
  
  void
 -record_property_change (EMACS_INT beg, EMACS_INT length,
 +record_property_change (ptrdiff_t beg, ptrdiff_t length,
                        Lisp_Object prop, Lisp_Object value,
                        Lisp_Object buffer)
  {
@@@ -308,11 -308,11 +308,11 @@@ truncate_undo_list (struct buffer *b
  {
    Lisp_Object list;
    Lisp_Object prev, next, last_boundary;
 -  int size_so_far = 0;
 +  EMACS_INT size_so_far = 0;
  
    /* Make sure that calling undo-outer-limit-function
       won't cause another GC.  */
 -  int count = inhibit_garbage_collection ();
 +  ptrdiff_t count = inhibit_garbage_collection ();
  
    /* Make the buffer current to get its local values of variables such
       as undo_limit.  Also so that Vundo_outer_limit_function can
  
    unbind_to (count, Qnil);
  }
+ static void user_error (const char*) NO_RETURN;
+ static void user_error (const char *msg)
+ {
+   xsignal1 (Quser_error, build_string (msg));
+ }
  \f
  DEFUN ("primitive-undo", Fprimitive_undo, Sprimitive_undo, 2, 2, 0,
         doc: /* Undo N records from the front of the list LIST.
@@@ -444,8 -451,8 +451,8 @@@ Return what remains of the list.  */
  {
    struct gcpro gcpro1, gcpro2;
    Lisp_Object next;
 -  int count = SPECPDL_INDEX ();
 -  register int arg;
 +  ptrdiff_t count = SPECPDL_INDEX ();
 +  register EMACS_INT arg;
    Lisp_Object oldlist;
    int did_apply = 0;
  
                  end = Fcdr (cdr);
  
                  if (XINT (beg) < BEGV || XINT (end) > ZV)
-                   error ("Changes to be undone are outside visible portion of buffer");
+                   user_error ("Changes to be undone are outside visible portion of buffer");
                  Fput_text_property (beg, end, prop, val, Qnil);
                }
              else if (INTEGERP (car) && INTEGERP (cdr))
  
                  if (XINT (car) < BEGV
                      || XINT (cdr) > ZV)
-                   error ("Changes to be undone are outside visible portion of buffer");
+                   user_error ("Changes to be undone are outside visible portion of buffer");
                  /* Set point first thing, so that undoing this undo
                     does not send point back to where it is now.  */
                  Fgoto_char (car);
                  if (pos < 0)
                    {
                      if (-pos < BEGV || -pos > ZV)
-                       error ("Changes to be undone are outside visible portion of buffer");
+                       user_error ("Changes to be undone are outside visible portion of buffer");
                      SET_PT (-pos);
                      Finsert (1, &membuf);
                    }
                  else
                    {
                      if (pos < BEGV || pos > ZV)
-                       error ("Changes to be undone are outside visible portion of buffer");
+                       user_error ("Changes to be undone are outside visible portion of buffer");
                      SET_PT (pos);
  
                      /* Now that we record marker adjustments
diff --combined src/w32fns.c
@@@ -4003,7 -4003,7 +4003,7 @@@ unwind_create_frame (Lisp_Object frame
  #if GLYPH_DEBUG
        /* Check that reference counts are indeed correct.  */
        xassert (dpyinfo->reference_count == dpyinfo_refcount);
-       xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
+       xassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
  #endif
        return Qt;
      }
@@@ -4070,7 -4070,7 +4070,7 @@@ This function is an internal primitive-
    int minibuffer_only = 0;
    long window_prompting = 0;
    int width, height;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    Lisp_Object display;
    struct w32_display_info *dpyinfo = NULL;
@@@ -5016,16 -5016,6 +5016,6 @@@ no value of TYPE (always string in the 
     cursor.  Duplicated from xdisp.c, but cannot use the version there
     due to lack of atimers on w32.  */
  #define DEFAULT_HOURGLASS_DELAY 1
- /* Return non-zero if hourglass timer has been started or hourglass is
-    shown.  */
- /* PENDING: if W32 can use atimers (atimer.[hc]) then the common impl in
-           xdisp.c could be used. */
- int
- hourglass_started (void)
- {
-   return hourglass_shown_p || hourglass_timer;
- }
  
  /* Cancel a currently active hourglass timer, and start a new one.  */
  
@@@ -5183,7 -5173,7 +5173,7 @@@ x_create_tip_frame (struct w32_display_
    Lisp_Object name;
    long window_prompting = 0;
    int width, height;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3;
    struct kboard *kb;
    int face_change_count_before = face_change_count;
  
  #if GLYPH_DEBUG
    image_cache_refcount =
-     FRAME_IMAGE_CACHE ? FRAME_IMAGE_CACHE (f)->refcount : 0;
+     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
    dpyinfo_refcount = dpyinfo->reference_count;
  #endif /* GLYPH_DEBUG */
    FRAME_KBOARD (f) = kb;
@@@ -5532,7 -5522,7 +5522,7 @@@ Text larger than the specified size is 
    int i, width, height, seen_reversed_p;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    int old_windows_or_buffers_changed = windows_or_buffers_changed;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    specbind (Qinhibit_redisplay, Qt);
  
@@@ -5811,7 -5801,7 +5801,7 @@@ DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hi
  Value is t if tooltip was open, nil otherwise.  */)
    (void)
  {
 -  int count;
 +  ptrdiff_t count;
    Lisp_Object deleted, frame, timer;
    struct gcpro gcpro1, gcpro2;
  
@@@ -5933,7 -5923,7 +5923,7 @@@ Otherwise, if ONLY-DIR-P is non-nil, th
  {
    struct frame *f = SELECTED_FRAME ();
    Lisp_Object file = Qnil;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
    char filename[MAX_PATH + 1];
    char init_dir[MAX_PATH + 1];
diff --combined src/w32menu.c
@@@ -48,6 -48,8 +48,8 @@@ along with GNU Emacs.  If not, see <htt
  
  #include "dispextern.h"
  
+ #include "w32heap.h"  /* for osinfo_cache */
  #undef HAVE_DIALOGS /* TODO: Implement native dialogs.  */
  
  #ifndef TRUE
@@@ -381,7 -383,7 +383,7 @@@ set_frame_menubar (FRAME_PTR f, int fir
  
        struct buffer *prev = current_buffer;
        Lisp_Object buffer;
 -      int specpdl_count = SPECPDL_INDEX ();
 +      ptrdiff_t specpdl_count = SPECPDL_INDEX ();
        int previous_menu_items_used = f->menu_bar_items_used;
        Lisp_Object *previous_items
        = (Lisp_Object *) alloca (previous_menu_items_used
@@@ -1498,8 -1500,11 +1500,11 @@@ add_menu_item (HMENU menu, widget_valu
            AppendMenu (menu, fuFlags,
                        item != NULL ? (UINT) item: (UINT) wv->call_data,
                        out_string);
-         /* Don't use Unicode menus in future.  */
-         unicode_append_menu = NULL;
+         /* Don't use Unicode menus in future, unless this is Windows
+            NT or later, where a failure of AppendMenuW does NOT mean
+            Unicode menus are unsupported.  */
+         if (osinfo_cache.dwPlatformId != VER_PLATFORM_WIN32_NT)
+           unicode_append_menu = NULL;
        }
  
        if (unicode_append_menu && (fuFlags & MF_OWNERDRAW))
diff --combined src/window.c
@@@ -63,7 -63,7 +63,7 @@@ static int displayed_window_lines (stru
  static struct window *decode_window (Lisp_Object);
  static int count_windows (struct window *);
  static int get_leaf_windows (struct window *, struct window **, int);
 -static void window_scroll (Lisp_Object, int, int, int);
 +static void window_scroll (Lisp_Object, EMACS_INT, int, int);
  static void window_scroll_pixel_based (Lisp_Object, int, int, int);
  static void window_scroll_line_based (Lisp_Object, int, int, int);
  static int freeze_window_start (struct window *, void *);
@@@ -127,8 -127,8 +127,8 @@@ static int window_scroll_pixel_based_pr
  static int window_scroll_pixel_based_preserve_y;
  
  /* Same for window_scroll_line_based.  */
 -static int window_scroll_preserve_hpos;
 -static int window_scroll_preserve_vpos;
 +static EMACS_INT window_scroll_preserve_hpos;
 +static EMACS_INT window_scroll_preserve_vpos;
  \f
  static struct window *
  decode_window (register Lisp_Object window)
@@@ -378,7 -378,7 +378,7 @@@ select_window (Lisp_Object window, Lisp
       redisplay_window has altered point after scrolling,
       because it makes the change only in the window.  */
    {
 -    register EMACS_INT new_point = marker_position (w->pointm);
 +    register ptrdiff_t new_point = marker_position (w->pointm);
      if (new_point < BEGV)
        SET_PT (BEGV);
      else if (new_point > ZV)
@@@ -680,10 -680,10 +680,10 @@@ window so that the location of point mo
    (Lisp_Object window, Lisp_Object ncol)
  {
    struct window *w = decode_window (window);
 -  int hscroll;
 +  ptrdiff_t hscroll;
  
    CHECK_NUMBER (ncol);
 -  hscroll = max (0, XINT (ncol));
 +  hscroll = clip_to_bounds (0, XINT (ncol), PTRDIFF_MAX);
  
    /* Prevent redisplay shortcuts when changing the hscroll.  */
    if (XINT (w->hscroll) != hscroll)
@@@ -1495,8 -1495,7 +1495,8 @@@ Return nil if window display is not up-
    register struct window *w;
    register struct buffer *b;
    struct glyph_row *row, *end_row;
 -  int max_y, crop, i, n;
 +  int max_y, crop, i;
 +  EMACS_INT n;
  
    w = decode_window (window);
  
@@@ -2564,7 -2563,7 +2564,7 @@@ window-start value is reasonable when t
    struct window *w, *r, *s;
    struct frame *f;
    Lisp_Object sibling, pwindow, swindow IF_LINT (= Qnil), delta;
 -  EMACS_INT startpos IF_LINT (= 0);
 +  ptrdiff_t startpos IF_LINT (= 0);
    int top IF_LINT (= 0), new_top, resize_failed;
    Mouse_HLInfo *hlinfo;
  
@@@ -2905,7 -2904,7 +2905,7 @@@ select_frame_norecord (Lisp_Object fram
  void
  run_window_configuration_change_hook (struct frame *f)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object frame, global_wcch
      = Fdefault_value (Qwindow_configuration_change_hook);
    XSETFRAME (frame, f);
        if (!NILP (Flocal_variable_p (Qwindow_configuration_change_hook,
                                      buffer)))
          {
 -          int inner_count = SPECPDL_INDEX ();
 +          ptrdiff_t inner_count = SPECPDL_INDEX ();
            record_unwind_protect (select_window_norecord, Fselected_window ());
            select_window_norecord (window);
            run_funs (Fbuffer_local_value (Qwindow_configuration_change_hook,
@@@ -2971,7 -2970,7 +2971,7 @@@ set_window_buffer (Lisp_Object window, 
  {
    struct window *w = XWINDOW (window);
    struct buffer *b = XBUFFER (buffer);
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int samebuf = EQ (buffer, w->buffer);
  
    w->buffer = buffer;
@@@ -3202,7 -3201,7 +3202,7 @@@ temp_output_buffer_show (register Lisp_
        /* Run temp-buffer-show-hook, with the chosen window selected
         and its buffer current.  */
        {
 -        int count = SPECPDL_INDEX ();
 +        ptrdiff_t count = SPECPDL_INDEX ();
          Lisp_Object prev_window, prev_buffer;
          prev_window = selected_window;
          XSETBUFFER (prev_buffer, old);
@@@ -4190,10 -4189,9 +4190,10 @@@ window_internal_height (struct window *
     respectively.  */
  
  static void
 -window_scroll (Lisp_Object window, int n, int whole, int noerror)
 +window_scroll (Lisp_Object window, EMACS_INT n, int whole, int noerror)
  {
    immediate_quit = 1;
 +  n = clip_to_bounds (INT_MIN, n, INT_MAX);
  
    /* If we must, use the pixel-based version which is much slower than
       the line-based one but can handle varying line heights.  */
@@@ -4223,6 -4221,11 +4223,11 @@@ window_scroll_pixel_based (Lisp_Object 
    void *itdata = NULL;
  
    SET_TEXT_POS_FROM_MARKER (start, w->start);
+   /* Scrolling a minibuffer window via scroll bar when the echo area
+      shows long text sometimes resets the minibuffer contents behind
+      our backs.  */
+   if (CHARPOS (start) > ZV)
+     SET_TEXT_POS (start, BEGV, BEGV_BYTE);
  
    /* If PT is not visible in WINDOW, move back one half of
       the screen.  Allow PT to be partially visible, otherwise
              /* Maybe modify window start instead of scrolling.  */
              if (rbot > 0 || w->vscroll < 0)
                {
 -                EMACS_INT spos;
 +                ptrdiff_t spos;
  
                  Fset_window_vscroll (window, make_number (0), Qt);
                  /* If there are other text lines above the current row,
    start_display (&it, w, start);
    if (whole)
      {
 -      EMACS_INT start_pos = IT_CHARPOS (it);
 +      ptrdiff_t start_pos = IT_CHARPOS (it);
        int dy = WINDOW_FRAME_LINE_HEIGHT (w);
        dy = max ((window_box_height (w)
                 - next_screen_context_lines * dy),
  
    if (! vscrolled)
      {
 -      EMACS_INT pos = IT_CHARPOS (it);
 -      EMACS_INT bytepos;
 +      ptrdiff_t pos = IT_CHARPOS (it);
 +      ptrdiff_t bytepos;
  
        /* If in the middle of a multi-glyph character move forward to
         the next character.  */
      }
    else if (n < 0)
      {
 -      EMACS_INT charpos, bytepos;
 +      ptrdiff_t charpos, bytepos;
        int partial_p;
  
        /* Save our position, for the
@@@ -4579,12 -4582,12 +4584,12 @@@ window_scroll_line_based (Lisp_Object w
       in `grep-mode-font-lock-keywords').  So we use a marker to record
       the old point position, to prevent crashes in SET_PT_BOTH.  */
    Lisp_Object opoint_marker = Fpoint_marker ();
 -  register EMACS_INT pos, pos_byte;
 +  register ptrdiff_t pos, pos_byte;
    register int ht = window_internal_height (w);
    register Lisp_Object tem;
    int lose;
    Lisp_Object bolp;
 -  EMACS_INT startpos;
 +  ptrdiff_t startpos;
    Lisp_Object original_pos = Qnil;
  
    /* If scrolling screen-fulls, compute the number of lines to
  static void
  scroll_command (Lisp_Object n, int direction)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    xassert (eabs (direction) == 1);
  
@@@ -4848,7 -4851,7 +4853,7 @@@ specifies the window to scroll.  This t
  {
    Lisp_Object window;
    struct window *w;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    window = Fother_window_for_scrolling ();
    w = XWINDOW (window);
@@@ -4890,7 -4893,7 +4895,7 @@@ by this function.  This happens in an i
    (register Lisp_Object arg, Lisp_Object set_minimum)
  {
    Lisp_Object result;
 -  int hscroll;
 +  EMACS_INT hscroll;
    struct window *w = XWINDOW (selected_window);
  
    if (NILP (arg))
@@@ -4919,7 -4922,7 +4924,7 @@@ by this function.  This happens in an i
    (register Lisp_Object arg, Lisp_Object set_minimum)
  {
    Lisp_Object result;
 -  int hscroll;
 +  EMACS_INT hscroll;
    struct window *w = XWINDOW (selected_window);
  
    if (NILP (arg))
@@@ -5030,7 -5033,7 +5035,7 @@@ and redisplay normally--don't erase an
    struct buffer *buf = XBUFFER (w->buffer);
    struct buffer *obuf = current_buffer;
    int center_p = 0;
 -  EMACS_INT charpos, bytepos;
 +  ptrdiff_t charpos, bytepos;
    EMACS_INT iarg IF_LINT (= 0);
    int this_scroll_margin;
  
        {
          struct it it;
          struct text_pos pt;
 -        int nlines = min (INT_MAX, -iarg);
 +        ptrdiff_t nlines = min (PTRDIFF_MAX, -iarg);
          int extra_line_spacing;
          int h = window_box_height (w);
          void *itdata = bidi_shelve_cache ();
@@@ -5379,7 -5382,7 +5384,7 @@@ the return value is nil.  Otherwise th
    Lisp_Object frame;
    Lisp_Object auto_buffer_name;
    FRAME_PTR f;
 -  EMACS_INT old_point = -1;
 +  ptrdiff_t old_point = -1;
  
    CHECK_WINDOW_CONFIGURATION (configuration);
  
@@@ -6184,7 -6187,7 +6189,7 @@@ Fourth parameter HORIZONTAL-TYPE is cur
  
    if (!NILP (width))
      {
 -      CHECK_NATNUM (width);
 +      CHECK_RANGED_INTEGER (0, width, INT_MAX);
  
        if (XINT (width) == 0)
        vertical_type = Qnil;
diff --combined src/xdisp.c
@@@ -383,11 -383,21 +383,21 @@@ static Lisp_Object Qline_height
  #define IT_OVERFLOW_NEWLINE_INTO_FRINGE(it) 0
  #endif /* HAVE_WINDOW_SYSTEM */
  
- /* Test if the display element loaded in IT is a space or tab
-    character.  This is used to determine word wrapping.  */
- #define IT_DISPLAYING_WHITESPACE(it)                          \
-   (it->what == IT_CHARACTER && (it->c == ' ' || it->c == '\t'))
+ /* Test if the display element loaded in IT, or the underlying buffer
+    or string character, is a space or a TAB character.  This is used
+    to determine where word wrapping can occur.  */
+ #define IT_DISPLAYING_WHITESPACE(it)                                  \
+   ((it->what == IT_CHARACTER && (it->c == ' ' || it->c == '\t'))      \
+    || ((STRINGP (it->string)                                          \
+       && (SREF (it->string, IT_STRING_BYTEPOS (*it)) == ' '           \
+           || SREF (it->string, IT_STRING_BYTEPOS (*it)) == '\t'))     \
+        || (it->s                                                      \
+          && (it->s[IT_BYTEPOS (*it)] == ' '                           \
+              || it->s[IT_BYTEPOS (*it)] == '\t'))                     \
+        || (IT_BYTEPOS (*it) < ZV_BYTE                                 \
+          && (*BYTE_POS_ADDR (IT_BYTEPOS (*it)) == ' '                 \
+              || *BYTE_POS_ADDR (IT_BYTEPOS (*it)) == '\t'))))         \
  
  /* Name of the face used to highlight trailing whitespace.  */
  
@@@ -748,7 -758,7 +758,7 @@@ static Lisp_Object Qinhibit_free_realiz
  Lisp_Object help_echo_string;
  Lisp_Object help_echo_window;
  Lisp_Object help_echo_object;
 -EMACS_INT help_echo_pos;
 +ptrdiff_t help_echo_pos;
  
  /* Temporary variable for XTread_socket.  */
  
@@@ -795,33 -805,33 +805,33 @@@ static Lisp_Object get_it_property (str
  
  static void handle_line_prefix (struct it *);
  
 -static void pint2str (char *, int, EMACS_INT);
 -static void pint2hrstr (char *, int, EMACS_INT);
 +static void pint2str (char *, int, ptrdiff_t);
 +static void pint2hrstr (char *, int, ptrdiff_t);
  static struct text_pos run_window_scroll_functions (Lisp_Object,
                                                      struct text_pos);
  static void reconsider_clip_changes (struct window *, struct buffer *);
  static int text_outside_line_unchanged_p (struct window *,
 -                                        EMACS_INT, EMACS_INT);
 +                                        ptrdiff_t, ptrdiff_t);
  static void store_mode_line_noprop_char (char);
  static int store_mode_line_noprop (const char *, int, int);
  static void handle_stop (struct it *);
 -static void handle_stop_backwards (struct it *, EMACS_INT);
 +static void handle_stop_backwards (struct it *, ptrdiff_t);
  static void vmessage (const char *, va_list) ATTRIBUTE_FORMAT_PRINTF (1, 0);
  static void ensure_echo_area_buffers (void);
  static Lisp_Object unwind_with_echo_area_buffer (Lisp_Object);
  static Lisp_Object with_echo_area_buffer_unwind_data (struct window *);
  static int with_echo_area_buffer (struct window *, int,
 -                                  int (*) (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT),
 -                                  EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT);
 +                                  int (*) (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t),
 +                                  ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t);
  static void clear_garbaged_frames (void);
 -static int current_message_1 (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT);
 +static int current_message_1 (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t);
  static void pop_message (void);
 -static int truncate_message_1 (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT);
 -static void set_message (const char *, Lisp_Object, EMACS_INT, int);
 -static int set_message_1 (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT);
 +static int truncate_message_1 (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t);
 +static void set_message (const char *, Lisp_Object, ptrdiff_t, int);
 +static int set_message_1 (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t);
  static int display_echo_area (struct window *);
 -static int display_echo_area_1 (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT);
 -static int resize_mini_window_1 (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT);
 +static int display_echo_area_1 (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t);
 +static int resize_mini_window_1 (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t);
  static Lisp_Object unwind_redisplay (Lisp_Object);
  static int string_char_and_length (const unsigned char *, int *);
  static struct text_pos display_prop_end (struct it *, Lisp_Object,
@@@ -834,11 -844,12 +844,12 @@@ static struct glyph_row *get_overlay_ar
  static void extend_face_to_end_of_line (struct it *);
  static int append_space_for_newline (struct it *, int);
  static int cursor_row_fully_visible_p (struct window *, int, int);
 -static int try_scrolling (Lisp_Object, int, EMACS_INT, EMACS_INT, int, int);
 +static int try_scrolling (Lisp_Object, int, ptrdiff_t, ptrdiff_t, int, int);
  static int try_cursor_movement (Lisp_Object, struct text_pos, int *);
 -static int trailing_whitespace_p (EMACS_INT);
 -static intmax_t message_log_check_duplicate (EMACS_INT, EMACS_INT);
 +static int trailing_whitespace_p (ptrdiff_t);
 +static intmax_t message_log_check_duplicate (ptrdiff_t, ptrdiff_t);
  static void push_it (struct it *, struct text_pos *);
+ static void iterate_out_of_display_property (struct it *);
  static void pop_it (struct it *);
  static void sync_frame_with_window_matrix_rows (struct window *);
  static void select_frame_for_redisplay (Lisp_Object);
@@@ -850,7 -861,7 +861,7 @@@ static Lisp_Object redisplay_window_err
  static Lisp_Object redisplay_window_0 (Lisp_Object);
  static Lisp_Object redisplay_window_1 (Lisp_Object);
  static int set_cursor_from_row (struct window *, struct glyph_row *,
 -                              struct glyph_matrix *, EMACS_INT, EMACS_INT,
 +                              struct glyph_matrix *, ptrdiff_t, ptrdiff_t,
                                int, int);
  static int update_menu_bar (struct frame *, int, int);
  static int try_window_reusing_current_matrix (struct window *);
@@@ -862,14 -873,14 +873,14 @@@ static int display_mode_element (struc
  static int store_mode_line_string (const char *, Lisp_Object, int, int, int, Lisp_Object);
  static const char *decode_mode_spec (struct window *, int, int, Lisp_Object *);
  static void display_menu_bar (struct window *);
 -static EMACS_INT display_count_lines (EMACS_INT, EMACS_INT, EMACS_INT,
 -                                    EMACS_INT *);
 +static ptrdiff_t display_count_lines (ptrdiff_t, ptrdiff_t, ptrdiff_t,
 +                                    ptrdiff_t *);
  static int display_string (const char *, Lisp_Object, Lisp_Object,
 -                           EMACS_INT, EMACS_INT, struct it *, int, int, int, int);
 +                           ptrdiff_t, ptrdiff_t, struct it *, int, int, int, int);
  static void compute_line_metrics (struct it *);
  static void run_redisplay_end_trigger_hook (struct it *);
 -static int get_overlay_strings (struct it *, EMACS_INT);
 -static int get_overlay_strings_1 (struct it *, EMACS_INT, int);
 +static int get_overlay_strings (struct it *, ptrdiff_t);
 +static int get_overlay_strings_1 (struct it *, ptrdiff_t, int);
  static void next_overlay_string (struct it *);
  static void reseat (struct it *, struct text_pos, int);
  static void reseat_1 (struct it *, struct text_pos, int);
@@@ -884,14 -895,14 +895,14 @@@ static int next_element_from_buffer (st
  static int next_element_from_composition (struct it *);
  static int next_element_from_image (struct it *);
  static int next_element_from_stretch (struct it *);
 -static void load_overlay_strings (struct it *, EMACS_INT);
 +static void load_overlay_strings (struct it *, ptrdiff_t);
  static int init_from_display_pos (struct it *, struct window *,
                                    struct display_pos *);
  static void reseat_to_string (struct it *, const char *,
 -                              Lisp_Object, EMACS_INT, EMACS_INT, int, int);
 +                              Lisp_Object, ptrdiff_t, ptrdiff_t, int, int);
  static int get_next_display_element (struct it *);
  static enum move_it_result
 -       move_it_in_display_line_to (struct it *, EMACS_INT, int,
 +       move_it_in_display_line_to (struct it *, ptrdiff_t, int,
                                   enum move_operation_enum);
  void move_it_vertically_backward (struct it *, int);
  static void init_to_row_start (struct it *, struct window *,
@@@ -901,20 -912,20 +912,20 @@@ static int init_to_row_end (struct it *
  static void back_to_previous_line_start (struct it *);
  static int forward_to_next_line_start (struct it *, int *, struct bidi_it *);
  static struct text_pos string_pos_nchars_ahead (struct text_pos,
 -                                                Lisp_Object, EMACS_INT);
 -static struct text_pos string_pos (EMACS_INT, Lisp_Object);
 -static struct text_pos c_string_pos (EMACS_INT, const char *, int);
 -static EMACS_INT number_of_chars (const char *, int);
 +                                                Lisp_Object, ptrdiff_t);
 +static struct text_pos string_pos (ptrdiff_t, Lisp_Object);
 +static struct text_pos c_string_pos (ptrdiff_t, const char *, int);
 +static ptrdiff_t number_of_chars (const char *, int);
  static void compute_stop_pos (struct it *);
  static void compute_string_pos (struct text_pos *, struct text_pos,
                                  Lisp_Object);
  static int face_before_or_after_it_pos (struct it *, int);
 -static EMACS_INT next_overlay_change (EMACS_INT);
 +static ptrdiff_t next_overlay_change (ptrdiff_t);
  static int handle_display_spec (struct it *, Lisp_Object, Lisp_Object,
 -                              Lisp_Object, struct text_pos *, EMACS_INT, int);
 +                              Lisp_Object, struct text_pos *, ptrdiff_t, int);
  static int handle_single_display_spec (struct it *, Lisp_Object,
                                         Lisp_Object, Lisp_Object,
 -                                       struct text_pos *, EMACS_INT, int, int);
 +                                       struct text_pos *, ptrdiff_t, int, int);
  static int underlying_face_id (struct it *);
  static int in_ellipses_for_invisible_text_p (struct display_pos *,
                                               struct window *);
@@@ -1246,7 -1257,7 +1257,7 @@@ string_from_display_spec (Lisp_Object s
     Set *ROWH and *VPOS to row's visible height and VPOS (row number).  */
  
  int
 -pos_visible_p (struct window *w, EMACS_INT charpos, int *x, int *y,
 +pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
               int *rtop, int *rbot, int *rowh, int *vpos)
  {
    struct it it;
      }
  
    SET_TEXT_POS_FROM_MARKER (top, w->start);
+   /* Scrolling a minibuffer window via scroll bar when the echo area
+      shows long text sometimes resets the minibuffer contents behind
+      our backs.  */
+   if (CHARPOS (top) > ZV)
+     SET_TEXT_POS (top, BEGV, BEGV_BYTE);
  
    /* Compute exact mode line heights.  */
    if (WINDOW_WANTS_MODELINE_P (w))
         glyph.  */
        int top_x = it.current_x;
        int top_y = it.current_y;
-       enum it_method it_method = it.method;
        /* Calling line_bottom_y may change it.method, it.position, etc.  */
+       enum it_method it_method = it.method;
        int bottom_y = (last_height = 0, line_bottom_y (&it));
        int window_top_y = WINDOW_HEADER_LINE_HEIGHT (w);
  
        visible_p = bottom_y > window_top_y;
        else if (top_y < it.last_visible_y)
        visible_p = 1;
+       if (bottom_y >= it.last_visible_y
+         && it.bidi_p && it.bidi_it.scan_dir == -1
+         && IT_CHARPOS (it) < charpos)
+       {
+         /* When the last line of the window is scanned backwards
+            under bidi iteration, we could be duped into thinking
+            that we have passed CHARPOS, when in fact move_it_to
+            simply stopped short of CHARPOS because it reached
+            last_visible_y.  To see if that's what happened, we call
+            move_it_to again with a slightly larger vertical limit,
+            and see if it actually moved vertically; if it did, we
+            didn't really reach CHARPOS, which is beyond window end.  */
+         struct it save_it = it;
+         /* Why 10? because we don't know how many canonical lines
+            will the height of the next line(s) be.  So we guess.  */
+         int ten_more_lines =
+           10 * FRAME_LINE_HEIGHT (XFRAME (WINDOW_FRAME (w)));
+         move_it_to (&it, charpos, -1, bottom_y + ten_more_lines, -1,
+                     MOVE_TO_POS | MOVE_TO_Y);
+         if (it.current_y > top_y)
+           visible_p = 0;
+         it = save_it;
+       }
        if (visible_p)
        {
          if (it_method == GET_FROM_DISPLAY_VECTOR)
                  Lisp_Object startpos, endpos;
                  EMACS_INT start, end;
                  struct it it3;
+                 int it3_moved;
  
                  /* Find the first and the last buffer positions
                     covered by the display string.  */
                     begins.  */
                  start_display (&it3, w, top);
                  move_it_to (&it3, -1, 0, top_y, -1, MOVE_TO_X | MOVE_TO_Y);
+                 /* If it3_moved stays zero after the 'while' loop
+                    below, that means we already were at a newline
+                    before the loop (e.g., the display string begins
+                    with a newline), so we don't need to (and cannot)
+                    inspect the glyphs of it3.glyph_row, because
+                    PRODUCE_GLYPHS will not produce anything for a
+                    newline, and thus it3.glyph_row stays at its
+                    stale content it got at top of the window.  */
+                 it3_moved = 0;
                  /* Finally, advance the iterator until we hit the
                     first display element whose character position is
                     CHARPOS, or until the first newline from the
                      if (IT_CHARPOS (it3) == charpos
                          || ITERATOR_AT_END_OF_LINE_P (&it3))
                        break;
+                     it3_moved = 1;
                      set_iterator_to_next (&it3, 0);
                    }
                  top_x = it3.current_x - it3.pixel_width;
                     display string, move back over the glyphs
                     produced from the string, until we find the
                     rightmost glyph not from the string.  */
-                 if (IT_CHARPOS (it3) != charpos && EQ (it3.object, string))
+                 if (it3_moved
+                     && IT_CHARPOS (it3) != charpos && EQ (it3.object, string))
                    {
                      struct glyph *g = it3.glyph_row->glyphs[TEXT_AREA]
                                        + it3.glyph_row->used[TEXT_AREA];
@@@ -1550,7 -1603,7 +1603,7 @@@ string_char_and_length (const unsigned 
     in STRING, return the position NCHARS ahead (NCHARS >= 0).  */
  
  static struct text_pos
 -string_pos_nchars_ahead (struct text_pos pos, Lisp_Object string, EMACS_INT nchars)
 +string_pos_nchars_ahead (struct text_pos pos, Lisp_Object string, ptrdiff_t nchars)
  {
    xassert (STRINGP (string) && nchars >= 0);
  
     for character position CHARPOS in STRING.  */
  
  static inline struct text_pos
 -string_pos (EMACS_INT charpos, Lisp_Object string)
 +string_pos (ptrdiff_t charpos, Lisp_Object string)
  {
    struct text_pos pos;
    xassert (STRINGP (string));
     means recognize multibyte characters.  */
  
  static struct text_pos
 -c_string_pos (EMACS_INT charpos, const char *s, int multibyte_p)
 +c_string_pos (ptrdiff_t charpos, const char *s, int multibyte_p)
  {
    struct text_pos pos;
  
  /* Value is the number of characters in C string S.  MULTIBYTE_P
     non-zero means recognize multibyte characters.  */
  
 -static EMACS_INT
 +static ptrdiff_t
  number_of_chars (const char *s, int multibyte_p)
  {
 -  EMACS_INT nchars;
 +  ptrdiff_t nchars;
  
    if (multibyte_p)
      {
 -      EMACS_INT rest = strlen (s);
 +      ptrdiff_t rest = strlen (s);
        int len;
        const unsigned char *p = (const unsigned char *) s;
  
@@@ -2346,7 -2399,7 +2399,7 @@@ safe_call (ptrdiff_t nargs, Lisp_Objec
      val = Qnil;
    else
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        struct gcpro gcpro1;
  
        GCPRO1 (args[0]);
@@@ -2496,7 -2549,7 +2549,7 @@@ check_window_end (struct window *w
  
  void
  init_iterator (struct it *it, struct window *w,
 -             EMACS_INT charpos, EMACS_INT bytepos,
 +             ptrdiff_t charpos, ptrdiff_t bytepos,
               struct glyph_row *row, enum face_id base_face_id)
  {
    int highlight_region_p;
       is invisible.  >0 means lines indented more than this value are
       invisible.  */
    it->selective = (INTEGERP (BVAR (current_buffer, selective_display))
 -                 ? XINT (BVAR (current_buffer, selective_display))
 +                 ? clip_to_bounds (-1, XINT (BVAR (current_buffer,
 +                                                   selective_display)),
 +                                   PTRDIFF_MAX)
                   : (!NILP (BVAR (current_buffer, selective_display))
                      ? -1 : 0));
    it->selective_display_ellipsis_p
              && WINDOWP (minibuf_selected_window)
              && w == XWINDOW (minibuf_selected_window))))
      {
 -      EMACS_INT markpos = marker_position (BVAR (current_buffer, mark));
 +      ptrdiff_t markpos = marker_position (BVAR (current_buffer, mark));
        it->region_beg_charpos = min (PT, markpos);
        it->region_end_charpos = max (PT, markpos);
      }
      it->redisplay_end_trigger_charpos
        = marker_position (w->redisplay_end_trigger);
    else if (INTEGERP (w->redisplay_end_trigger))
 -    it->redisplay_end_trigger_charpos = XINT (w->redisplay_end_trigger);
 +    it->redisplay_end_trigger_charpos =
 +      clip_to_bounds (PTRDIFF_MIN, XINT (w->redisplay_end_trigger), PTRDIFF_MAX);
  
    it->tab_width = SANE_TAB_WIDTH (current_buffer);
  
@@@ -2897,7 -2947,7 +2950,7 @@@ in_ellipses_for_invisible_text_p (struc
  {
    Lisp_Object prop, window;
    int ellipses_p = 0;
 -  EMACS_INT charpos = CHARPOS (pos->pos);
 +  ptrdiff_t charpos = CHARPOS (pos->pos);
  
    /* If POS specifies a position in a display vector, this might
       be for an ellipsis displayed for invisible text.  We won't
  static int
  init_from_display_pos (struct it *it, struct window *w, struct display_pos *pos)
  {
 -  EMACS_INT charpos = CHARPOS (pos->pos), bytepos = BYTEPOS (pos->pos);
 +  ptrdiff_t charpos = CHARPOS (pos->pos), bytepos = BYTEPOS (pos->pos);
    int i, overlay_strings_with_newlines = 0;
  
    /* If POS specifies a position in a display vector, this might
         pos->overlay_string_index is in IT->overlay_strings.  */
        if (pos->overlay_string_index >= OVERLAY_STRING_CHUNK_SIZE)
        {
 -        int n = pos->overlay_string_index / OVERLAY_STRING_CHUNK_SIZE;
 +        ptrdiff_t n = pos->overlay_string_index / OVERLAY_STRING_CHUNK_SIZE;
          it->current.overlay_string_index = 0;
          while (n--)
            {
@@@ -3111,7 -3161,15 +3164,15 @@@ handle_stop (struct it *it
                 overlays even if the actual buffer text is replaced.  */
              if (!handle_overlay_change_p
                  || it->sp > 1
-                 || !get_overlay_strings_1 (it, 0, 0))
+                 /* Don't call get_overlay_strings_1 if we already
+                    have overlay strings loaded, because doing so
+                    will load them again and push the iterator state
+                    onto the stack one more time, which is not
+                    expected by the rest of the code that processes
+                    overlay strings.  */
+                 || (it->n_overlay_strings <= 0
+                     ? !get_overlay_strings_1 (it, 0, 0)
+                     : 0))
                {
                  if (it->ellipsis_p)
                    setup_for_ellipsis (it, 0);
@@@ -3176,7 -3234,7 +3237,7 @@@ compute_stop_pos (struct it *it
  {
    register INTERVAL iv, next_iv;
    Lisp_Object object, limit, position;
 -  EMACS_INT charpos, bytepos;
 +  ptrdiff_t charpos, bytepos;
  
    if (STRINGP (it->string))
      {
      }
    else
      {
 -      EMACS_INT pos;
 +      ptrdiff_t pos;
  
        /* If end_charpos is out of range for some reason, such as a
         misbehaving display function, rationalize it (Bug#5984).  */
  
    if (it->cmp_it.id < 0)
      {
 -      EMACS_INT stoppos = it->end_charpos;
 +      ptrdiff_t stoppos = it->end_charpos;
  
        if (it->bidi_p && it->bidi_it.scan_dir < 0)
        stoppos = -1;
     follows.  This is like `next-overlay-change' but doesn't use
     xmalloc.  */
  
 -static EMACS_INT
 -next_overlay_change (EMACS_INT pos)
 +static ptrdiff_t
 +next_overlay_change (ptrdiff_t pos)
  {
    ptrdiff_t i, noverlays;
 -  EMACS_INT endpos;
 +  ptrdiff_t endpos;
    Lisp_Object *overlays;
  
    /* Get all overlays at the given position.  */
    for (i = 0; i < noverlays; ++i)
      {
        Lisp_Object oend;
 -      EMACS_INT oendpos;
 +      ptrdiff_t oendpos;
  
        oend = OVERLAY_END (overlays[i]);
        oendpos = OVERLAY_POSITION (oend);
     strings, non-zero otherwise.  It is set to 2 if the display string
     uses any kind of `(space ...)' spec that will produce a stretch of
     white space in the text area.  */
 -EMACS_INT
 +ptrdiff_t
  compute_display_string_pos (struct text_pos *position,
                            struct bidi_string_data *string,
                            int frame_window_p, int *disp_prop)
      (string && STRINGP (string->lstring)) ? string->lstring : Qnil;
    Lisp_Object pos, spec, limpos;
    int string_p = (string && (STRINGP (string->lstring) || string->s));
 -  EMACS_INT eob = string_p ? string->schars : ZV;
 -  EMACS_INT begb = string_p ? 0 : BEGV;
 -  EMACS_INT bufpos, charpos = CHARPOS (*position);
 -  EMACS_INT lim =
 +  ptrdiff_t eob = string_p ? string->schars : ZV;
 +  ptrdiff_t begb = string_p ? 0 : BEGV;
 +  ptrdiff_t bufpos, charpos = CHARPOS (*position);
 +  ptrdiff_t lim =
      (charpos < eob - MAX_DISP_SCAN) ? charpos + MAX_DISP_SCAN : eob;
    struct text_pos tpos;
    int rv = 0;
     return -1.  A display string is either an overlay with `display'
     property whose value is a string or a `display' text property whose
     value is a string.  */
 -EMACS_INT
 -compute_display_string_end (EMACS_INT charpos, struct bidi_string_data *string)
 +ptrdiff_t
 +compute_display_string_end (ptrdiff_t charpos, struct bidi_string_data *string)
  {
    /* OBJECT = nil means current buffer.  */
    Lisp_Object object =
      (string && STRINGP (string->lstring)) ? string->lstring : Qnil;
    Lisp_Object pos = make_number (charpos);
 -  EMACS_INT eob =
 +  ptrdiff_t eob =
      (STRINGP (object) || (string && string->s)) ? string->schars : ZV;
  
    if (charpos >= eob || (string->s && !STRINGP (object)))
@@@ -3487,7 -3545,7 +3548,7 @@@ handle_fontified_prop (struct it *it
             no amount of fontifying will be able to change it.  */
          NILP (prop) && IT_CHARPOS (*it) < Z))
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        Lisp_Object val;
        struct buffer *obuf = current_buffer;
        int begv = BEGV, zv = ZV;
@@@ -3584,7 -3642,7 +3645,7 @@@ static enum prop_handle
  handle_face_prop (struct it *it)
  {
    int new_face_id;
 -  EMACS_INT next_stop;
 +  ptrdiff_t next_stop;
  
    if (!STRINGP (it->string))
      {
    else
      {
        int base_face_id;
 -      EMACS_INT bufpos;
 +      ptrdiff_t bufpos;
        int i;
        Lisp_Object from_overlay
        = (it->current.overlay_string_index >= 0
@@@ -3745,7 -3803,7 +3806,7 @@@ static in
  face_before_or_after_it_pos (struct it *it, int before_p)
  {
    int face_id, limit;
 -  EMACS_INT next_check_charpos;
 +  ptrdiff_t next_check_charpos;
    struct it it_copy;
    void *it_copy_data = NULL;
  
  
    if (STRINGP (it->string))
      {
 -      EMACS_INT bufpos, charpos;
 +      ptrdiff_t bufpos, charpos;
        int base_face_id;
  
        /* No face change past the end of the string (for the case
@@@ -3966,7 -4024,7 +4027,7 @@@ handle_invisible_prop (struct it *it
        if (!NILP (prop)
          && IT_STRING_CHARPOS (*it) < it->end_charpos)
        {
 -        EMACS_INT endpos;
 +        ptrdiff_t endpos;
  
          handled = HANDLED_RECOMPUTE_PROPS;
  
              && (endpos = XFASTINT (end_charpos)) < XFASTINT (limit))
            {
              struct text_pos old;
 -            EMACS_INT oldpos;
 +            ptrdiff_t oldpos;
  
              old = it->current.string_pos;
              oldpos = CHARPOS (old);
    else
      {
        int invis_p;
 -      EMACS_INT newpos, next_stop, start_charpos, tem;
 +      ptrdiff_t newpos, next_stop, start_charpos, tem;
        Lisp_Object pos, prop, overlay;
  
        /* First of all, is there invisible text at this position?  */
          /* The position newpos is now either ZV or on visible text.  */
          if (it->bidi_p)
            {
 -            EMACS_INT bpos = CHAR_TO_BYTE (newpos);
 +            ptrdiff_t bpos = CHAR_TO_BYTE (newpos);
              int on_newline =
                bpos == ZV_BYTE || FETCH_BYTE (bpos) == '\n';
              int after_newline =
@@@ -4276,7 -4334,7 +4337,7 @@@ handle_display_prop (struct it *it
  {
    Lisp_Object propval, object, overlay;
    struct text_pos *position;
 -  EMACS_INT bufpos;
 +  ptrdiff_t bufpos;
    /* Nonzero if some property replaces the display of the text itself.  */
    int display_replaced_p = 0;
  
  static int
  handle_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
                     Lisp_Object overlay, struct text_pos *position,
 -                   EMACS_INT bufpos, int frame_window_p)
 +                   ptrdiff_t bufpos, int frame_window_p)
  {
    int replacing_p = 0;
    int rv;
      }
    else if (VECTORP (spec))
      {
 -      int i;
 +      ptrdiff_t i;
        for (i = 0; i < ASIZE (spec); ++i)
        if ((rv = handle_single_display_spec (it, AREF (spec, i), object,
                                              overlay, position, bufpos,
@@@ -4448,7 -4506,7 +4509,7 @@@ display_prop_end (struct it *it, Lisp_O
  static int
  handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
                            Lisp_Object overlay, struct text_pos *position,
 -                          EMACS_INT bufpos, int display_replaced_p,
 +                          ptrdiff_t bufpos, int display_replaced_p,
                            int frame_window_p)
  {
    Lisp_Object form;
  
    if (!NILP (form) && !EQ (form, Qt))
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        struct gcpro gcpro1;
  
        /* Bind `object' to the object having the `display' property, a
                  && (EQ (XCAR (it->font_height), Qplus)
                      || EQ (XCAR (it->font_height), Qminus))
                  && CONSP (XCDR (it->font_height))
 -                && INTEGERP (XCAR (XCDR (it->font_height))))
 +                && RANGED_INTEGERP (0, XCAR (XCDR (it->font_height)), INT_MAX))
                {
                  /* `(+ N)' or `(- N)' where N is an integer.  */
                  int steps = XINT (XCAR (XCDR (it->font_height)));
                {
                  /* Evaluate IT->font_height with `height' bound to the
                     current specified height to get the new height.  */
 -                int count = SPECPDL_INDEX ();
 +                ptrdiff_t count = SPECPDL_INDEX ();
  
                  specbind (Qheight, face->lface[LFACE_HEIGHT_INDEX]);
                  value = safe_eval (it->font_height);
          if (!FRAME_WINDOW_P (it->f))
            /* If we return here, POSITION has been advanced
               across the text with this property.  */
-           return 0;
+           {
+             /* Synchronize the bidi iterator with POSITION.  This is
+                needed because we are not going to push the iterator
+                on behalf of this display property, so there will be
+                no pop_it call to do this synchronization for us.  */
+             if (it->bidi_p)
+               {
+                 it->position = *position;
+                 iterate_out_of_display_property (it);
+                 *position = it->position;
+               }
+             return 1;
+           }
        }
        else if (!frame_window_p)
-       return 0;
+       return 1;
  
  #ifdef HAVE_WINDOW_SYSTEM
        value = XCAR (XCDR (spec));
          || !(fringe_bitmap = lookup_fringe_bitmap (value)))
        /* If we return here, POSITION has been advanced
           across the text with this property.  */
-       return 0;
+       {
+         if (it && it->bidi_p)
+           {
+             it->position = *position;
+             iterate_out_of_display_property (it);
+             *position = it->position;
+           }
+         return 1;
+       }
  
        if (it)
        {
  
  int
  display_prop_intangible_p (Lisp_Object prop, Lisp_Object overlay,
 -                         EMACS_INT charpos, EMACS_INT bytepos)
 +                         ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    int frame_window_p = FRAME_WINDOW_P (XFRAME (selected_frame));
    struct text_pos position;
@@@ -4954,7 -5032,7 +5035,7 @@@ display_prop_string_p (Lisp_Object prop
    else if (VECTORP (prop))
      {
        /* A vector of sub-properties.  */
 -      int i;
 +      ptrdiff_t i;
        for (i = 0; i < ASIZE (prop); ++i)
        if (single_display_spec_string_p (AREF (prop, i), string))
          return 1;
     This function may only use code that doesn't eval because it is
     called asynchronously from note_mouse_highlight.  */
  
 -static EMACS_INT
 +static ptrdiff_t
  string_buffer_position_lim (Lisp_Object string,
 -                          EMACS_INT from, EMACS_INT to, int back_p)
 +                          ptrdiff_t from, ptrdiff_t to, int back_p)
  {
    Lisp_Object limit, prop, pos;
    int found = 0;
     This function may only use code that doesn't eval because it is
     called asynchronously from note_mouse_highlight.  */
  
 -static EMACS_INT
 -string_buffer_position (Lisp_Object string, EMACS_INT around_charpos)
 +static ptrdiff_t
 +string_buffer_position (Lisp_Object string, ptrdiff_t around_charpos)
  {
    const int MAX_DISTANCE = 1000;
 -  EMACS_INT found = string_buffer_position_lim (string, around_charpos,
 +  ptrdiff_t found = string_buffer_position_lim (string, around_charpos,
                                                around_charpos + MAX_DISTANCE,
                                                0);
  
@@@ -5050,7 -5128,7 +5131,7 @@@ static enum prop_handle
  handle_composition_prop (struct it *it)
  {
    Lisp_Object prop, string;
 -  EMACS_INT pos, pos_byte, start, end;
 +  ptrdiff_t pos, pos_byte, start, end;
  
    if (STRINGP (it->string))
      {
@@@ -5116,7 -5194,7 +5197,7 @@@ struct overlay_entr
  {
    Lisp_Object overlay;
    Lisp_Object string;
 -  int priority;
 +  EMACS_INT priority;
    int after_string_p;
  };
  
@@@ -5248,17 -5326,12 +5329,17 @@@ compare_overlay_entries (const void *e1
        else
        result = entry1->after_string_p ? -1 : 1;
      }
 -  else if (entry1->after_string_p)
 -    /* After-strings sorted in order of decreasing priority.  */
 -    result = entry2->priority - entry1->priority;
 +  else if (entry1->priority != entry2->priority)
 +    {
 +      if (entry1->after_string_p)
 +      /* After-strings sorted in order of decreasing priority.  */
 +      result = entry2->priority < entry1->priority ? -1 : 1;
 +      else
 +      /* Before-strings sorted in order of increasing priority.  */
 +      result = entry1->priority < entry2->priority ? -1 : 1;
 +    }
    else
 -    /* Before-strings sorted in order of increasing priority.  */
 -    result = entry1->priority - entry2->priority;
 +    result = 0;
  
    return result;
  }
     compare_overlay_entries.  */
  
  static void
 -load_overlay_strings (struct it *it, EMACS_INT charpos)
 +load_overlay_strings (struct it *it, ptrdiff_t charpos)
  {
    Lisp_Object overlay, window, str, invisible;
    struct Lisp_Overlay *ov;
 -  EMACS_INT start, end;
 -  int size = 20;
 -  int n = 0, i, j, invis_p;
 +  ptrdiff_t start, end;
 +  ptrdiff_t size = 20;
 +  ptrdiff_t n = 0, i, j;
 +  int invis_p;
    struct overlay_entry *entries
      = (struct overlay_entry *) alloca (size * sizeof *entries);
 +  USE_SAFE_ALLOCA;
  
    if (charpos <= 0)
      charpos = IT_CHARPOS (*it);
                                                                        \
        if (n == size)                                                  \
        {                                                               \
 -        int new_size = 2 * size;                                      \
          struct overlay_entry *old = entries;                          \
 -        entries =                                                     \
 -            (struct overlay_entry *) alloca (new_size                 \
 -                                           * sizeof *entries);        \
 +        SAFE_NALLOCA (entries, 2, size);                              \
          memcpy (entries, old, size * sizeof *entries);                \
 -        size = new_size;                                              \
 +        size *= 2;                                                    \
        }                                                               \
                                                                        \
        entries[n].string = (STRING);                                   \
      }
  
    CHECK_IT (it);
 +  SAFE_FREE ();
  }
  
  
     least one overlay string was found.  */
  
  static int
 -get_overlay_strings_1 (struct it *it, EMACS_INT charpos, int compute_stop_p)
 +get_overlay_strings_1 (struct it *it, ptrdiff_t charpos, int compute_stop_p)
  {
    /* Get the first OVERLAY_STRING_CHUNK_SIZE overlay strings to
       process.  This fills IT->overlay_strings with strings, and sets
        /* Set up the bidi iterator for this overlay string.  */
        if (it->bidi_p)
        {
 -        EMACS_INT pos = (charpos > 0 ? charpos : IT_CHARPOS (*it));
 +        ptrdiff_t pos = (charpos > 0 ? charpos : IT_CHARPOS (*it));
  
          it->bidi_it.string.lstring = it->string;
          it->bidi_it.string.s = NULL;
  }
  
  static int
 -get_overlay_strings (struct it *it, EMACS_INT charpos)
 +get_overlay_strings (struct it *it, ptrdiff_t charpos)
  {
    it->string = Qnil;
    it->method = GET_FROM_BUFFER;
@@@ -5602,9 -5675,9 +5683,9 @@@ push_it (struct it *it, struct text_po
  static void
  iterate_out_of_display_property (struct it *it)
  {
-   int buffer_p = BUFFERP (it->object);
+   int buffer_p = !STRINGP (it->string);
 -  EMACS_INT eob = (buffer_p ? ZV : it->end_charpos);
 -  EMACS_INT bob = (buffer_p ? BEGV : 0);
 +  ptrdiff_t eob = (buffer_p ? ZV : it->end_charpos);
 +  ptrdiff_t bob = (buffer_p ? BEGV : 0);
  
    xassert (eob >= CHARPOS (it->position) && CHARPOS (it->position) >= bob);
  
@@@ -5766,7 -5839,7 +5847,7 @@@ static in
  forward_to_next_line_start (struct it *it, int *skipped_p,
                            struct bidi_it *bidi_it_prev)
  {
 -  EMACS_INT old_selective;
 +  ptrdiff_t old_selective;
    int newline_found_p, n;
    const int MAX_NEWLINE_DISTANCE = 500;
  
       short-cut.  */
    if (!newline_found_p)
      {
 -      EMACS_INT start = IT_CHARPOS (*it);
 -      EMACS_INT limit = find_next_newline_no_quit (start, 1);
 +      ptrdiff_t start = IT_CHARPOS (*it);
 +      ptrdiff_t limit = find_next_newline_no_quit (start, 1);
        Lisp_Object pos;
  
        xassert (!STRINGP (it->string));
@@@ -5907,8 -5980,8 +5988,8 @@@ back_to_previous_visible_line_start (st
        {
        struct it it2;
        void *it2data = NULL;
 -      EMACS_INT pos;
 -      EMACS_INT beg, end;
 +      ptrdiff_t pos;
 +      ptrdiff_t beg, end;
        Lisp_Object val, overlay;
  
        SAVE_IT (it2, *it, it2data);
@@@ -6061,7 -6134,7 +6142,7 @@@ reseat_at_next_visible_line_start (stru
  static void
  reseat (struct it *it, struct text_pos pos, int force_p)
  {
 -  EMACS_INT original_pos = IT_CHARPOS (*it);
 +  ptrdiff_t original_pos = IT_CHARPOS (*it);
  
    reseat_1 (it, pos, 0);
  
@@@ -6171,7 -6244,7 +6252,7 @@@ reseat_1 (struct it *it, struct text_po
  
  static void
  reseat_to_string (struct it *it, const char *s, Lisp_Object string,
 -                EMACS_INT charpos, EMACS_INT precision, int field_width,
 +                ptrdiff_t charpos, ptrdiff_t precision, int field_width,
                  int multibyte)
  {
    /* No region in strings.  */
      }
    if (s == NULL && it->multibyte_p)
      {
 -      EMACS_INT endpos = SCHARS (it->string);
 +      ptrdiff_t endpos = SCHARS (it->string);
        if (endpos > it->end_charpos)
        endpos = it->end_charpos;
        composition_compute_stop_pos (&it->cmp_it, charpos, -1, endpos,
@@@ -6397,11 -6470,11 +6478,11 @@@ lookup_glyphless_char_display (int c, s
     end of buffer (or C string) is reached.  */
  
  static struct frame *last_escape_glyph_frame = NULL;
 -static unsigned last_escape_glyph_face_id = (1 << FACE_ID_BITS);
 +static int last_escape_glyph_face_id = (1 << FACE_ID_BITS);
  static int last_escape_glyph_merged_face_id = 0;
  
  struct frame *last_glyphless_glyph_frame = NULL;
 -unsigned last_glyphless_glyph_face_id = (1 << FACE_ID_BITS);
 +int last_glyphless_glyph_face_id = (1 << FACE_ID_BITS);
  int last_glyphless_glyph_merged_face_id = 0;
  
  static int
@@@ -6533,7 -6606,7 +6614,7 @@@ get_next_display_element (struct it *it
              Lisp_Object gc;
              int ctl_len;
              int face_id;
 -            EMACS_INT lface_id = 0;
 +            int lface_id = 0;
              int escape_glyph;
  
              /* Handle control characters with ^.  */
                  g = '^';           /* default glyph for Control */
                  /* Set IT->ctl_chars[0] to the glyph for `^'.  */
                  if (it->dp
 -                    && (gc = DISP_CTRL_GLYPH (it->dp), GLYPH_CODE_P (gc))
 -                    && GLYPH_CODE_CHAR_VALID_P (gc))
 +                    && (gc = DISP_CTRL_GLYPH (it->dp), GLYPH_CODE_P (gc)))
                    {
                      g = GLYPH_CODE_CHAR (gc);
                      lface_id = GLYPH_CODE_FACE (gc);
              escape_glyph = '\\';
  
              if (it->dp
 -                && (gc = DISP_ESCAPE_GLYPH (it->dp), GLYPH_CODE_P (gc))
 -                && GLYPH_CODE_CHAR_VALID_P (gc))
 +                && (gc = DISP_ESCAPE_GLYPH (it->dp), GLYPH_CODE_P (gc)))
                {
                  escape_glyph = GLYPH_CODE_CHAR (gc);
                  lface_id = GLYPH_CODE_FACE (gc);
        }
        else
        {
 -        EMACS_INT pos = (it->s ? -1
 +        ptrdiff_t pos = (it->s ? -1
                     : STRINGP (it->string) ? IT_STRING_CHARPOS (*it)
                     : IT_CHARPOS (*it));
          int c;
                       && (it->current.overlay_string_index
                           == it->n_overlay_strings - 1))
                {
 -                EMACS_INT ignore;
 +                ptrdiff_t ignore;
                  int next_face_id;
                  struct text_pos pos = it->current.pos;
                  INC_TEXT_POS (pos, it->multibyte_p);
               && FACE_FROM_ID (it->f, face_id)->box == FACE_NO_BOX);
        }
      }
+   /* If we reached the end of the object we've been iterating (e.g., a
+      display string or an overlay string), and there's something on
+      IT->stack, proceed with what's on the stack.  It doesn't make
+      sense to return zero if there's unprocessed stuff on the stack,
+      because otherwise that stuff will never be displayed.  */
+   if (!success_p && it->sp > 0)
+     {
+       set_iterator_to_next (it, 0);
+       success_p = get_next_display_element (it);
+     }
  
    /* Value is 0 if end of buffer or string reached.  */
    return success_p;
@@@ -6847,7 -6932,7 +6938,7 @@@ set_iterator_to_next (struct it *it, in
                {
                  /* No more grapheme clusters in this composition.
                     Find the next stop position.  */
 -                EMACS_INT stop = it->end_charpos;
 +                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.  */
                {
                  /* No more grapheme clusters in this composition.
                     Find the next stop position.  */
 -                EMACS_INT stop = it->end_charpos;
 +                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.  */
                {
                  /* As the scan direction was changed, we must
                     re-compute the stop position for composition.  */
 -                EMACS_INT stop = it->end_charpos;
 +                ptrdiff_t stop = it->end_charpos;
                  if (it->bidi_it.scan_dir < 0)
                    stop = -1;
                  composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
           display vector entry (these entries may contain faces).  */
        it->face_id = it->saved_face_id;
  
-       if (it->dpvec + it->current.dpvec_index == it->dpend)
+       if (it->dpvec + it->current.dpvec_index >= it->dpend)
        {
          int recheck_faces = it->ellipsis_p;
  
      case GET_FROM_STRING:
        /* Current display element is a character from a Lisp string.  */
        xassert (it->s == NULL && STRINGP (it->string));
+       /* Don't advance past string end.  These conditions are true
+        when set_iterator_to_next is called at the end of
+        get_next_display_element, in which case the Lisp string is
+        already exhausted, and all we want is pop the iterator
+        stack.  */
+       if (it->current.overlay_string_index >= 0)
+       {
+         /* This is an overlay string, so there's no padding with
+            spaces, and the number of characters in the string is
+            where the string ends.  */
+         if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
+           goto consider_string_end;
+       }
+       else
+       {
+         /* Not an overlay string.  There could be padding, so test
+            against it->end_charpos . */
+         if (IT_STRING_CHARPOS (*it) >= it->end_charpos)
+           goto consider_string_end;
+       }
        if (it->cmp_it.id >= 0)
        {
          int i;
                it->cmp_it.from = it->cmp_it.to;
              else
                {
 -                EMACS_INT stop = it->end_charpos;
 +                ptrdiff_t stop = it->end_charpos;
                  if (it->bidi_it.scan_dir < 0)
                    stop = -1;
                  composition_compute_stop_pos (&it->cmp_it,
                it->cmp_it.to = it->cmp_it.from;
              else
                {
 -                EMACS_INT stop = it->end_charpos;
 +                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->bidi_it.charpos;
              if (prev_scan_dir != it->bidi_it.scan_dir)
                {
 -                EMACS_INT stop = it->end_charpos;
 +                ptrdiff_t stop = it->end_charpos;
  
                  if (it->bidi_it.scan_dir < 0)
                    stop = -1;
@@@ -7155,7 -7260,7 +7266,7 @@@ next_element_from_display_vector (struc
       That seemed totally bogus - so I changed it...  */
    gc = it->dpvec[it->current.dpvec_index];
  
 -  if (GLYPH_CODE_P (gc) && GLYPH_CODE_CHAR_VALID_P (gc))
 +  if (GLYPH_CODE_P (gc))
      {
        it->c = GLYPH_CODE_CHAR (gc);
        it->len = CHAR_BYTES (it->c);
        it->face_id = it->dpvec_face_id;
        else
        {
 -        EMACS_INT lface_id = GLYPH_CODE_FACE (gc);
 +        int lface_id = GLYPH_CODE_FACE (gc);
          if (lface_id > 0)
            it->face_id = merge_faces (it->f, Qt, lface_id,
                                       it->saved_face_id);
@@@ -7190,8 -7295,8 +7301,8 @@@ static voi
  get_visually_first_element (struct it *it)
  {
    int string_p = STRINGP (it->string) || it->s;
 -  EMACS_INT eob = (string_p ? it->bidi_it.string.schars : ZV);
 -  EMACS_INT bob = (string_p ? 0 : BEGV);
 +  ptrdiff_t eob = (string_p ? it->bidi_it.string.schars : ZV);
 +  ptrdiff_t bob = (string_p ? 0 : BEGV);
  
    if (STRINGP (it->string))
      {
      }
    else
      {
 -      EMACS_INT orig_bytepos = it->bidi_it.bytepos;
 +      ptrdiff_t orig_bytepos = it->bidi_it.bytepos;
  
        /* We need to prime the bidi iterator starting at the line's or
         string's beginning, before we will be able to produce the
  
    if (STRINGP (it->string) || !it->s)
      {
 -      EMACS_INT stop, charpos, bytepos;
 +      ptrdiff_t stop, charpos, bytepos;
  
        if (STRINGP (it->string))
        {
@@@ -7562,10 -7667,10 +7673,10 @@@ compute_stop_pos_backwards (struct it *
    struct text_pos pos;
    struct display_pos save_current = it->current;
    struct text_pos save_position = it->position;
 -  EMACS_INT charpos = IT_CHARPOS (*it);
 -  EMACS_INT where_we_are = charpos;
 -  EMACS_INT save_stop_pos = it->stop_charpos;
 -  EMACS_INT save_end_pos = it->end_charpos;
 +  ptrdiff_t charpos = IT_CHARPOS (*it);
 +  ptrdiff_t where_we_are = charpos;
 +  ptrdiff_t save_stop_pos = it->stop_charpos;
 +  ptrdiff_t save_end_pos = it->end_charpos;
  
    xassert (NILP (it->string) && !it->s);
    xassert (it->bidi_p);
     position.  */
  
  static void
 -handle_stop_backwards (struct it *it, EMACS_INT charpos)
 +handle_stop_backwards (struct it *it, ptrdiff_t charpos)
  {
    int bufp = !STRINGP (it->string);
 -  EMACS_INT where_we_are = (bufp ? IT_CHARPOS (*it) : IT_STRING_CHARPOS (*it));
 +  ptrdiff_t where_we_are = (bufp ? IT_CHARPOS (*it) : IT_STRING_CHARPOS (*it));
    struct display_pos save_current = it->current;
    struct text_pos save_position = it->position;
    struct text_pos pos1;
 -  EMACS_INT next_stop;
 +  ptrdiff_t next_stop;
  
    /* Scan in strict logical order.  */
    xassert (it->bidi_p);
@@@ -7754,7 -7859,7 +7865,7 @@@ next_element_from_buffer (struct it *it
        /* No face changes, overlays etc. in sight, so just return a
         character from current_buffer.  */
        unsigned char *p;
 -      EMACS_INT stop;
 +      ptrdiff_t stop;
  
        /* Maybe run the redisplay end trigger hook.  Performance note:
         This doesn't seem to cost measurable time.  */
@@@ -7943,7 -8048,7 +8054,7 @@@ next_element_from_composition (struct i
  
  static enum move_it_result
  move_it_in_display_line_to (struct it *it,
 -                          EMACS_INT to_charpos, int to_x,
 +                          ptrdiff_t to_charpos, int to_x,
                            enum move_operation_enum op)
  {
    enum move_it_result result = MOVE_UNDEFINED;
    void *ppos_data = NULL;
    int may_wrap = 0;
    enum it_method prev_method = it->method;
 -  EMACS_INT prev_pos = IT_CHARPOS (*it);
 +  ptrdiff_t prev_pos = IT_CHARPOS (*it);
    int saw_smaller_pos = prev_pos < to_charpos;
  
    /* Don't produce glyphs in produce_glyphs.  */
  /* For external use.  */
  void
  move_it_in_display_line (struct it *it,
 -                       EMACS_INT to_charpos, int to_x,
 +                       ptrdiff_t to_charpos, int to_x,
                         enum move_operation_enum op)
  {
    if (it->line_wrap == WORD_WRAP
     displayed to the right of TO_CHARPOS on the screen.  */
  
  void
 -move_it_to (struct it *it, EMACS_INT to_charpos, int to_x, int to_y, int to_vpos, int op)
 +move_it_to (struct it *it, ptrdiff_t to_charpos, int to_x, int to_y, int to_vpos, int op)
  {
    enum move_it_result skip, skip2 = MOVE_X_REACHED;
    int line_height, line_start_x = 0, reached = 0;
@@@ -8757,7 -8862,7 +8868,7 @@@ move_it_vertically_backward (struct it 
    int nlines, h;
    struct it it2, it3;
    void *it2data = NULL, *it3data = NULL;
 -  EMACS_INT start_pos;
 +  ptrdiff_t start_pos;
  
   move_further_back:
    xassert (dy >= 0);
          && IT_CHARPOS (*it) > BEGV
          && FETCH_BYTE (IT_BYTEPOS (*it) - 1) != '\n')
        {
 -        EMACS_INT nl_pos =
 +        ptrdiff_t nl_pos =
            find_next_newline_no_quit (IT_CHARPOS (*it) - 1, -1);
  
          move_it_to (it, nl_pos, -1, -1, -1, MOVE_TO_POS);
@@@ -8949,7 -9054,7 +9060,7 @@@ move_it_past_eol (struct it *it
     truncate-lines nil.  */
  
  void
 -move_it_by_lines (struct it *it, int dvpos)
 +move_it_by_lines (struct it *it, ptrdiff_t dvpos)
  {
  
    /* The commented-out optimization uses vmotion on terminals.  This
      {
        struct it it2;
        void *it2data = NULL;
 -      EMACS_INT start_charpos, i;
 +      ptrdiff_t start_charpos, i;
  
        /* Start at the beginning of the screen line containing IT's
         position.  This may actually move vertically backwards,
@@@ -9084,7 -9189,7 +9195,7 @@@ add_to_log (const char *format, Lisp_Ob
    Lisp_Object args[3];
    Lisp_Object msg, fmt;
    char *buffer;
 -  EMACS_INT len;
 +  ptrdiff_t len;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    USE_SAFE_ALLOCA;
  
@@@ -9133,7 -9238,7 +9244,7 @@@ message_log_maybe_newline (void
     so the buffer M must NOT point to a Lisp string.  */
  
  void
 -message_dolog (const char *m, EMACS_INT nbytes, int nlflag, int multibyte)
 +message_dolog (const char *m, ptrdiff_t nbytes, int nlflag, int multibyte)
  {
    const unsigned char *msg = (const unsigned char *) m;
  
        struct buffer *oldbuf;
        Lisp_Object oldpoint, oldbegv, oldzv;
        int old_windows_or_buffers_changed = windows_or_buffers_changed;
 -      EMACS_INT point_at_end = 0;
 -      EMACS_INT zv_at_end = 0;
 +      ptrdiff_t point_at_end = 0;
 +      ptrdiff_t zv_at_end = 0;
        Lisp_Object old_deactivate_mark, tem;
        struct gcpro gcpro1;
  
        if (multibyte
          && NILP (BVAR (current_buffer, enable_multibyte_characters)))
        {
 -        EMACS_INT i;
 +        ptrdiff_t i;
          int c, char_bytes;
          char work[1];
  
        else if (! multibyte
               && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
        {
 -        EMACS_INT i;
 +        ptrdiff_t i;
          int c, char_bytes;
          unsigned char str[MAX_MULTIBYTE_LENGTH];
          /* Convert a single-byte string to multibyte
  
        if (nlflag)
        {
 -        EMACS_INT this_bol, this_bol_byte, prev_bol, prev_bol_byte;
 +        ptrdiff_t this_bol, this_bol_byte, prev_bol, prev_bol_byte;
          printmax_t dups;
          insert_1 ("\n", 1, 1, 0, 0);
  
     value N > 1 if we should also append " [N times]".  */
  
  static intmax_t
 -message_log_check_duplicate (EMACS_INT prev_bol_byte, EMACS_INT this_bol_byte)
 +message_log_check_duplicate (ptrdiff_t prev_bol_byte, ptrdiff_t this_bol_byte)
  {
 -  EMACS_INT i;
 -  EMACS_INT len = Z_BYTE - 1 - this_bol_byte;
 +  ptrdiff_t i;
 +  ptrdiff_t len = Z_BYTE - 1 - this_bol_byte;
    int seen_dots = 0;
    unsigned char *p1 = BUF_BYTE_ADDRESS (current_buffer, prev_bol_byte);
    unsigned char *p2 = BUF_BYTE_ADDRESS (current_buffer, this_bol_byte);
     This may GC, so the buffer M must NOT point to a Lisp string.  */
  
  void
 -message2 (const char *m, EMACS_INT nbytes, int multibyte)
 +message2 (const char *m, ptrdiff_t nbytes, int multibyte)
  {
    /* First flush out any partial line written with print.  */
    message_log_maybe_newline ();
  /* The non-logging counterpart of message2.  */
  
  void
 -message2_nolog (const char *m, EMACS_INT nbytes, int multibyte)
 +message2_nolog (const char *m, ptrdiff_t nbytes, int multibyte)
  {
    struct frame *sf = SELECTED_FRAME ();
    message_enable_multibyte = multibyte;
     This function cancels echoing.  */
  
  void
 -message3 (Lisp_Object m, EMACS_INT nbytes, int multibyte)
 +message3 (Lisp_Object m, ptrdiff_t nbytes, int multibyte)
  {
    struct gcpro gcpro1;
  
     and make this cancel echoing.  */
  
  void
 -message3_nolog (Lisp_Object m, EMACS_INT nbytes, int multibyte)
 +message3_nolog (Lisp_Object m, ptrdiff_t nbytes, int multibyte)
  {
    struct frame *sf = SELECTED_FRAME ();
    message_enable_multibyte = multibyte;
@@@ -9749,12 -9854,12 +9860,12 @@@ ensure_echo_area_buffers (void
  
  static int
  with_echo_area_buffer (struct window *w, int which,
 -                     int (*fn) (EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT),
 -                     EMACS_INT a1, Lisp_Object a2, EMACS_INT a3, EMACS_INT a4)
 +                     int (*fn) (ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t),
 +                     ptrdiff_t a1, Lisp_Object a2, ptrdiff_t a3, ptrdiff_t a4)
  {
    Lisp_Object buffer;
    int this_one, the_other, clear_buffer_p, rc;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    /* If buffers aren't live, make new ones.  */
    ensure_echo_area_buffers ();
@@@ -9930,7 -10035,7 +10041,7 @@@ setup_echo_area_for_printing (int multi
  
        if (Z > BEG)
        {
 -        int count = SPECPDL_INDEX ();
 +        ptrdiff_t count = SPECPDL_INDEX ();
          specbind (Qinhibit_read_only, Qt);
          /* Note that undo recording is always disabled.  */
          del_range (BEG, Z);
  static int
  display_echo_area (struct window *w)
  {
 -  int i, no_message_p, window_height_changed_p, count;
 +  int i, no_message_p, window_height_changed_p;
  
    /* Temporarily disable garbage collections while displaying the echo
       area.  This is done because a GC can print a message itself.
       That message would modify the echo area buffer's contents while a
       redisplay of the buffer is going on, and seriously confuse
       redisplay.  */
 -  count = inhibit_garbage_collection ();
 +  ptrdiff_t count = inhibit_garbage_collection ();
  
    /* If there is no message, we must call display_echo_area_1
       nevertheless because it resizes the window.  But we will have to
     Value is non-zero if height of W was changed.  */
  
  static int
 -display_echo_area_1 (EMACS_INT a1, Lisp_Object a2, EMACS_INT a3, EMACS_INT a4)
 +display_echo_area_1 (ptrdiff_t a1, Lisp_Object a2, ptrdiff_t a3, ptrdiff_t a4)
  {
    intptr_t i1 = a1;
    struct window *w = (struct window *) i1;
@@@ -10083,7 -10188,7 +10194,7 @@@ resize_echo_area_exactly (void
     resize_mini_window returns.  */
  
  static int
 -resize_mini_window_1 (EMACS_INT a1, Lisp_Object exactly, EMACS_INT a3, EMACS_INT a4)
 +resize_mini_window_1 (ptrdiff_t a1, Lisp_Object exactly, ptrdiff_t a3, ptrdiff_t a4)
  {
    intptr_t i1 = a1;
    return resize_mini_window ((struct window *) i1, !NILP (exactly));
@@@ -10133,8 -10238,7 +10244,8 @@@ resize_mini_window (struct window *w, i
        struct it it;
        struct window *root = XWINDOW (FRAME_ROOT_WINDOW (f));
        int total_height = WINDOW_TOTAL_LINES (root) + WINDOW_TOTAL_LINES (w);
 -      int height, max_height;
 +      int height;
 +      EMACS_INT max_height;
        int unit = FRAME_LINE_HEIGHT (f);
        struct text_pos start;
        struct buffer *old_current_buffer = NULL;
@@@ -10263,7 -10367,7 +10374,7 @@@ current_message (void
  
  
  static int
 -current_message_1 (EMACS_INT a1, Lisp_Object a2, EMACS_INT a3, EMACS_INT a4)
 +current_message_1 (ptrdiff_t a1, Lisp_Object a2, ptrdiff_t a3, ptrdiff_t a4)
  {
    intptr_t i1 = a1;
    Lisp_Object *msg = (Lisp_Object *) i1;
@@@ -10342,7 -10446,7 +10453,7 @@@ check_message_stack (void
     time we display it---but don't redisplay it now.  */
  
  void
 -truncate_echo_area (EMACS_INT nchars)
 +truncate_echo_area (ptrdiff_t nchars)
  {
    if (nchars == 0)
      echo_area_buffer[0] = Qnil;
     message to at most NCHARS characters.  */
  
  static int
 -truncate_message_1 (EMACS_INT nchars, Lisp_Object a2, EMACS_INT a3, EMACS_INT a4)
 +truncate_message_1 (ptrdiff_t nchars, Lisp_Object a2, ptrdiff_t a3, ptrdiff_t a4)
  {
    if (BEG + nchars < Z)
      del_range (BEG + nchars, Z);
  
  static void
  set_message (const char *s, Lisp_Object string,
 -           EMACS_INT nbytes, int multibyte_p)
 +           ptrdiff_t nbytes, int multibyte_p)
  {
    message_enable_multibyte
      = ((s && multibyte_p)
     current.  */
  
  static int
 -set_message_1 (EMACS_INT a1, Lisp_Object a2, EMACS_INT nbytes, EMACS_INT multibyte_p)
 +set_message_1 (ptrdiff_t a1, Lisp_Object a2, ptrdiff_t nbytes, ptrdiff_t multibyte_p)
  {
    intptr_t i1 = a1;
    const char *s = (const char *) i1;
  
    if (STRINGP (string))
      {
 -      EMACS_INT nchars;
 +      ptrdiff_t nchars;
  
        if (nbytes == 0)
        nbytes = SBYTES (string);
        if (multibyte_p && NILP (BVAR (current_buffer, enable_multibyte_characters)))
        {
          /* Convert from multi-byte to single-byte.  */
 -        EMACS_INT i;
 +        ptrdiff_t i;
          int c, n;
          char work[1];
  
               && !NILP (BVAR (current_buffer, enable_multibyte_characters)))
        {
          /* Convert from single-byte to multi-byte.  */
 -        EMACS_INT i;
 +        ptrdiff_t i;
          int c, n;
          unsigned char str[MAX_MULTIBYTE_LENGTH];
  
@@@ -10612,7 -10716,7 +10723,7 @@@ echo_area_display (int update_frame_p
              /* Must update other windows.  Likewise as in other
                 cases, don't let this update be interrupted by
                 pending input.  */
 -            int count = SPECPDL_INDEX ();
 +            ptrdiff_t count = SPECPDL_INDEX ();
              specbind (Qredisplay_dont_pause, Qt);
              windows_or_buffers_changed = 1;
              redisplay_internal ();
@@@ -10789,7 -10893,7 +10900,7 @@@ store_mode_line_noprop (const char *str
  {
    const unsigned char *str = (const unsigned char *) string;
    int n = 0;
 -  EMACS_INT dummy, nbytes;
 +  ptrdiff_t dummy, nbytes;
  
    /* Copy at most PRECISION chars from STR.  */
    nbytes = strlen (string);
@@@ -10834,7 -10938,7 +10945,7 @@@ x_consider_frame_title (Lisp_Object fra
        char *title;
        ptrdiff_t len;
        struct it it;
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
  
        for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
        {
@@@ -10937,7 -11041,7 +11048,7 @@@ prepare_menu_bars (void
    if (all_windows)
      {
        Lisp_Object tail, frame;
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        /* 1 means that update_menu_bar has run its hooks
         so any further calls to update_menu_bar shouldn't do so again.  */
        int menu_bar_hooks_run = 0;
@@@ -11054,7 -11158,7 +11165,7 @@@ update_menu_bar (struct frame *f, int s
              != !NILP (w->region_showing)))
        {
          struct buffer *prev = current_buffer;
 -        int count = SPECPDL_INDEX ();
 +        ptrdiff_t count = SPECPDL_INDEX ();
  
          specbind (Qinhibit_menubar_update, Qt);
  
@@@ -11252,7 -11356,7 +11363,7 @@@ update_tool_bar (struct frame *f, int s
              != !NILP (w->region_showing)))
        {
          struct buffer *prev = current_buffer;
 -        int count = SPECPDL_INDEX ();
 +        ptrdiff_t count = SPECPDL_INDEX ();
          Lisp_Object frame, new_tool_bar;
            int new_n_tool_bar;
          struct gcpro gcpro1;
@@@ -11390,20 -11494,20 +11501,20 @@@ build_desired_tool_bar_string (struct f
                : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
        hmargin = vmargin = relief;
  
 -      if (INTEGERP (Vtool_bar_button_margin)
 -        && XINT (Vtool_bar_button_margin) > 0)
 +      if (RANGED_INTEGERP (1, Vtool_bar_button_margin,
 +                         INT_MAX - max (hmargin, vmargin)))
        {
          hmargin += XFASTINT (Vtool_bar_button_margin);
          vmargin += XFASTINT (Vtool_bar_button_margin);
        }
        else if (CONSP (Vtool_bar_button_margin))
        {
 -        if (INTEGERP (XCAR (Vtool_bar_button_margin))
 -            && XINT (XCAR (Vtool_bar_button_margin)) > 0)
 +        if (RANGED_INTEGERP (1, XCAR (Vtool_bar_button_margin),
 +                             INT_MAX - hmargin))
            hmargin += XFASTINT (XCAR (Vtool_bar_button_margin));
  
 -        if (INTEGERP (XCDR (Vtool_bar_button_margin))
 -            && XINT (XCDR (Vtool_bar_button_margin)) > 0)
 +        if (RANGED_INTEGERP (1, XCDR (Vtool_bar_button_margin),
 +                             INT_MAX - vmargin))
            vmargin += XFASTINT (XCDR (Vtool_bar_button_margin));
        }
  
@@@ -11749,7 -11853,7 +11860,7 @@@ redisplay_tool_bar (struct frame *f
      {
        int border, rows, height, extra;
  
 -      if (INTEGERP (Vtool_bar_border))
 +      if (TYPE_RANGED_INTEGERP (int, Vtool_bar_border))
        border = XINT (Vtool_bar_border);
        else if (EQ (Vtool_bar_border, Qinternal_border_width))
        border = FRAME_INTERNAL_BORDER_WIDTH (f);
@@@ -11937,7 -12041,7 +12048,7 @@@ get_tool_bar_item (struct frame *f, in
  
  void
  handle_tool_bar_click (struct frame *f, int x, int y, int down_p,
 -                     unsigned int modifiers)
 +                     int modifiers)
  {
    Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
    struct window *w = XWINDOW (f->tool_bar_window);
@@@ -12116,7 -12220,7 +12227,7 @@@ hscroll_window_tree (Lisp_Object window
          hscroll_step_abs = 0;
        }
      }
 -  else if (INTEGERP (Vhscroll_step))
 +  else if (TYPE_RANGED_INTEGERP (int, Vhscroll_step))
      {
        hscroll_step_abs = XINT (Vhscroll_step);
        if (hscroll_step_abs < 0)
                              && (w->cursor.x >= text_area_width - h_margin))))))
            {
              struct it it;
 -            int hscroll;
 +            ptrdiff_t hscroll;
              struct buffer *saved_current_buffer;
 -            EMACS_INT pt;
 +            ptrdiff_t pt;
              int wanted_x;
  
              /* Find point in a display of infinite width.  */
@@@ -12297,12 -12401,12 +12408,12 @@@ static int debug_dvpos, debug_dy
  
  /* Delta in characters and bytes for try_window_id.  */
  
 -static EMACS_INT debug_delta, debug_delta_bytes;
 +static ptrdiff_t debug_delta, debug_delta_bytes;
  
  /* Values of window_end_pos and window_end_vpos at the end of
     try_window_id.  */
  
 -static EMACS_INT debug_end_vpos;
 +static ptrdiff_t debug_end_vpos;
  
  /* Append a string to W->desired_matrix->method.  FMT is a printf
     format string.  If trace_redisplay_p is non-zero also printf the
@@@ -12352,7 -12456,7 +12463,7 @@@ debug_method_add (struct window *w, cha
  
  static inline int
  text_outside_line_unchanged_p (struct window *w,
 -                             EMACS_INT start, EMACS_INT end)
 +                             ptrdiff_t start, ptrdiff_t end)
  {
    int unchanged_p = 1;
  
@@@ -12575,10 -12679,10 +12686,10 @@@ overlay_arrow_at_row (struct it *it, st
     position.  BUF and PT are the current point buffer and position.  */
  
  static int
 -check_point_in_composition (struct buffer *prev_buf, EMACS_INT prev_pt,
 -                          struct buffer *buf, EMACS_INT pt)
 +check_point_in_composition (struct buffer *prev_buf, ptrdiff_t prev_pt,
 +                          struct buffer *buf, ptrdiff_t pt)
  {
 -  EMACS_INT start, end;
 +  ptrdiff_t start, end;
    Lisp_Object prop;
    Lisp_Object buffer;
  
@@@ -12629,7 -12733,7 +12740,7 @@@ reconsider_clip_changes (struct window 
    if (!b->clip_changed
        && BUFFERP (w->buffer) && !NILP (w->window_end_valid))
      {
 -      EMACS_INT pt;
 +      ptrdiff_t pt;
  
        if (w == XWINDOW (selected_window))
        pt = PT;
@@@ -12698,7 -12802,7 +12809,7 @@@ redisplay_internal (void
    int must_finish = 0;
    struct text_pos tlbufpos, tlendpos;
    int number_of_visible_frames;
 -  int count, count1;
 +  ptrdiff_t count, count1;
    struct frame *sf;
    int polling_stopped_here = 0;
    Lisp_Object old_frame = selected_frame;
       frames.  Zero means, only selected_window is considered.  */
    int consider_all_windows_p;
  
+   /* Non-zero means redisplay has to redisplay the miniwindow */
+   int update_miniwindow_p = 0;
    TRACE ((stderr, "redisplay_internal %d\n", redisplaying_p));
  
    /* No redisplay if running in batch mode or frame is not yet fully
          && !MINI_WINDOW_P (XWINDOW (selected_window))))
      {
        int window_height_changed_p = echo_area_display (0);
+       if (message_cleared_p)
+       update_miniwindow_p = 1;
        must_finish = 1;
  
        /* If we don't display the current message, don't clear the
  /* FIXME: this causes all frames to be updated, which seems unnecessary
     since only the current frame needs to be considered.  This function needs
     to be rewritten with two variables, consider_all_windows and
-    consider_all_frames. */
+    consider_all_frames.  */
        consider_all_windows_p = 1;
        ++windows_or_buffers_changed;
        ++update_mode_lines;
                {
                  struct glyph_row *row
                    = MATRIX_ROW (w->current_matrix, this_line_vpos + 1);
 -                EMACS_INT delta, delta_bytes;
 +                ptrdiff_t delta, delta_bytes;
  
                  /* We used to distinguish between two cases here,
                     conditioned by Z - CHARPOS (tlendpos) == ZV, for
         then we can't just move the cursor.  */
        else if (! (!NILP (Vtransient_mark_mode)
                  && !NILP (BVAR (current_buffer, mark_active)))
-              && (EQ (selected_window, BVAR (current_buffer, last_selected_window))
+              && (EQ (selected_window,
+                      BVAR (current_buffer, last_selected_window))
                   || highlight_nonselected_windows)
               && NILP (w->region_showing)
               && NILP (Vshow_trailing_whitespace)
      }
    else if (FRAME_VISIBLE_P (sf) && !FRAME_OBSCURED_P (sf))
      {
-       Lisp_Object mini_window;
+       Lisp_Object mini_window = FRAME_MINIBUF_WINDOW (sf);
        struct frame *mini_frame;
  
        displayed_buffer = XBUFFER (XWINDOW (selected_window)->buffer);
        internal_condition_case_1 (redisplay_window_1, selected_window,
                                 list_of_error,
                                 redisplay_window_error);
+       if (update_miniwindow_p)
+       internal_condition_case_1 (redisplay_window_1, mini_window,
+                                  list_of_error,
+                                  redisplay_window_error);
  
        /* Compare desired and current matrices, perform output.  */
  
@@@ -13664,18 -13780,18 +13787,18 @@@ redisplay_window_1 (Lisp_Object window
  static int
  set_cursor_from_row (struct window *w, struct glyph_row *row,
                     struct glyph_matrix *matrix,
 -                   EMACS_INT delta, EMACS_INT delta_bytes,
 +                   ptrdiff_t delta, ptrdiff_t delta_bytes,
                     int dy, int dvpos)
  {
    struct glyph *glyph = row->glyphs[TEXT_AREA];
    struct glyph *end = glyph + row->used[TEXT_AREA];
    struct glyph *cursor = NULL;
    /* The last known character position in row.  */
 -  EMACS_INT last_pos = MATRIX_ROW_START_CHARPOS (row) + delta;
 +  ptrdiff_t last_pos = MATRIX_ROW_START_CHARPOS (row) + delta;
    int x = row->x;
 -  EMACS_INT pt_old = PT - delta;
 -  EMACS_INT pos_before = MATRIX_ROW_START_CHARPOS (row) + delta;
 -  EMACS_INT pos_after = MATRIX_ROW_END_CHARPOS (row) + delta;
 +  ptrdiff_t pt_old = PT - delta;
 +  ptrdiff_t pos_before = MATRIX_ROW_START_CHARPOS (row) + delta;
 +  ptrdiff_t pos_after = MATRIX_ROW_END_CHARPOS (row) + delta;
    struct glyph *glyph_before = glyph - 1, *glyph_after = end;
    /* A glyph beyond the edge of TEXT_AREA which we should never
       touch.  */
    int string_seen = 0;
    /* Largest and smallest buffer positions seen so far during scan of
       glyph row.  */
 -  EMACS_INT bpos_max = pos_before;
 -  EMACS_INT bpos_min = pos_after;
 +  ptrdiff_t bpos_max = pos_before;
 +  ptrdiff_t bpos_min = pos_after;
    /* Last buffer position covered by an overlay string with an integer
       `cursor' property.  */
 -  EMACS_INT bpos_covered = 0;
 +  ptrdiff_t bpos_covered = 0;
    /* Non-zero means the display string on which to display the cursor
       comes from a text property, not from an overlay.  */
    int string_from_text_prop = 0;
        {
        if (BUFFERP (glyph->object))
          {
 -          EMACS_INT dpos = glyph->charpos - pt_old;
 +          ptrdiff_t dpos = glyph->charpos - pt_old;
  
            if (glyph->charpos > bpos_max)
              bpos_max = glyph->charpos;
        else if (STRINGP (glyph->object))
          {
            Lisp_Object chprop;
 -          EMACS_INT glyph_pos = glyph->charpos;
 +          ptrdiff_t glyph_pos = glyph->charpos;
  
            chprop = Fget_char_property (make_number (glyph_pos), Qcursor,
                                         glyph->object);
                   text is completely covered by display properties,
                   so that no glyph with valid buffer positions is
                   ever seen in the row.  */
 -              EMACS_INT prop_pos =
 +              ptrdiff_t prop_pos =
                  string_buffer_position_lim (glyph->object, pos_before,
                                              pos_after, 0);
  
        {
        if (BUFFERP (glyph->object))
          {
 -          EMACS_INT dpos = glyph->charpos - pt_old;
 +          ptrdiff_t dpos = glyph->charpos - pt_old;
  
            if (glyph->charpos > bpos_max)
              bpos_max = glyph->charpos;
        else if (STRINGP (glyph->object))
          {
            Lisp_Object chprop;
 -          EMACS_INT glyph_pos = glyph->charpos;
 +          ptrdiff_t glyph_pos = glyph->charpos;
  
            chprop = Fget_char_property (make_number (glyph_pos), Qcursor,
                                         glyph->object);
            if (!NILP (chprop))
              {
 -              EMACS_INT prop_pos =
 +              ptrdiff_t prop_pos =
                  string_buffer_position_lim (glyph->object, pos_before,
                                              pos_after, 0);
  
  
        if (row->ends_in_ellipsis_p && pos_after == last_pos)
        {
 -        EMACS_INT ellipsis_pos;
 +        ptrdiff_t ellipsis_pos;
  
          /* Scan back over the ellipsis glyphs.  */
          if (!row->reversed_p)
             positioned between POS_BEFORE and POS_AFTER in the
             buffer.  */
          struct glyph *start, *stop;
 -        EMACS_INT pos = pos_before;
 +        ptrdiff_t pos = pos_before;
  
          x = -1;
  
              if (STRINGP (glyph->object))
                {
                  Lisp_Object str;
 -                EMACS_INT tem;
 +                ptrdiff_t tem;
                  /* If the display property covers the newline, we
                     need to search for it one position farther.  */
 -                EMACS_INT lim = pos_after
 +                ptrdiff_t lim = pos_after
                    + (pos_after == MATRIX_ROW_END_CHARPOS (row) + delta);
  
                  string_from_text_prop = 0;
                             be a character in the string with the
                             `cursor' property, which means display
                             cursor on that character's glyph.  */
 -                        EMACS_INT strpos = glyph->charpos;
 +                        ptrdiff_t strpos = glyph->charpos;
  
                          if (tem)
                            {
                               glyph += incr)
                            {
                              Lisp_Object cprop;
 -                            EMACS_INT gpos = glyph->charpos;
 +                            ptrdiff_t gpos = glyph->charpos;
  
                              cprop = Fget_char_property (make_number (gpos),
                                                          Qcursor,
  
  static int
  try_scrolling (Lisp_Object window, int just_this_one_p,
 -             EMACS_INT arg_scroll_conservatively, EMACS_INT scroll_step,
 +             ptrdiff_t arg_scroll_conservatively, ptrdiff_t scroll_step,
               int temp_scroll_step, int last_line_misfit)
  {
    struct window *w = XWINDOW (window);
@@@ -15019,7 -15135,7 +15142,7 @@@ try_cursor_movement (Lisp_Object window
                        MATRIX_ROW (w->current_matrix, w->cursor.vpos);
                      struct glyph *g =
                        candidate->glyphs[TEXT_AREA] + w->cursor.hpos;
 -                    EMACS_INT endpos = MATRIX_ROW_END_CHARPOS (candidate);
 +                    ptrdiff_t endpos = MATRIX_ROW_END_CHARPOS (candidate);
  
                      exact_match_p =
                        (BUFFERP (g->object) && g->charpos == PT)
@@@ -15079,7 -15195,7 +15202,7 @@@ stati
  void
  set_vertical_scroll_bar (struct window *w)
  {
 -  EMACS_INT start, end, whole;
 +  ptrdiff_t start, end, whole;
  
    /* Calculate the start and end positions for the current window.
       At some point, it would be nice to choose between scrollbars
@@@ -15139,11 -15255,11 +15262,11 @@@ redisplay_window (Lisp_Object window, i
       It indicates that the buffer contents and narrowing are unchanged.  */
    int buffer_unchanged_p = 0;
    int temp_scroll_step = 0;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int rc;
    int centering_position = -1;
    int last_line_misfit = 0;
 -  EMACS_INT beg_unchanged, end_unchanged;
 +  ptrdiff_t beg_unchanged, end_unchanged;
  
    SET_TEXT_POS (lpoint, PT, PT_BYTE);
    opoint = lpoint;
       window, set up appropriate value.  */
    if (!EQ (window, selected_window))
      {
 -      EMACS_INT new_pt = XMARKER (w->pointm)->charpos;
 -      EMACS_INT new_pt_byte = marker_byte_position (w->pointm);
 +      ptrdiff_t new_pt = XMARKER (w->pointm)->charpos;
 +      ptrdiff_t new_pt_byte = marker_byte_position (w->pointm);
        if (new_pt < BEGV)
        {
          new_pt = BEGV;
        scroll_margin > 0
        ? min (scroll_margin, WINDOW_TOTAL_LINES (w) / 4)
        : 0;
 -      EMACS_INT margin_pos = CHARPOS (startp);
 +      ptrdiff_t margin_pos = CHARPOS (startp);
        Lisp_Object aggressive;
        int scrolling_up;
  
@@@ -16556,7 -16672,7 +16679,7 @@@ try_window_reusing_current_matrix (stru
  
  static struct glyph_row *find_last_unchanged_at_beg_row (struct window *);
  static struct glyph_row *find_first_unchanged_at_end_row (struct window *,
 -                                                          EMACS_INT *, EMACS_INT *);
 +                                                          ptrdiff_t *, ptrdiff_t *);
  static struct glyph_row *
  find_last_row_displaying_text (struct glyph_matrix *, struct it *,
                                 struct glyph_row *);
@@@ -16604,7 -16720,7 +16727,7 @@@ find_last_row_displaying_text (struct g
  static struct glyph_row *
  find_last_unchanged_at_beg_row (struct window *w)
  {
 -  EMACS_INT first_changed_pos = BEG + BEG_UNCHANGED;
 +  ptrdiff_t first_changed_pos = BEG + BEG_UNCHANGED;
    struct glyph_row *row;
    struct glyph_row *row_found = NULL;
    int yb = window_text_bottom_y (w);
  
  static struct glyph_row *
  find_first_unchanged_at_end_row (struct window *w,
 -                               EMACS_INT *delta, EMACS_INT *delta_bytes)
 +                               ptrdiff_t *delta, ptrdiff_t *delta_bytes)
  {
    struct glyph_row *row;
    struct glyph_row *row_found = NULL;
         corresponds to window_end_pos.  This allows us to translate
         buffer positions in the current matrix to current buffer
         positions for characters not in changed text.  */
 -      EMACS_INT Z_old =
 +      ptrdiff_t Z_old =
        MATRIX_ROW_END_CHARPOS (row) + XFASTINT (w->window_end_pos);
 -      EMACS_INT Z_BYTE_old =
 +      ptrdiff_t Z_BYTE_old =
        MATRIX_ROW_END_BYTEPOS (row) + w->window_end_bytepos;
 -      EMACS_INT last_unchanged_pos, last_unchanged_pos_old;
 +      ptrdiff_t last_unchanged_pos, last_unchanged_pos_old;
        struct glyph_row *first_text_row
        = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
  
@@@ -16779,12 -16895,12 +16902,12 @@@ sync_frame_with_window_matrix_rows (str
     containing CHARPOS or null.  */
  
  struct glyph_row *
 -row_containing_pos (struct window *w, EMACS_INT charpos,
 +row_containing_pos (struct window *w, ptrdiff_t charpos,
                    struct glyph_row *start, struct glyph_row *end, int dy)
  {
    struct glyph_row *row = start;
    struct glyph_row *best_row = NULL;
 -  EMACS_INT mindif = BUF_ZV (XBUFFER (w->buffer)) + 1;
 +  ptrdiff_t mindif = BUF_ZV (XBUFFER (w->buffer)) + 1;
    int last_y;
  
    /* If we happen to start on a header-line, skip that.  */
@@@ -16898,14 -17014,14 +17021,14 @@@ try_window_id (struct window *w
    struct glyph_row *bottom_row;
    int bottom_vpos;
    struct it it;
 -  EMACS_INT delta = 0, delta_bytes = 0, stop_pos;
 +  ptrdiff_t delta = 0, delta_bytes = 0, stop_pos;
    int dvpos, dy;
    struct text_pos start_pos;
    struct run run;
    int first_unchanged_at_end_vpos = 0;
    struct glyph_row *last_text_row, *last_text_row_at_end;
    struct text_pos start;
 -  EMACS_INT first_changed_charpos, last_changed_charpos;
 +  ptrdiff_t first_changed_charpos, last_changed_charpos;
  
  #if GLYPH_DEBUG
    if (inhibit_try_window_id)
          || (last_changed_charpos < CHARPOS (start) - 1
              && FETCH_BYTE (BYTEPOS (start) - 1) == '\n')))
      {
 -      EMACS_INT Z_old, Z_delta, Z_BYTE_old, Z_delta_bytes;
 +      ptrdiff_t Z_old, Z_delta, Z_BYTE_old, Z_delta_bytes;
        struct glyph_row *r0;
  
        /* Compute how many chars/bytes have been added to or removed
@@@ -17776,7 -17892,7 +17899,7 @@@ dump_glyph_row (struct glyph_row *row, 
               row->visible_height,
               row->ascent,
               row->phys_ascent);
 -      fprintf (stderr, "%9d %5d\t%5d\n", row->start.overlay_string_index,
 +      fprintf (stderr, "%9"pD"d %5"pD"d\t%5d\n", row->start.overlay_string_index,
               row->end.overlay_string_index,
               row->continuation_lines_width);
        fprintf (stderr, "%9"pI"d %5"pI"d\n",
@@@ -17850,7 -17966,7 +17973,7 @@@ glyphs in short form, otherwise show gl
           w->cursor.x, w->cursor.y, w->cursor.hpos, w->cursor.vpos);
    fprintf (stderr, "=============================================\n");
    dump_glyph_matrix (w->current_matrix,
 -                   NILP (glyphs) ? 0 : XINT (glyphs));
 +                   TYPE_RANGED_INTEGERP (int, glyphs) ? XINT (glyphs) : 0);
    return Qnil;
  }
  
@@@ -17873,7 -17989,7 +17996,7 @@@ GLYPH > 1 or omitted means dump glyphs 
    (Lisp_Object row, Lisp_Object glyphs)
  {
    struct glyph_matrix *matrix;
 -  int vpos;
 +  EMACS_INT vpos;
  
    CHECK_NUMBER (row);
    matrix = XWINDOW (selected_window)->current_matrix;
    if (vpos >= 0 && vpos < matrix->nrows)
      dump_glyph_row (MATRIX_ROW (matrix, vpos),
                    vpos,
 -                  INTEGERP (glyphs) ? XINT (glyphs) : 2);
 +                  TYPE_RANGED_INTEGERP (int, glyphs) ? XINT (glyphs) : 2);
    return Qnil;
  }
  
@@@ -17895,13 -18011,13 +18018,13 @@@ GLYPH > 1 or omitted means dump glyphs 
  {
    struct frame *sf = SELECTED_FRAME ();
    struct glyph_matrix *m = XWINDOW (sf->tool_bar_window)->current_matrix;
 -  int vpos;
 +  EMACS_INT vpos;
  
    CHECK_NUMBER (row);
    vpos = XINT (row);
    if (vpos >= 0 && vpos < m->nrows)
      dump_glyph_row (MATRIX_ROW (m, vpos), vpos,
 -                  INTEGERP (glyphs) ? XINT (glyphs) : 2);
 +                  TYPE_RANGED_INTEGERP (int, glyphs) ? XINT (glyphs) : 2);
    return Qnil;
  }
  
@@@ -18426,9 -18542,9 +18549,9 @@@ extend_face_to_end_of_line (struct it *
     trailing whitespace.  */
  
  static int
 -trailing_whitespace_p (EMACS_INT charpos)
 +trailing_whitespace_p (ptrdiff_t charpos)
  {
 -  EMACS_INT bytepos = CHAR_TO_BYTE (charpos);
 +  ptrdiff_t bytepos = CHAR_TO_BYTE (charpos);
    int c = 0;
  
    while (bytepos < ZV_BYTE
@@@ -18570,7 -18686,7 +18693,7 @@@ cursor_row_p (struct glyph_row *row
  
                        for ( ; glyph >= beg && EQ (glyph->object, s); --glyph)
                          {
 -                          EMACS_INT gpos = glyph->charpos;
 +                          ptrdiff_t gpos = glyph->charpos;
  
                            if (!NILP (Fget_char_property (make_number (gpos),
                                                           Qcursor, s)))
@@@ -18767,8 -18883,8 +18890,8 @@@ unproduce_glyphs (struct it *it, int n
     and ROW->maxpos.  */
  static void
  find_row_edges (struct it *it, struct glyph_row *row,
 -              EMACS_INT min_pos, EMACS_INT min_bpos,
 -              EMACS_INT max_pos, EMACS_INT max_bpos)
 +              ptrdiff_t min_pos, ptrdiff_t min_bpos,
 +              ptrdiff_t max_pos, ptrdiff_t max_bpos)
  {
    /* FIXME: Revisit this when glyph ``spilling'' in continuation
       lines' rows is implemented for bidi-reordered rows.  */
@@@ -18935,11 -19051,11 +19058,11 @@@ display_line (struct it *it
    int wrap_row_ascent IF_LINT (= 0), wrap_row_height IF_LINT (= 0);
    int wrap_row_phys_ascent IF_LINT (= 0), wrap_row_phys_height IF_LINT (= 0);
    int wrap_row_extra_line_spacing IF_LINT (= 0);
 -  EMACS_INT wrap_row_min_pos IF_LINT (= 0), wrap_row_min_bpos IF_LINT (= 0);
 -  EMACS_INT wrap_row_max_pos IF_LINT (= 0), wrap_row_max_bpos IF_LINT (= 0);
 +  ptrdiff_t wrap_row_min_pos IF_LINT (= 0), wrap_row_min_bpos IF_LINT (= 0);
 +  ptrdiff_t wrap_row_max_pos IF_LINT (= 0), wrap_row_max_bpos IF_LINT (= 0);
    int cvpos;
 -  EMACS_INT min_pos = ZV + 1, max_pos = 0;
 -  EMACS_INT min_bpos IF_LINT (= 0), max_bpos IF_LINT (= 0);
 +  ptrdiff_t min_pos = ZV + 1, max_pos = 0;
 +  ptrdiff_t min_bpos IF_LINT (= 0), max_bpos IF_LINT (= 0);
  
    /* We always start displaying at hpos zero even if hscrolled.  */
    xassert (it->hpos == 0 && it->current_x == 0);
      {                                                         \
        int composition_p = !STRINGP ((IT)->string)             \
        && ((IT)->what == IT_COMPOSITION);                      \
 -      EMACS_INT current_pos =                                 \
 +      ptrdiff_t current_pos =                                 \
        composition_p ? (IT)->cmp_it.charpos                    \
                      : IT_CHARPOS (*(IT));                     \
 -      EMACS_INT current_bpos =                                        \
 +      ptrdiff_t current_bpos =                                        \
        composition_p ? CHAR_TO_BYTE (current_pos)              \
                      : IT_BYTEPOS (*(IT));                     \
        if (current_pos < min_pos)                              \
@@@ -19663,8 -19779,8 +19786,8 @@@ See also `bidi-paragraph-direction'.  *
         use current_matrix if it is up to date, but this seems fast
         enough as it is.  */
        struct bidi_it itb;
 -      EMACS_INT pos = BUF_PT (buf);
 -      EMACS_INT bytepos = BUF_PT_BYTE (buf);
 +      ptrdiff_t pos = BUF_PT (buf);
 +      ptrdiff_t bytepos = BUF_PT_BYTE (buf);
        int c;
        void *itb_data = bidi_shelve_cache ();
  
@@@ -19952,7 -20068,7 +20075,7 @@@ display_mode_line (struct window *w, en
  {
    struct it it;
    struct face *face;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    init_iterator (&it, w, -1, -1, NULL, face_id);
    /* Don't extend on a previously drawn mode-line.
@@@ -20088,7 -20204,7 +20211,7 @@@ display_mode_element (struct it *it, in
        {
        /* A string: output it and check for %-constructs within it.  */
        unsigned char c;
 -      EMACS_INT offset = 0;
 +      ptrdiff_t offset = 0;
  
        if (SCHARS (elt) > 0
            && (!NILP (props) || risky))
               && (mode_line_target != MODE_LINE_DISPLAY
                   || it->current_x < it->last_visible_x))
          {
 -          EMACS_INT last_offset = offset;
 +          ptrdiff_t last_offset = offset;
  
            /* Advance to end of string or next format specifier.  */
            while ((c = SREF (elt, offset++)) != '\0' && c != '%')
  
            if (offset - 1 != last_offset)
              {
 -              EMACS_INT nchars, nbytes;
 +              ptrdiff_t nchars, nbytes;
  
                /* Output to end of string or up to '%'.  Field width
                   is length of string.  Don't output more than
                    break;
                  case MODE_LINE_STRING:
                    {
 -                    EMACS_INT bytepos = last_offset;
 -                    EMACS_INT charpos = string_byte_to_char (elt, bytepos);
 -                    EMACS_INT endpos = (precision <= 0
 +                    ptrdiff_t bytepos = last_offset;
 +                    ptrdiff_t charpos = string_byte_to_char (elt, bytepos);
 +                    ptrdiff_t endpos = (precision <= 0
                                          ? string_byte_to_char (elt, offset)
                                          : charpos + nchars);
  
                    break;
                  case MODE_LINE_DISPLAY:
                    {
 -                    EMACS_INT bytepos = last_offset;
 -                    EMACS_INT charpos = string_byte_to_char (elt, bytepos);
 +                    ptrdiff_t bytepos = last_offset;
 +                    ptrdiff_t charpos = string_byte_to_char (elt, bytepos);
  
                      if (precision <= 0)
                        nchars = string_byte_to_char (elt, offset) - charpos;
              }
            else /* c == '%' */
              {
 -              EMACS_INT percent_position = offset;
 +              ptrdiff_t percent_position = offset;
  
                /* Get the specified minimum width.  Zero means
                   don't pad.  */
                else if (c != 0)
                  {
                    int multibyte;
 -                  EMACS_INT bytepos, charpos;
 +                  ptrdiff_t bytepos, charpos;
                    const char *spec;
                    Lisp_Object string;
  
@@@ -20535,7 -20651,7 +20658,7 @@@ static in
  store_mode_line_string (const char *string, Lisp_Object lisp_string, int copy_string,
                        int field_width, int precision, Lisp_Object props)
  {
 -  EMACS_INT len;
 +  ptrdiff_t len;
    int n = 0;
  
    if (string != NULL)
@@@ -20636,7 -20752,7 +20759,7 @@@ are the selected window and the WINDOW'
    struct buffer *old_buffer = NULL;
    int face_id;
    int no_props = INTEGERP (face);
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object str;
    int string_start = 0;
  
     the positive integer D to BUF using a minimal field width WIDTH.  */
  
  static void
 -pint2str (register char *buf, register int width, register EMACS_INT d)
 +pint2str (register char *buf, register int width, register ptrdiff_t d)
  {
    register char *p = buf;
  
@@@ -20766,11 -20882,11 +20889,11 @@@ static const char power_letter[] 
    };
  
  static void
 -pint2hrstr (char *buf, int width, EMACS_INT d)
 +pint2hrstr (char *buf, int width, ptrdiff_t d)
  {
    /* We aim to represent the nonnegative integer D as
       QUOTIENT.TENTHS * 10 ^ (3 * EXPONENT). */
 -  EMACS_INT quotient = d;
 +  ptrdiff_t quotient = d;
    int remainder = 0;
    /* -1 means: do not use TENTHS. */
    int tenths = -1;
@@@ -21050,7 -21166,7 +21173,7 @@@ decode_mode_spec (struct window *w, reg
        return "";
        else
        {
 -        EMACS_INT col = current_column ();
 +        ptrdiff_t col = current_column ();
          w->column_number_displayed = make_number (col);
          pint2str (decode_mode_spec_buf, field_width, col);
          return decode_mode_spec_buf;
  
      case 'i':
        {
 -      EMACS_INT size = ZV - BEGV;
 +      ptrdiff_t size = ZV - BEGV;
        pint2str (decode_mode_spec_buf, field_width, size);
        return decode_mode_spec_buf;
        }
  
      case 'I':
        {
 -      EMACS_INT size = ZV - BEGV;
 +      ptrdiff_t size = ZV - BEGV;
        pint2hrstr (decode_mode_spec_buf, field_width, size);
        return decode_mode_spec_buf;
        }
  
      case 'l':
        {
 -      EMACS_INT startpos, startpos_byte, line, linepos, linepos_byte;
 -      EMACS_INT topline, nlines, height;
 -      EMACS_INT junk;
 +      ptrdiff_t startpos, startpos_byte, line, linepos, linepos_byte;
 +      ptrdiff_t topline, nlines, height;
 +      ptrdiff_t junk;
  
        /* %c and %l are ignored in `frame-title-format'.  */
        if (mode_line_target == MODE_LINE_TITLE)
        else if (nlines < height + 25 || nlines > height * 3 + 50
                 || linepos == BUF_BEGV (b))
          {
 -          EMACS_INT limit = BUF_BEGV (b);
 -          EMACS_INT limit_byte = BUF_BEGV_BYTE (b);
 -          EMACS_INT position;
 -          EMACS_INT distance =
 +          ptrdiff_t limit = BUF_BEGV (b);
 +          ptrdiff_t limit_byte = BUF_BEGV_BYTE (b);
 +          ptrdiff_t position;
 +          ptrdiff_t distance =
              (height * 2 + 30) * line_number_display_limit_width;
  
            if (startpos - distance > limit)
  
      case 'p':
        {
 -      EMACS_INT pos = marker_position (w->start);
 -      EMACS_INT total = BUF_ZV (b) - BUF_BEGV (b);
 +      ptrdiff_t pos = marker_position (w->start);
 +      ptrdiff_t total = BUF_ZV (b) - BUF_BEGV (b);
  
        if (XFASTINT (w->window_end_pos) <= BUF_Z (b) - BUF_ZV (b))
          {
               so get us a 2-digit number that is close.  */
            if (total == 100)
              total = 99;
 -          sprintf (decode_mode_spec_buf, "%2"pI"d%%", total);
 +          sprintf (decode_mode_spec_buf, "%2"pD"d%%", total);
            return decode_mode_spec_buf;
          }
        }
        /* Display percentage of size above the bottom of the screen.  */
      case 'P':
        {
 -      EMACS_INT toppos = marker_position (w->start);
 -      EMACS_INT botpos = BUF_Z (b) - XFASTINT (w->window_end_pos);
 -      EMACS_INT total = BUF_ZV (b) - BUF_BEGV (b);
 +      ptrdiff_t toppos = marker_position (w->start);
 +      ptrdiff_t botpos = BUF_Z (b) - XFASTINT (w->window_end_pos);
 +      ptrdiff_t total = BUF_ZV (b) - BUF_BEGV (b);
  
        if (botpos >= BUF_ZV (b))
          {
            if (total == 100)
              total = 99;
            if (toppos <= BUF_BEGV (b))
 -            sprintf (decode_mode_spec_buf, "Top%2"pI"d%%", total);
 +            sprintf (decode_mode_spec_buf, "Top%2"pD"d%%", total);
            else
 -            sprintf (decode_mode_spec_buf, "%2"pI"d%%", total);
 +            sprintf (decode_mode_spec_buf, "%2"pD"d%%", total);
            return decode_mode_spec_buf;
          }
        }
  
      case '@':
        {
 -      int count = inhibit_garbage_collection ();
 +      ptrdiff_t count = inhibit_garbage_collection ();
        Lisp_Object val = call1 (intern ("file-remote-p"),
                                 BVAR (current_buffer, directory));
        unbind_to (count, Qnil);
  
     Set *BYTE_POS_PTR to 1 if we found COUNT lines, 0 if we hit LIMIT.  */
  
 -static EMACS_INT
 -display_count_lines (EMACS_INT start_byte,
 -                   EMACS_INT limit_byte, EMACS_INT count,
 -                   EMACS_INT *byte_pos_ptr)
 +static ptrdiff_t
 +display_count_lines (ptrdiff_t start_byte,
 +                   ptrdiff_t limit_byte, ptrdiff_t count,
 +                   ptrdiff_t *byte_pos_ptr)
  {
    register unsigned char *cursor;
    unsigned char *base;
  
 -  register EMACS_INT ceiling;
 +  register ptrdiff_t ceiling;
    register unsigned char *ceiling_addr;
 -  EMACS_INT orig_count = count;
 +  ptrdiff_t orig_count = count;
  
    /* If we are not in selective display mode,
       check only for newlines.  */
  
  static int
  display_string (const char *string, Lisp_Object lisp_string, Lisp_Object face_string,
 -              EMACS_INT face_string_pos, EMACS_INT start, struct it *it,
 +              ptrdiff_t face_string_pos, ptrdiff_t start, struct it *it,
                int field_width, int precision, int max_x, int multibyte)
  {
    int hpos_at_start = it->hpos;
    int saved_face_id = it->face_id;
    struct glyph_row *row = it->glyph_row;
 -  EMACS_INT it_charpos;
 +  ptrdiff_t it_charpos;
  
    /* Initialize the iterator IT for iteration over STRING beginning
       with index START.  */
       FACE_STRING, if that's given.  */
    if (STRINGP (face_string))
      {
 -      EMACS_INT endptr;
 +      ptrdiff_t endptr;
        struct face *face;
  
        it->face_id
@@@ -23018,7 -23134,7 +23141,7 @@@ compute_overhangs_and_x (struct glyph_s
  
  static int
  draw_glyphs (struct window *w, int x, struct glyph_row *row,
 -           enum glyph_row_area area, EMACS_INT start, EMACS_INT end,
 +           enum glyph_row_area area, ptrdiff_t start, ptrdiff_t end,
             enum draw_glyphs_face hl, int overlaps)
  {
    struct glyph_string *head, *tail;
@@@ -24482,7 -24598,7 +24605,7 @@@ x_produce_glyphs (struct it *it
          XChar2b char2b;
          struct font_metrics *pcm;
          int font_not_found_p;
 -        EMACS_INT pos;
 +        ptrdiff_t pos;
  
          for (glyph_len = cmp->glyph_len; glyph_len > 0; glyph_len--)
            if ((c = COMPOSITION_GLYPH (cmp, glyph_len - 1)) != '\t')
@@@ -24890,7 -25006,7 +25013,7 @@@ x_insert_glyphs (struct glyph *start, i
    struct glyph_row *row;
    struct glyph *glyph;
    int frame_x, frame_y;
 -  EMACS_INT hpos;
 +  ptrdiff_t hpos;
  
    xassert (updated_window && updated_row);
    BLOCK_INPUT;
@@@ -25037,7 -25153,8 +25160,7 @@@ get_specified_cursor_type (Lisp_Object 
  
    if (CONSP (arg)
        && EQ (XCAR (arg), Qbar)
 -      && INTEGERP (XCDR (arg))
 -      && XINT (XCDR (arg)) >= 0)
 +      && RANGED_INTEGERP (0, XCDR (arg), INT_MAX))
      {
        *width = XINT (XCDR (arg));
        return BAR_CURSOR;
  
    if (CONSP (arg)
        && EQ (XCAR (arg), Qhbar)
 -      && INTEGERP (XCDR (arg))
 -      && XINT (XCDR (arg)) >= 0)
 +      && RANGED_INTEGERP (0, XCDR (arg), INT_MAX))
      {
        *width = XINT (XCDR (arg));
        return HBAR_CURSOR;
@@@ -25948,7 -26066,7 +26071,7 @@@ cursor_in_mouse_face_p (struct window *
     buffer positions change non-linearly with glyph rows.  */
  static void
  rows_from_pos_range (struct window *w,
 -                   EMACS_INT start_charpos, EMACS_INT end_charpos,
 +                   ptrdiff_t start_charpos, ptrdiff_t end_charpos,
                     Lisp_Object disp_string,
                     struct glyph_row **start, struct glyph_row **end)
  {
    for ( ; row->enabled_p && MATRIX_ROW_BOTTOM_Y (row) <= last_y; row++)
      {
        struct glyph_row *next = row + 1;
 -      EMACS_INT next_start = MATRIX_ROW_START_CHARPOS (next);
 +      ptrdiff_t next_start = MATRIX_ROW_START_CHARPOS (next);
  
        if (!next->enabled_p
          || next >= MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w)
  static void
  mouse_face_from_buffer_pos (Lisp_Object window,
                            Mouse_HLInfo *hlinfo,
 -                          EMACS_INT mouse_charpos,
 -                          EMACS_INT start_charpos,
 -                          EMACS_INT end_charpos,
 +                          ptrdiff_t mouse_charpos,
 +                          ptrdiff_t start_charpos,
 +                          ptrdiff_t end_charpos,
                            Lisp_Object before_string,
                            Lisp_Object after_string,
                            Lisp_Object disp_string)
    struct glyph_row *first = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
    struct glyph_row *r1, *r2;
    struct glyph *glyph, *end;
 -  EMACS_INT ignore, pos;
 +  ptrdiff_t ignore, pos;
    int x;
  
    xassert (NILP (disp_string) || STRINGP (disp_string));
     Value is non-zero if a glyph was found.  */
  
  static int
 -fast_find_string_pos (struct window *w, EMACS_INT pos, Lisp_Object object,
 +fast_find_string_pos (struct window *w, ptrdiff_t pos, Lisp_Object object,
                      int *hpos, int *vpos, int *x, int *y, int right_p)
  {
    int yb = window_text_bottom_y (w);
  static void
  mouse_face_from_string_pos (struct window *w, Mouse_HLInfo *hlinfo,
                            Lisp_Object object,
 -                          EMACS_INT startpos, EMACS_INT endpos)
 +                          ptrdiff_t startpos, ptrdiff_t endpos)
  {
    int yb = window_text_bottom_y (w);
    struct glyph_row *r;
@@@ -26689,8 -26807,8 +26812,8 @@@ on_hot_spot_p (Lisp_Object hot_spot, in
        {
          struct Lisp_Vector *v = XVECTOR (XCDR (hot_spot));
          Lisp_Object *poly = v->contents;
 -        int n = v->header.size;
 -        int i;
 +        ptrdiff_t n = v->header.size;
 +        ptrdiff_t i;
          int inside = 0;
          Lisp_Object lx, ly;
          int x0, y0;
@@@ -26768,9 -26886,7 +26891,9 @@@ Returns the alist element for the firs
    CHECK_NUMBER (x);
    CHECK_NUMBER (y);
  
 -  return find_hot_spot (map, XINT (x), XINT (y));
 +  return find_hot_spot (map,
 +                      clip_to_bounds (INT_MIN, XINT (x), INT_MAX),
 +                      clip_to_bounds (INT_MIN, XINT (y), INT_MAX));
  }
  
  
@@@ -26829,7 -26945,7 +26952,7 @@@ note_mode_line_or_margin_highlight (Lis
    Cursor cursor = No_Cursor;
    Lisp_Object pointer = Qnil;
    int dx, dy, width, height;
 -  EMACS_INT charpos;
 +  ptrdiff_t charpos;
    Lisp_Object string, object = Qnil;
    Lisp_Object pos, help;
  
          int gpos;
          int gseq_length;
          int total_pixel_width;
 -        EMACS_INT begpos, endpos, ignore;
 +        ptrdiff_t begpos, endpos, ignore;
  
          int vpos, hpos;
  
@@@ -27199,14 -27315,14 +27322,14 @@@ note_mouse_highlight (struct frame *f, 
        && XFASTINT (w->last_overlay_modified) == BUF_OVERLAY_MODIFF (b))
      {
        int hpos, vpos, dx, dy, area = LAST_AREA;
 -      EMACS_INT pos;
 +      ptrdiff_t pos;
        struct glyph *glyph;
        Lisp_Object object;
        Lisp_Object mouse_face = Qnil, position;
        Lisp_Object *overlay_vec = NULL;
        ptrdiff_t i, noverlays;
        struct buffer *obuf;
 -      EMACS_INT obegv, ozv;
 +      ptrdiff_t obegv, ozv;
        int same_region;
  
        /* Find the glyph under X/Y.  */
              /* The mouse-highlighting comes from a display string
                 with a mouse-face.  */
              Lisp_Object s, e;
 -            EMACS_INT ignore;
 +            ptrdiff_t ignore;
  
              s = Fprevious_single_property_change
                (make_number (pos + 1), Qmouse_face, object, Qnil);
                  /* If we are on a display string with no mouse-face,
                     check if the text under it has one.  */
                  struct glyph_row *r = MATRIX_ROW (w->current_matrix, vpos);
 -                EMACS_INT start = MATRIX_ROW_START_CHARPOS (r);
 +                ptrdiff_t start = MATRIX_ROW_START_CHARPOS (r);
                  pos = string_buffer_position (object, start);
                  if (pos > 0)
                    {
        else
          {
            Lisp_Object obj = glyph->object;
 -          EMACS_INT charpos = glyph->charpos;
 +          ptrdiff_t charpos = glyph->charpos;
  
            /* Try text properties.  */
            if (STRINGP (obj)
                       see if the buffer text ``under'' it does.  */
                    struct glyph_row *r
                      = MATRIX_ROW (w->current_matrix, vpos);
 -                  EMACS_INT start = MATRIX_ROW_START_CHARPOS (r);
 -                  EMACS_INT p = string_buffer_position (obj, start);
 +                  ptrdiff_t start = MATRIX_ROW_START_CHARPOS (r);
 +                  ptrdiff_t p = string_buffer_position (obj, start);
                    if (p > 0)
                      {
                        help = Fget_char_property (make_number (p),
          if (NILP (pointer))
            {
              Lisp_Object obj = glyph->object;
 -            EMACS_INT charpos = glyph->charpos;
 +            ptrdiff_t charpos = glyph->charpos;
  
              /* Try text properties.  */
              if (STRINGP (obj)
                         see if the buffer text ``under'' it does.  */
                      struct glyph_row *r
                        = MATRIX_ROW (w->current_matrix, vpos);
 -                    EMACS_INT start = MATRIX_ROW_START_CHARPOS (r);
 -                    EMACS_INT p = string_buffer_position (obj, start);
 +                    ptrdiff_t start = MATRIX_ROW_START_CHARPOS (r);
 +                    ptrdiff_t p = string_buffer_position (obj, start);
                      if (p > 0)
                        pointer = Fget_char_property (make_number (p),
                                                      Qpointer, w->buffer);
@@@ -28850,30 -28966,29 +28973,22 @@@ init_xdisp (void
  
  /* Platform-independent portion of hourglass implementation. */
  
- /* Return non-zero if hourglass timer has been started or hourglass is
-    shown.  */
- int
- hourglass_started (void)
- {
-   return hourglass_shown_p || hourglass_atimer != NULL;
- }
  /* Cancel a currently active hourglass timer, and start a new one.  */
  void
  start_hourglass (void)
  {
  #if defined (HAVE_WINDOW_SYSTEM)
    EMACS_TIME delay;
 -  int secs, usecs = 0;
 +  int secs = DEFAULT_HOURGLASS_DELAY, usecs = 0;
  
    cancel_hourglass ();
  
 -  if (INTEGERP (Vhourglass_delay)
 -      && XINT (Vhourglass_delay) > 0)
 -    secs = XFASTINT (Vhourglass_delay);
 -  else if (FLOATP (Vhourglass_delay)
 -         && XFLOAT_DATA (Vhourglass_delay) > 0)
 +  if (NUMBERP (Vhourglass_delay))
      {
 -      Lisp_Object tem;
 -      tem = Ftruncate (Vhourglass_delay, Qnil);
 -      secs = XFASTINT (tem);
 -      usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
 +      double duration = extract_float (Vhourglass_delay);
 +      if (0 < duration)
 +      duration_to_sec_usec (duration, &secs, &usecs);
      }
 -  else
 -    secs = DEFAULT_HOURGLASS_DELAY;
  
    EMACS_SET_SECS_USECS (delay, secs, usecs);
    hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
diff --combined src/xfns.c
@@@ -136,7 -136,7 +136,7 @@@ char *gray_bitmap_bits = gray_bits
  
  /* Nonzero if using X.  */
  
static int x_in_use;
+ int x_in_use;
  
  static Lisp_Object Qnone;
  static Lisp_Object Qsuppress_icon;
@@@ -1200,7 -1200,7 +1200,7 @@@ x_set_menu_bar_lines (struct frame *f, 
    if (FRAME_MINIBUF_ONLY_P (f))
      return;
  
 -  if (INTEGERP (value))
 +  if (TYPE_RANGED_INTEGERP (int, value))
      nlines = XINT (value);
    else
      nlines = 0;
@@@ -1286,8 -1286,8 +1286,8 @@@ x_set_tool_bar_lines (struct frame *f, 
    if (FRAME_MINIBUF_ONLY_P (f))
      return;
  
 -  /* Use VALUE only if an integer >= 0.  */
 -  if (INTEGERP (value) && XINT (value) >= 0)
 +  /* Use VALUE only if an int >= 0.  */
 +  if (RANGED_INTEGERP (0, value, INT_MAX))
      nlines = XFASTINT (value);
    else
      nlines = 0;
@@@ -2439,7 -2439,6 +2439,6 @@@ x_window (struct frame *f, long window_
  
    /* Do some needed geometry management.  */
    {
-     ptrdiff_t len;
      char *tem, shell_position[sizeof "=x++" + 4 * INT_STRLEN_BOUND (int)];
      Arg gal[10];
      int gac = 0;
          }
      }
  
-     len = strlen (shell_position) + 1;
      /* We don't free this because we don't know whether
         it is safe to free it while the frame exists.
         It isn't worth the trouble of arranging to free it
         when the frame is deleted.  */
-     tem = (char *) xmalloc (len);
-     strncpy (tem, shell_position, len);
+     tem = (char *) xstrdup (shell_position);
      XtSetArg (gal[gac], XtNgeometry, tem); gac++;
      XtSetValues (shell_widget, gal, gac);
    }
@@@ -2787,8 -2784,8 +2784,8 @@@ x_icon (struct frame *f, Lisp_Object pa
    icon_y = x_frame_get_and_record_arg (f, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
    if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
      {
 -      CHECK_NUMBER (icon_x);
 -      CHECK_NUMBER (icon_y);
 +      CHECK_TYPE_RANGED_INTEGER (int, icon_x);
 +      CHECK_TYPE_RANGED_INTEGER (int, icon_y);
      }
    else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
      error ("Both left and top icon corners of icon must be specified");
@@@ -3079,7 -3076,7 +3076,7 @@@ This function is an internal primitive-
    int minibuffer_only = 0;
    long window_prompting = 0;
    int width, height;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    Lisp_Object display;
    struct x_display_info *dpyinfo = NULL;
       could get an infloop in next_frame since the frame is not yet in
       Vframe_list.  */
    {
 -    int count2 = SPECPDL_INDEX ();
 +    ptrdiff_t count2 = SPECPDL_INDEX ();
      record_unwind_protect (unwind_create_frame_1, inhibit_lisp_code);
      inhibit_lisp_code = Qt;
  
@@@ -4224,11 -4221,11 +4221,11 @@@ FRAME.  Default is to change on the edi
    if (! NILP (format))
      {
        CHECK_NUMBER (format);
 -      element_format = XFASTINT (format);
  
 -      if (element_format != 8 && element_format != 16
 -          && element_format != 32)
 +      if (XINT (format) != 8 && XINT (format) != 16
 +          && XINT (format) != 32)
          error ("FORMAT must be one of 8, 16 or 32");
 +      element_format = XINT (format);
      }
  
    if (CONSP (value))
@@@ -4586,7 -4583,7 +4583,7 @@@ x_create_tip_frame (struct x_display_in
    Lisp_Object frame;
    Lisp_Object name;
    int width, height;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3;
    int face_change_count_before = face_change_count;
    Lisp_Object buffer;
@@@ -4983,7 -4980,7 +4980,7 @@@ Text larger than the specified size is 
    int i, width, height, seen_reversed_p;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    int old_windows_or_buffers_changed = windows_or_buffers_changed;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    specbind (Qinhibit_redisplay, Qt);
  
    w->left_col = w->top_line = make_number (0);
  
    if (CONSP (Vx_max_tooltip_size)
 -      && INTEGERP (XCAR (Vx_max_tooltip_size))
 -      && XINT (XCAR (Vx_max_tooltip_size)) > 0
 -      && INTEGERP (XCDR (Vx_max_tooltip_size))
 -      && XINT (XCDR (Vx_max_tooltip_size)) > 0)
 +      && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
 +      && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
      {
        w->total_cols = XCAR (Vx_max_tooltip_size);
        w->total_lines = XCDR (Vx_max_tooltip_size);
@@@ -5240,7 -5239,7 +5237,7 @@@ DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hi
  Value is t if tooltip was open, nil otherwise.  */)
    (void)
  {
 -  int count;
 +  ptrdiff_t count;
    Lisp_Object deleted, frame, timer;
    struct gcpro gcpro1, gcpro2;
  
@@@ -5382,7 -5381,7 +5379,7 @@@ Otherwise, if ONLY-DIR-P is non-nil, th
    Arg al[10];
    int ac = 0;
    XmString dir_xmstring, pattern_xmstring;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
  
    check_x ();
@@@ -5551,7 -5550,7 +5548,7 @@@ Otherwise, if ONLY-DIR-P is non-nil, th
    char *fn;
    Lisp_Object file = Qnil;
    Lisp_Object decoded_file;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
    char *cdef_file;
  
@@@ -5614,7 -5613,7 +5611,7 @@@ If FRAME is omitted or nil, it default
    Lisp_Object font_param;
    char *default_name = NULL;
    struct gcpro gcpro1, gcpro2;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    check_x ();
  
diff --combined src/xselect.c
@@@ -81,13 -81,13 +81,13 @@@ static Lisp_Object clean_local_selectio
  
  #ifdef TRACE_SELECTION
  #define TRACE0(fmt) \
 -  fprintf (stderr, "%d: " fmt "\n", getpid ())
 +  fprintf (stderr, "%"pMd": " fmt "\n", (printmax_t) getpid ())
  #define TRACE1(fmt, a0) \
 -  fprintf (stderr, "%d: " fmt "\n", getpid (), a0)
 +  fprintf (stderr, "%"pMd": " fmt "\n", (printmax_t) getpid (), a0)
  #define TRACE2(fmt, a0, a1) \
 -  fprintf (stderr, "%d: " fmt "\n", getpid (), a0, a1)
 +  fprintf (stderr, "%"pMd": " fmt "\n", (printmax_t) getpid (), a0, a1)
  #define TRACE3(fmt, a0, a1, a2) \
 -  fprintf (stderr, "%d: " fmt "\n", getpid (), a0, a1, a2)
 +  fprintf (stderr, "%"pMd": " fmt "\n", (printmax_t) getpid (), a0, a1, a2)
  #else
  #define TRACE0(fmt)           (void) 0
  #define TRACE1(fmt, a0)               (void) 0
@@@ -392,6 -392,7 +392,6 @@@ x_get_local_selection (Lisp_Object sele
  {
    Lisp_Object local_value;
    Lisp_Object handler_fn, value, check;
 -  int count;
  
    local_value = LOCAL_SELECTION (selection_symbol, dpyinfo);
  
        /* Don't allow a quit within the converter.
         When the user types C-g, he would be surprised
         if by luck it came during a converter.  */
 -      count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        specbind (Qinhibit_quit, Qt);
  
        CHECK_SYMBOL (target_type);
@@@ -602,7 -603,7 +602,7 @@@ x_reply_selection_request (struct input
    Window window = SELECTION_EVENT_REQUESTOR (event);
    ptrdiff_t bytes_remaining;
    int max_bytes = selection_quantum (display);
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct selection_data *cs;
  
    reply->type = SelectionNotify;
@@@ -791,7 -792,7 +791,7 @@@ x_handle_selection_request (struct inpu
    Atom property = SELECTION_EVENT_PROPERTY (event);
    Lisp_Object local_selection_data;
    int success = 0;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    GCPRO2 (local_selection_data, target_symbol);
  
    if (!dpyinfo) goto DONE;
@@@ -930,6 -931,7 +930,7 @@@ x_convert_selection (struct input_even
  
    /* Otherwise, record the converted selection to binary.  */
    cs = xmalloc (sizeof (struct selection_data));
+   cs->data = NULL;
    cs->nofree = 1;
    cs->property = property;
    cs->wait_object = NULL;
@@@ -1139,7 -1141,7 +1140,7 @@@ static voi
  wait_for_property_change (struct prop_location *location)
  {
    int secs, usecs;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    if (property_change_reply_object)
      abort ();
@@@ -1700,7 -1702,7 +1701,7 @@@ selection_data_to_lisp_data (Display *d
        v = Fmake_vector (make_number (size / 2), make_number (0));
        for (i = 0; i < size / 2; i++)
        {
 -        EMACS_INT j = ((short *) data) [i];
 +        short j = ((short *) data) [i];
          Faset (v, make_number (i), make_number (j));
        }
        return v;
@@@ -2621,12 -2623,13 +2622,12 @@@ x_send_client_event (Lisp_Object displa
    if (x_check_property_data (values) == -1)
      error ("Bad data in VALUES, must be number, cons or string");
  
 -  event.xclient.type = ClientMessage;
 -  event.xclient.format = XFASTINT (format);
 -
 -  if (event.xclient.format != 8 && event.xclient.format != 16
 -      && event.xclient.format != 32)
 +  if (XINT (format) != 8 && XINT (format) != 16 && XINT (format) != 32)
      error ("FORMAT must be one of 8, 16 or 32");
  
 +  event.xclient.type = ClientMessage;
 +  event.xclient.format = XINT (format);
 +
    if (FRAMEP (dest) || NILP (dest))
      {
        struct frame *fdest = check_x_frame (dest);
diff --combined src/xterm.c
@@@ -256,11 -256,7 +256,7 @@@ static Time last_user_time
  /* Incremented by XTread_socket whenever it really tries to read
     events.  */
  
- #ifdef __STDC__
  static int volatile input_signal_count;
- #else
- static int input_signal_count;
- #endif
  
  /* Used locally within XTread_socket.  */
  
@@@ -3700,23 -3696,24 +3696,23 @@@ x_find_modifier_meanings (struct x_disp
  /* Convert between the modifier bits X uses and the modifier bits
     Emacs uses.  */
  
 -EMACS_INT
 +int
  x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
  {
 -  EMACS_INT mod_meta = meta_modifier;
 -  EMACS_INT mod_alt  = alt_modifier;
 -  EMACS_INT mod_hyper = hyper_modifier;
 -  EMACS_INT mod_super = super_modifier;
 +  int mod_meta = meta_modifier;
 +  int mod_alt  = alt_modifier;
 +  int mod_hyper = hyper_modifier;
 +  int mod_super = super_modifier;
    Lisp_Object tem;
  
    tem = Fget (Vx_alt_keysym, Qmodifier_value);
 -  if (INTEGERP (tem)) mod_alt = XINT (tem);
 +  if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
    tem = Fget (Vx_meta_keysym, Qmodifier_value);
 -  if (INTEGERP (tem)) mod_meta = XINT (tem);
 +  if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
    tem = Fget (Vx_hyper_keysym, Qmodifier_value);
 -  if (INTEGERP (tem)) mod_hyper = XINT (tem);
 +  if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
    tem = Fget (Vx_super_keysym, Qmodifier_value);
 -  if (INTEGERP (tem)) mod_super = XINT (tem);
 -
 +  if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
  
    return (  ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
              | ((state & ControlMask)                  ? ctrl_modifier : 0)
  static int
  x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
  {
 -  int mod_meta = meta_modifier;
 -  int mod_alt  = alt_modifier;
 -  int mod_hyper = hyper_modifier;
 -  int mod_super = super_modifier;
 +  EMACS_INT mod_meta = meta_modifier;
 +  EMACS_INT mod_alt  = alt_modifier;
 +  EMACS_INT mod_hyper = hyper_modifier;
 +  EMACS_INT mod_super = super_modifier;
  
    Lisp_Object tem;
  
@@@ -6491,10 -6488,9 +6487,10 @@@ handle_one_xevent (struct x_display_inf
  
          /* Now non-ASCII.  */
          if (HASH_TABLE_P (Vx_keysym_table)
 -            && (NATNUMP (c = Fgethash (make_number (keysym),
 -                                       Vx_keysym_table,
 -                                       Qnil))))
 +            && (c = Fgethash (make_number (keysym),
 +                              Vx_keysym_table,
 +                              Qnil),
 +                NATNUMP (c)))
            {
              inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
                                ? ASCII_KEYSTROKE_EVENT
@@@ -7772,7 -7768,7 +7768,7 @@@ x_connection_closed (Display *dpy, cons
  {
    struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
    Lisp_Object frame, tail;
 -  int idx = SPECPDL_INDEX ();
 +  ptrdiff_t idx = SPECPDL_INDEX ();
  
    error_msg = (char *) alloca (strlen (error_message) + 1);
    strcpy (error_msg, error_message);
@@@ -10146,7 -10142,7 +10142,7 @@@ x_term_init (Lisp_Object display_name, 
  
    /* Set the name of the terminal. */
    terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
-   strncpy (terminal->name, SSDATA (display_name), SBYTES (display_name));
+   memcpy (terminal->name, SSDATA (display_name), SBYTES (display_name));
    terminal->name[SBYTES (display_name)] = 0;
  
  #if 0
diff --combined src/xterm.h
@@@ -779,7 -779,8 +779,7 @@@ enu
  struct scroll_bar
  {
    /* These fields are shared by all vectors.  */
 -  EMACS_INT size_from_Lisp_Vector_struct;
 -  struct Lisp_Vector *next_from_Lisp_Vector_struct;
 +  struct vectorlike_header header;
  
    /* The window we're a scroll bar for.  */
    Lisp_Object window;
    unsigned int fringe_extended_p : 1;
  };
  
 -/* The number of elements a vector holding a struct scroll_bar needs.  */
 -#define SCROLL_BAR_VEC_SIZE                                   \
 -  ((sizeof (struct scroll_bar)                                        \
 -    - sizeof (EMACS_INT) - sizeof (struct Lisp_Vector *))     \
 -   / sizeof (Lisp_Object))
 -
  /* Turning a lisp vector value into a pointer to a struct scroll_bar.  */
  #define XSCROLL_BAR(vec) ((struct scroll_bar *) XVECTOR (vec))
  
@@@ -989,7 -996,7 +989,7 @@@ extern void x_mouse_leave (struct x_dis
  #ifdef USE_X_TOOLKIT
  extern int x_dispatch_event (XEvent *, Display *);
  #endif
 -extern EMACS_INT x_x_to_emacs_modifiers (struct x_display_info *, int);
 +extern int x_x_to_emacs_modifiers (struct x_display_info *, int);
  extern int x_display_pixel_height (struct x_display_info *);
  extern int x_display_pixel_width (struct x_display_info *);
  
@@@ -1031,6 -1038,7 +1031,7 @@@ extern void x_clipboard_manager_save_al
  
  extern struct x_display_info * check_x_display_info (Lisp_Object);
  extern Lisp_Object x_get_focus_frame (struct frame *);
+ extern int x_in_use;
  
  #ifdef USE_GTK
  extern int xg_set_icon (struct frame *, Lisp_Object);