]> code.delx.au - gnu-emacs/commitdiff
Merge from trunk.
authorPaul Eggert <eggert@cs.ucla.edu>
Sun, 11 Dec 2011 00:56:50 +0000 (16:56 -0800)
committerPaul Eggert <eggert@cs.ucla.edu>
Sun, 11 Dec 2011 00:56:50 +0000 (16:56 -0800)
56 files changed:
1  2 
src/ChangeLog
src/alloc.c
src/bidi.c
src/buffer.c
src/buffer.h
src/callint.c
src/casetab.c
src/ccl.c
src/character.c
src/character.h
src/charset.c
src/chartab.c
src/coding.c
src/coding.h
src/data.c
src/dbusbind.c
src/dired.c
src/dispextern.h
src/dispnew.c
src/emacs.c
src/eval.c
src/fileio.c
src/fns.c
src/font.c
src/font.h
src/fontset.c
src/frame.c
src/fringe.c
src/ftfont.c
src/gtkutil.c
src/image.c
src/intervals.c
src/keyboard.c
src/lisp.h
src/lread.c
src/minibuf.c
src/nsfns.m
src/nsfont.m
src/print.c
src/process.c
src/puresize.h
src/search.c
src/sound.c
src/sysdep.c
src/term.c
src/textprop.c
src/w32fns.c
src/w32menu.c
src/window.c
src/xdisp.c
src/xfaces.c
src/xfns.c
src/xmenu.c
src/xselect.c
src/xterm.c
src/xterm.h

diff --combined src/ChangeLog
index 4cec277fb36497a57f3f933d90bb5f99581c8e4e,20fd021a3760a2ad620ef1f5f6192f6962a8b52a..f525535e4d8ffce60cb0e220e2321546d2e6a9a0
- 2011-11-18  Paul Eggert  <eggert@cs.ucla.edu>
++2011-12-11  Paul Eggert  <eggert@cs.ucla.edu>
 +
 +      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):
++      (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.
 +      * 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.
 +      * 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.
 +      (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.
 +      * 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.
 +
- 2011-11-18  Paul Eggert  <eggert@cs.ucla.edu>
+ 2011-12-10  Jan Djärv  <jan.h.d@swipnet.se>
  
-       Fix minor problems found by static checking.
-       * dispextern.h, xdisp.c (row_hash): Declare extern only if XASSERTS.
-       * dispnew.c (verify_row_hash): Now static.
+       * xterm.c (x_term_init): Move call to gdk_window_add_filter before
+       gtk_init (Bug#10100).
+ 2011-12-10  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (RECORD_MAX_MIN_POS): Use IT->cmp_it.charpos only if
+       IT->string is nil.  (Bug#10263)
+ 2011-12-10  Jan Djärv  <jan.h.d@swipnet.se>
+       * nsterm.h (x_free_frame_resources): Declare.
+       * nsfns.m (ns_get_defaults_value): New function (Bug#10103).
+       (Fns_get_resource, x_get_string_resource): Call ns_get_defaults_value.
+       * nsterm.h (ns_get_defaults_value): Declare.
+       * nsterm.m (ns_default): Call ns_get_defaults_value.
+ 2011-12-09  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (try_scrolling): Don't set scroll_down_p if dy is zero.
+       (Bug#10170)
+ 2011-12-09  YAMAMOTO Mitsuharu  <mituharu@math.s.chiba-u.ac.jp>
+       * unexelf.c (unexec) [NS_IMPL_GNUSTEP]: Take account of the case
+       that where the value of an _OBJC_* symbol points to is in the .bss
+       section (Bug#10240).
+ 2011-12-08  Kazuhiro Ito  <kzhr@d1.dion.ne.jp>  (tiny change)
+       * coding.c (encode_coding_ccl): Check (charbuf < charbuf_end)
+       after the loop to call ccl_driver at least once (Bug#8619).
+ 2011-12-08  Kenichi Handa  <handa@m17n.org>
+       * ftfont.c (get_adstyle_property): Fix previous change
+       (Bug#10233).
+ 2011-12-07  Juanma Barranquero  <lekktu@gmail.com>
+       * w32.c (init_environment): If no_site_lisp, remove site-lisp
+       dirs from the default value of EMACSLOADPATH (bug#10208).
+ 2011-12-07  Glenn Morris  <rgm@gnu.org>
+       * lread.c (init_lread): If no_site_lisp, exclude site-lisp/ in
+       installation and source directories as well.  (Bug#10208)
+ 2011-12-06  Chong Yidong  <cyd@gnu.org>
+       * minibuf.c (Fread_from_minibuffer): Doc fix (Bug#10228).
+ 2011-12-06  Glenn Morris  <rgm@gnu.org>
+       * process.c (start_process_unwind): Treat any pid <= 0, except -2,
+       as an error, not just -1.  (Bug#10217)
+ 2011-12-05  Chong Yidong  <cyd@gnu.org>
+       * keyboard.c (process_special_events): New function.
+       (swallow_events, Finput_pending_p): Use it (Bug#10195).
+ 2011-12-05  Paul Eggert  <eggert@cs.ucla.edu>
+       * coding.c (encode_designation_at_bol): Don't use uninitialized
+       local variable (Bug#9318).
+ 2011-12-05  Kenichi Handa  <handa@m17n.org>
+       * ftfont.c (get_adstyle_property): If the font is not BDF nor PCF,
+       return Qnil (Bug#8046, Bug#10193).
+ 2011-12-05  Kenichi Handa  <handa@m17n.org>
+       * coding.c (encode_designation_at_bol): New args charbuf_end and
+       dst.  Return the number of produced bytes.  Callers changed.
+       (coding_set_source): Return how many bytes coding->source was
+       relocated.
+       (coding_set_destination): Return how many bytes
+       coding->destination was relocated.
+       (CODING_DECODE_CHAR, CODING_ENCODE_CHAR, CODING_CHAR_CHARSET)
+       (CODING_CHAR_CHARSET_P): Adjusted for the avove changes.
+ 2011-12-05  Kazuhiro Ito  <kzhr@d1.dion.ne.jp>  (tiny change)
+       * coding.c (CODING_CHAR_CHARSET_P): New macro.
+       (encode_coding_emacs_mule, encode_coding_iso_2022): Use the above
+       macro (Bug#9318).
+ 2011-12-05  Andreas Schwab  <schwab@linux-m68k.org>
+       The following changes are to fix Bug#9318.
+       * coding.c (CODING_ENCODE_CHAR, CODING_CHAR_CHARSET): New macros.
+       (encode_coding_emacs_mule, ENCODE_ISO_CHARACTER)
+       (encode_coding_iso_2022, encode_coding_sjis)
+       (encode_coding_big5, encode_coding_charset): Use the above macros.
+ 2011-12-05  Juanma Barranquero  <lekktu@gmail.com>
+       * lisp.h (process_quit_flag): Fix external declaration.
+ 2011-12-04  Stefan Monnier  <monnier@iro.umontreal.ca>
+       Don't macro-inline non-performance-critical code.
+       * eval.c (process_quit_flag): New function.
+       * lisp.h (QUIT): Use it.
+ 2011-12-04  Jan Djärv  <jan.h.d@swipnet.se>
+       * nsfns.m (get_geometry_from_preferences): New function.
+       (Fx_create_frame): Call get_geometry_from_preferences (Bug#10103).
+ 2011-12-04  Andreas Schwab  <schwab@linux-m68k.org>
+       * emacs.c (Qkill_emacs): Define.
+       (syms_of_emacs): Initialize it.
+       * keyboard.c (interrupt_signal): Don't call Fkill_emacs here, set
+       Qquit_flag to `kill-emacs' instead.
+       (quit_throw_to_read_char): Add parameter `from_signal'.
+       All callers changed.  Call Fkill_emacs if requested and safe.
+       * lisp.h (QUIT): Call Fkill_emacs if requested.
+ 2011-12-03  Jan Djärv  <jan.h.d@swipnet.se>
+       * widget.c (update_wm_hints): Return if wmshell is null.
+       (widget_update_wm_size_hints): New function.
+       * widget.h (widget_update_wm_size_hints): Declare.
+       * xterm.c (x_wm_set_size_hint): If USE_X_TOOLKIT, call
+       widget_update_wm_size_hints (Bug#10104).
+ 2011-12-03  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (handle_invisible_prop): If the invisible text ends just
+       before a newline, prepare the bidi iterator for consuming the
+       newline, and keep the current paragraph direction.  (Bug#10183)
+       (redisplay_window): Don't let `margin' become negative.  (Bug#10192)
+ 2011-12-02  Juri Linkov  <juri@jurta.org>
+       * search.c (Fword_search_regexp): New Lisp function created from
+       `wordify'.  Change type of arg `lax' from `int' to `Lisp_Object'.
+       (Fword_search_backward, Fword_search_forward)
+       (Fword_search_backward_lax, Fword_search_forward_lax):
+       Use `Fword_search_regexp' instead of `wordify'.  Doc fix.
+       (syms_of_search): Define `Sword_search_regexp'.  (Bug#10145)
+ 2011-12-01  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * fileio.c (Finsert_file_contents): Move after-change-function call
+       to before the "handled:" label, since all "goto handled" appear in
+       cases where the *-change-functions have already been properly called
+       (bug#10117).
+ 2011-12-01  Andreas Schwab  <schwab@linux-m68k.org>
+       * keyboard.c (interrupt_signal): Don't call kill-emacs when
+       waiting for input.  (Bug#10169)
+ 2011-11-30  Eli Zaretskii  <eliz@gnu.org>
+       * dispnew.c (adjust_glyph_matrix): Remove the assertion that
+       verifies glyph row's hash code--we have just reallocated the
+       glyphs, so their contents can be complete garbage.  (Bug#10164)
+ 2011-11-30  Juanma Barranquero  <lekktu@gmail.com>
+       * dispnew.c (adjust_glyph_matrix) [XASSERTS]: Add missing check.
+ 2011-11-30  Eli Zaretskii  <eliz@gnu.org>
+       * dispnew.c (adjust_glyph_matrix) [XASSERTS]: Ensure ROW's
+       attributes are tested _before_ calling verify_row_hash, to protect
+       against GCC re-ordering of the tests.  (Bug#10164)
+ 2011-11-29  Jan Djärv  <jan.h.d@swipnet.se>
+       * xterm.h (struct x_output): net_wm_state_hidden_seen is new.
+       * xterm.c (handle_one_xevent): Only set async_visible and friends
+       if net_wm_state_hidden_seen is non-zero (Bug#10002)
+       (get_current_wm_state): Set net_wm_state_hidden_seen to 1 if
+       _NET_WM_STATE_HIDDEN is in NET_WM_STATE.
+ 2011-11-28  Paul Eggert  <eggert@cs.ucla.edu>
+       Remove GCPRO-related macros that exist only to avoid shadowing locals.
+       * lisp.h (GCPRO1_VAR, GCPRO2_VAR, GCPRO3_VAR, GCPRO4_VAR, GCPRO5_VAR)
+       (GCPRO6_VAR, UNGCPRO_VAR): Remove.  See
+       <http://lists.gnu.org/archive/html/emacs-diffs/2011-11/msg00265.html>.
+       All uses changed to use GCPRO1 etc.
+       (GCPRO1, GCPRO2, GCPRO3, GCPRO4, GCPRO5, GCPRO6, UNGCPRO):
+       Revert to old implementation (i.e., before 2011-03-11).
+ 2011-11-28  YAMAMOTO Mitsuharu  <mituharu@math.s.chiba-u.ac.jp>
+       * dispnew.c (scrolling_window): Truncate overlaps in copy destination
+       of scroll runs so as to avoid assigning disabled bogus rows and
+       unnecessary graphics copy operations.
+ 2011-11-27  Eli Zaretskii  <eliz@gnu.org>
+       * s/ms-w32.h (utimbuf) [_MSC_VER]: Don't define.
+       (snprintf) [_MSC_VER]: Redirect to _snprintf.
+       (strtoll) [_MSC_VER]: Redirect to _strtoi64.
+       (malloc, free, realloc, calloc): Redirect to e_* only when
+       compiling Emacs.
+       * lisp.h (GCTYPEBITS): Move before first use.
+       (ALIGN_GCTYPEBITS) [_MSC_VER]: Define.
+       (DECL_ALIGN) [_MSC_VER]: Use it, as MSVC doesn't like bit ops in
+       this macro definition.
+       * s/ms-w32.h (tzname): Redirect to _tzname for all values of
+       _MSC_VER.
+ 2011-11-27  Jan Djärv  <jan.h.d@swipnet.se>
+       * gtkutil.c (xg_create_frame_widgets):
+       Call gtk_window_set_has_resize_grip (FALSE) if that function is
+       present with Gtk+ 2.0.
+ 2011-11-26  Paul Eggert  <eggert@cs.ucla.edu>
+       * fileio.c (Finsert_file_contents): Undo previous change; see
+       <http://lists.gnu.org/archive/html/emacs-diffs/2011-11/msg00265.html>.
+ 2011-11-26  Paul Eggert  <eggert@cs.ucla.edu>
+       Rename locals to avoid shadowing.
+       * fileio.c (Finsert_file_contents):
+       Rename inner 'gcpro1' to 'inner_gcpro1' to avoid shadowing.
+       * process.c (wait_reading_process_output):
+       Rename inner 'proc' to 'p' to avoid shadowing.
+       Indent for consistency with usual Emacs style.
+ 2011-11-25  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (redisplay_window): If cursor row is not fully visible
+       after recentering, and scroll-conservatively is set to a large
+       number, scroll window by a few more lines to make the cursor fully
+       visible and out of scroll-margin.  (Bug#10105)
+       (start_display): Don't move to the next line if the display should
+       start at a newline that is part of a display vector or an overlay
+       string.  (Bug#10119)
+ 2011-11-24  Juri Linkov  <juri@jurta.org>
+       * image.c (imagemagick_load_image): Move `MagickSetResolution' down
+       after the `MagickPingImage' call.  (Bug#10112)
+ 2011-11-23  Chong Yidong  <cyd@gnu.org>
+       * window.c (Fcoordinates_in_window_p): Accept only live windows.
+ 2011-11-23  Martin Rudalics  <rudalics@gmx.at>
+       * buffer.c (Fkill_buffer): Run replace_buffer_in_windows before
+       making another buffer current.  (Bug#10114)
+ 2011-11-23  Glenn Morris  <rgm@gnu.org>
+       * font.c (font_find_for_lface) [HAVE_NS]: Ignore case.  (Bug#2526)
+ 2011-11-23  Chong Yidong  <cyd@gnu.org>
+       * xdisp.c (compute_stop_pos): Check validity of end_charpos before
+       using it (Bug#5984).
+ 2011-11-22  Eli Zaretskii  <eliz@gnu.org>
+       * dispnew.c (adjust_glyph_matrix): Don't verify hash code of mode-
+       and header-lines, as they don't have one computed for them.
+       (Bug#10098)
+       * .gdbinit (prow): Make displayed values more self-explaining.
+       Add row's hash code.
+ 2011-11-21  Lars Magne Ingebrigtsen  <larsi@gnus.org>
+       * process.c (wait_reading_process_output): Fix asynchrounous
+       GnuTLS socket handling on some versions of the GnuTLS library.
+       (wait_reading_process_output): Add comment and URL.
+ 2011-11-21  Jan Djärv  <jan.h.d@swipnet.se>
+       * xterm.c (x_clear_frame): Reinstate the XClearWindow call.
+ 2011-11-21  Chong Yidong  <cyd@gnu.org>
+       * window.c (Fnext_window, Fprevious_window): Doc fix.
+ 2011-11-20  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * window.c (get_phys_cursor_glyph): Fix Lisp_Object/int mixup.
+ 2011-11-20  Juanma Barranquero  <lekktu@gmail.com>
+       * nsfont.m (syms_of_nsfont) <ns-reg-to-script>: Fix typo.
+ 2011-11-20  Martin Rudalics  <rudalics@gmx.at>
+       * window.c (Fset_window_combination_limit): Rename argument
+       STATUS to LIMIT.
+       (Vwindow_combination_limit): Remove "status" from doc-string.
+ 2011-11-20  Andreas Schwab  <schwab@linux-m68k.org>
+       * m/ibms390.h: Remove.
+       * m/ibms390x.h: Don't include "ibms390.h".
+ 2011-11-20  Stefan Monnier  <monnier@iro.umontreal.ca>
+       * fileio.c (Finsert_file_contents): Add missing gcpro1 variable.
+       Suggested by Dmitry Antipov <dmantipov@yandex.ru>.
+ 2011-11-20  Juanma Barranquero  <lekktu@gmail.com>
+       * casetab.c (Fset_case_table):
+       * charset.c (Fcharset_after): Fix typos.
+ 2011-11-20  Paul Eggert  <eggert@cs.ucla.edu>
+       Standardize on VIRT_ADDR_VARIES behavior (Bug#10042).
+       Otherwise, valgrind does not work on some platforms.
+       Problem reported by Andreas Schwab in
+       <http://lists.gnu.org/archive/html/emacs-devel/2011-11/msg00081.html>.
+       * puresize.h (pure, PURE_P): Always behave as if VIRT_ADDR_VARIES
+       is set, removing the need for VIRT_ADDRESS_VARIES.
+       (PURE_P): Use a more-efficient implementation that needs just one
+       comparison, not two: on x86-64 with GCC 4.6.2, this cut down the
+       number of instructions from 6 (xorl, cmpq, jge, xorl, cmpq, setge)
+       to 4 (xorl, subq, cmpq, setbe).
+       * alloc.c (pure): Always extern now, since that's the
+       VIRT_ADDR_VARIES behavior.
+       (PURE_POINTER_P): Use a single comparison, not two, for
+       consistency with the new puresize.h.
+       * lisp.h (PNTR_COMPARISON_TYPE): Remove; no longer needed.
+       * m/ibms390.h, m/intel386.h, m/template.h, s/cygwin.h, s/hpux10-20.h:
+       Remove VIRT_ADDR_VARIES no longer needed.
+ 2011-11-19  Eli Zaretskii  <eliz@gnu.org>
+       * xdisp.c (x_write_glyphs, draw_phys_cursor_glyph)
+       (erase_phys_cursor, update_window_cursor, show_mouse_face)
+       (cursor_in_mouse_face_p): If the cursor position is out of bounds,
+       behave as if the cursor position were at the window margin.
+       * window.c (get_phys_cursor_glyph): If the window is hscrolled,
+       and the cursor position is out of bounds, behave as if the cursor
+       position were at the window margin.  (Bug#10075)
+ 2011-11-18  Chong Yidong  <cyd@gnu.org>
+       * window.c (Fwindow_combination_limit): Make first argument
+       non-optional, since it is meaningless for live windows like the
+       selected window.
  
  2011-11-18  Dmitry Antipov  <dmantipov@yandex.ru>
  
        * xdisp.c (display_line): Move the call to
        highlight_trailing_whitespace before the call to
        compute_line_metrics, since the latter needs to see the final
-       faces of all the glyphs to compute ROW's hash value.  Fixes
-       assertion violations in row_equal_p.  (Bug#10035)
+       faces of all the glyphs to compute ROW's hash value.
+       Fixes assertion violations in row_equal_p.  (Bug#10035)
  
  2011-11-14  Juanma Barranquero  <lekktu@gmail.com>
  
  2011-11-08  Chong Yidong  <cyd@gnu.org>
  
        * window.c (Fwindow_left_column, Fwindow_top_line): Doc fix.
-       (Fwindow_body_height, Fwindow_body_width): Move from Lisp.  Signal
-       an error if not a live window.
+       (Fwindow_body_height, Fwindow_body_width): Move from Lisp.
+       Signal an error if not a live window.
        (Fwindow_total_width, Fwindow_total_height): Move from Lisp.
        (Fwindow_total_size, Fwindow_body_size): Move to Lisp.
  
        (x_destroy_window): Move code to x_free_frame_resources.
  
        * xfns.c (unwind_create_frame): Fix comment.
-       (Fx_create_frame, x_create_tip_frame): Move
-       terminal->reference_count++ just before making the frame
+       (Fx_create_frame, x_create_tip_frame):
+       Move terminal->reference_count++ just before making the frame
        official. Move initialization of image_cache_refcount and
        dpyinfo_refcount before calling init_frame_faces (Bug#9943).
  
        * xdisp.c (mouse_face_from_buffer_pos): Fix a typo in a comment.
        Don't stop backward scan on the continuation glyph, even though
        its CHARPOS is positive.
-       (mouse_face_from_buffer_pos, note_mouse_highlight): Rename
-       cover_string to disp_string.
+       (mouse_face_from_buffer_pos, note_mouse_highlight):
+       Rename cover_string to disp_string.
  
  2011-11-01  Martin Rudalics  <rudalics@gmx.at>
  
  
  2011-04-08  T.V. Raman  <tv.raman.tv@gmail.com>  (tiny change)
  
-       * xml.c (parse_region): Avoid creating spurious whiespace nodes.
+       * xml.c (parse_region): Avoid creating spurious whitespace nodes.
  
  2011-04-08  Chong Yidong  <cyd@stupidchicken.com>
  
        * keyboard.c (Fcommand_execute, Fsuspend_emacs, safe_run_hooks_1):
        Use Frun_hooks.
        (command_loop_1): Use Frun_hooks.  Call safe_run_hooks
-       unconditionnaly since it does the check itself.
+       unconditionally since it does the check itself.
  
  2011-03-23  Paul Eggert  <eggert@cs.ucla.edu>
  
        (xg_set_widget_bg): New function.
        (delete_cb): New function.
        (xg_create_frame_widgets): Connect delete-event to delete_cb.
-       Call xg_set_widget_bg.  Only set backgrund pixmap for ! HAVE_GTK3
+       Call xg_set_widget_bg.  Only set background pixmap for ! HAVE_GTK3
        (xg_set_background_color): Call xg_set_widget_bg.
        (xg_set_frame_icon): Call xg_get_pixbuf_from_pix_and_mask.
        (xg_create_scroll_bar): vadj is a GtkAdjustment for HAVE_GTK3.
diff --combined src/alloc.c
index f21f0b4fa3a549a0564e4f116b01dc3e947d6c22,96d63f53cf96f923a7e8deda29602cfb042f0c72..84a84df3597fbc4e307a04fc561d85b10445142e
@@@ -203,9 -203,6 +203,6 @@@ static int malloc_hysteresis
     remapping on more recent systems because this is less important
     nowadays than in the days of small memories and timesharing.  */
  
- #ifndef VIRT_ADDR_VARIES
- static
- #endif
  EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
  #define PUREBEG (char *) pure
  
@@@ -222,18 -219,15 +219,15 @@@ static ptrdiff_t pure_bytes_used_before
  /* Value is non-zero if P points into pure space.  */
  
  #define PURE_POINTER_P(P)                                     \
-      (((PNTR_COMPARISON_TYPE) (P)                             \
-        < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size))       \
-       && ((PNTR_COMPARISON_TYPE) (P)                          \
-         >= (PNTR_COMPARISON_TYPE) purebeg))
+   ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
  
  /* 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.  */
@@@ -384,7 -378,7 +378,7 @@@ 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 mark_stack (void);
  static int live_vector_p (struct mem_node *, void *);
@@@ -470,7 -464,7 +464,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
@@@ -1640,7 -1634,7 +1634,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
@@@ -1765,24 -1759,24 +1759,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 */
  
@@@ -1826,10 -1820,10 +1820,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)
@@@ -1852,7 -1846,7 +1846,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. */
@@@ -1998,7 -1992,7 +1992,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 ();
@@@ -2243,7 -2237,7 +2237,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
@@@ -2373,8 -2367,7 +2367,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;
  
@@@ -2918,7 -2911,7 +2912,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;
@@@ -2974,7 -2967,7 +2968,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;
@@@ -3038,14 -3031,14 +3032,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;
  
@@@ -4731,14 -4724,14 +4725,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;
@@@ -4830,7 -4823,7 +4824,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;
@@@ -4877,7 -4870,7 +4871,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;
@@@ -4921,8 -4914,8 +4915,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)
@@@ -4974,10 -4967,10 +4968,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;
@@@ -5002,7 -4995,7 +4996,7 @@@ returns nil, because real GC can't be d
    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);
      }
@@@ -5382,8 -5375,8 +5376,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 */
@@@ -6264,7 -6257,7 +6258,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/bidi.c
index e8f2df89a9e4fce33e225895733db21a08f935d2,e0337927ec50d22aed04646c47e1842e1619f47d..bd78a5eff29a155ba1f9fadc042ec1cb6c5e369f
@@@ -51,7 -51,7 +51,7 @@@ along with GNU Emacs.  If not, see <htt
  
     A note about references to UAX#9 rules: if the reference says
     something like "X9/Retaining", it means that you need to refer to
-    rule X9 and to its modifications decribed in the "Implementation
+    rule X9 and to its modifications described in the "Implementation
     Notes" section of UAX#9, under "Retaining Format Codes".  */
  
  #include <config.h>
@@@ -204,7 -204,7 +204,7 @@@ bidi_mirror_char (int c
    val = CHAR_TABLE_REF (bidi_mirror_table, c);
    if (INTEGERP (val))
      {
 -      int v = XINT (val);
 +      EMACS_INT v = XINT (val);
  
        if (v < 0 || v > MAX_CHAR)
        abort ();
@@@ -378,7 -378,7 +378,7 @@@ bidi_cache_fetch_state (ptrdiff_t idx, 
     resolved levels in cached states.  DIR, if non-zero, means search
     in that direction from the last cache hit.  */
  static inline ptrdiff_t
 -bidi_cache_search (EMACS_INT charpos, int level, int dir)
 +bidi_cache_search (ptrdiff_t charpos, int level, int dir)
  {
    ptrdiff_t i, i_start;
  
@@@ -562,7 -562,7 +562,7 @@@ bidi_cache_iterator_state (struct bidi_
  }
  
  static inline bidi_type_t
 -bidi_cache_find (EMACS_INT charpos, int level, struct bidi_it *bidi_it)
 +bidi_cache_find (ptrdiff_t charpos, int level, struct bidi_it *bidi_it)
  {
    ptrdiff_t i = bidi_cache_search (charpos, level, bidi_it->scan_dir);
  
@@@ -795,7 -795,7 +795,7 @@@ bidi_set_paragraph_end (struct bidi_it 
  
  /* Initialize the bidi iterator from buffer/string position CHARPOS.  */
  void
 -bidi_init_it (EMACS_INT charpos, EMACS_INT bytepos, int frame_window_p,
 +bidi_init_it (ptrdiff_t charpos, ptrdiff_t bytepos, int frame_window_p,
              struct bidi_it *bidi_it)
  {
    if (! bidi_initialized)
@@@ -867,11 -867,11 +867,11 @@@ bidi_line_init (struct bidi_it *bidi_it
     are zero-based character positions in S, BEGBYTE is byte position
     corresponding to BEG.  UNIBYTE, if non-zero, means S is a unibyte
     string.  */
 -static inline EMACS_INT
 -bidi_count_bytes (const unsigned char *s, const EMACS_INT beg,
 -                const EMACS_INT begbyte, const EMACS_INT end, int unibyte)
 +static inline ptrdiff_t
 +bidi_count_bytes (const unsigned char *s, const ptrdiff_t beg,
 +                const ptrdiff_t begbyte, const ptrdiff_t end, int unibyte)
  {
 -  EMACS_INT pos = beg;
 +  ptrdiff_t pos = beg;
    const unsigned char *p = s + begbyte, *start = p;
  
    if (unibyte)
     character from the current buffer.  UNIBYTE non-zero means S is a
     unibyte string.  */
  static inline int
 -bidi_char_at_pos (EMACS_INT bytepos, const unsigned char *s, int unibyte)
 +bidi_char_at_pos (ptrdiff_t bytepos, const unsigned char *s, int unibyte)
  {
    if (s)
      {
     string to iterate, or NULL if iterating over a buffer or a Lisp
     string; in the latter case, STRING->lstring is the Lisp string.  */
  static inline int
 -bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
 +bidi_fetch_char (ptrdiff_t bytepos, ptrdiff_t charpos, ptrdiff_t *disp_pos,
                 int *disp_prop, struct bidi_string_data *string,
 -               int frame_window_p, EMACS_INT *ch_len, EMACS_INT *nchars)
 +               int frame_window_p, ptrdiff_t *ch_len, ptrdiff_t *nchars)
  {
    int ch;
 -  EMACS_INT endpos
 +  ptrdiff_t endpos
      = (string->s || STRINGP (string->lstring)) ? string->schars : ZV;
    struct text_pos pos;
  
      }
    else if (charpos >= *disp_pos && *disp_prop)
      {
 -      EMACS_INT disp_end_pos;
 +      ptrdiff_t disp_end_pos;
  
        /* We don't expect to find ourselves in the middle of a display
         property.  Hopefully, it will never be needed.  */
     following the buffer position, -1 if position is at the beginning
     of a new paragraph, or -2 if position is neither at beginning nor
     at end of a paragraph.  */
 -static EMACS_INT
 -bidi_at_paragraph_end (EMACS_INT charpos, EMACS_INT bytepos)
 +static ptrdiff_t
 +bidi_at_paragraph_end (ptrdiff_t charpos, ptrdiff_t bytepos)
  {
    Lisp_Object sep_re;
    Lisp_Object start_re;
 -  EMACS_INT val;
 +  ptrdiff_t val;
  
    sep_re = paragraph_separate_re;
    start_re = paragraph_start_re;
     Value is the byte position of the paragraph's beginning, or
     BEGV_BYTE if paragraph_start_re is still not found after looking
     back MAX_PARAGRAPH_SEARCH lines in the buffer.  */
 -static EMACS_INT
 -bidi_find_paragraph_start (EMACS_INT pos, EMACS_INT pos_byte)
 +static ptrdiff_t
 +bidi_find_paragraph_start (ptrdiff_t pos, ptrdiff_t pos_byte)
  {
    Lisp_Object re = paragraph_start_re;
 -  EMACS_INT limit = ZV, limit_byte = ZV_BYTE;
 -  EMACS_INT n = 0;
 +  ptrdiff_t limit = ZV, limit_byte = ZV_BYTE;
 +  ptrdiff_t n = 0;
  
    while (pos_byte > BEGV_BYTE
         && n++ < MAX_PARAGRAPH_SEARCH
  void
  bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, int no_default_p)
  {
 -  EMACS_INT bytepos = bidi_it->bytepos;
 +  ptrdiff_t bytepos = bidi_it->bytepos;
    int string_p = bidi_it->string.s != NULL || STRINGP (bidi_it->string.lstring);
 -  EMACS_INT pstartbyte;
 +  ptrdiff_t pstartbyte;
    /* Note that begbyte is a byte position, while end is a character
       position.  Yes, this is ugly, but we are trying to avoid costly
       calls to BYTE_TO_CHAR and its ilk.  */
 -  EMACS_INT begbyte = string_p ? 0 : BEGV_BYTE;
 -  EMACS_INT end = string_p ? bidi_it->string.schars : ZV;
 +  ptrdiff_t begbyte = string_p ? 0 : BEGV_BYTE;
 +  ptrdiff_t end = string_p ? bidi_it->string.schars : ZV;
  
    /* Special case for an empty buffer. */
    if (bytepos == begbyte && bidi_it->charpos == end)
    else if (dir == NEUTRAL_DIR)        /* P2 */
      {
        int ch;
 -      EMACS_INT ch_len, nchars;
 -      EMACS_INT pos, disp_pos = -1;
 +      ptrdiff_t ch_len, nchars;
 +      ptrdiff_t pos, disp_pos = -1;
        int disp_prop = 0;
        bidi_type_t type;
        const unsigned char *s;
              bidi_it->paragraph_dir = L2R; /* P3 and HL1 */
            else
              {
 -              EMACS_INT prevpbyte = pstartbyte;
 -              EMACS_INT p = BYTE_TO_CHAR (pstartbyte), pbyte = pstartbyte;
 +              ptrdiff_t prevpbyte = pstartbyte;
 +              ptrdiff_t p = BYTE_TO_CHAR (pstartbyte), pbyte = pstartbyte;
  
                /* Find the beginning of the previous paragraph, if any.  */
                while (pbyte > BEGV_BYTE && prevpbyte >= pstartbyte)
@@@ -1527,7 -1527,7 +1527,7 @@@ bidi_resolve_explicit (struct bidi_it *
  {
    int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
    int new_level  = bidi_resolve_explicit_1 (bidi_it);
 -  EMACS_INT eob = bidi_it->string.s ? bidi_it->string.schars : ZV;
 +  ptrdiff_t eob = bidi_it->string.s ? bidi_it->string.schars : ZV;
    const unsigned char *s
      = (STRINGP (bidi_it->string.lstring)
         ? SDATA (bidi_it->string.lstring)
@@@ -1615,7 -1615,7 +1615,7 @@@ bidi_resolve_weak (struct bidi_it *bidi
    int next_char;
    bidi_type_t type_of_next;
    struct bidi_it saved_it;
 -  EMACS_INT eob
 +  ptrdiff_t eob
      = ((STRINGP (bidi_it->string.lstring) || bidi_it->string.s)
         ? bidi_it->string.schars : ZV);
  
            }
          else if (bidi_it->next_en_pos >=0)
            {
 -            EMACS_INT en_pos = bidi_it->charpos + bidi_it->nchars;
 +            ptrdiff_t en_pos = bidi_it->charpos + bidi_it->nchars;
              const unsigned char *s = (STRINGP (bidi_it->string.lstring)
                                        ? SDATA (bidi_it->string.lstring)
                                        : bidi_it->string.s);
@@@ -2032,11 -2032,11 +2032,11 @@@ bidi_level_of_next_char (struct bidi_i
    bidi_type_t type;
    int level, prev_level = -1;
    struct bidi_saved_info next_for_neutral;
 -  EMACS_INT next_char_pos = -2;
 +  ptrdiff_t next_char_pos = -2;
  
    if (bidi_it->scan_dir == 1)
      {
 -      EMACS_INT eob
 +      ptrdiff_t eob
        = ((bidi_it->string.s || STRINGP (bidi_it->string.lstring))
           ? bidi_it->string.schars : ZV);
  
        && bidi_it->next_for_ws.type == UNKNOWN_BT)
      {
        int ch;
 -      EMACS_INT clen = bidi_it->ch_len;
 -      EMACS_INT bpos = bidi_it->bytepos;
 -      EMACS_INT cpos = bidi_it->charpos;
 -      EMACS_INT disp_pos = bidi_it->disp_pos;
 -      EMACS_INT nc = bidi_it->nchars;
 +      ptrdiff_t clen = bidi_it->ch_len;
 +      ptrdiff_t bpos = bidi_it->bytepos;
 +      ptrdiff_t cpos = bidi_it->charpos;
 +      ptrdiff_t disp_pos = bidi_it->disp_pos;
 +      ptrdiff_t nc = bidi_it->nchars;
        struct bidi_string_data bs = bidi_it->string;
        bidi_type_t chtype;
        int fwp = bidi_it->frame_window_p;
@@@ -2411,7 -2411,7 +2411,7 @@@ bidi_move_to_visually_next (struct bidi
        bidi_it->separator_limit = bidi_it->string.schars;
        else if (bidi_it->bytepos < ZV_BYTE)
        {
 -        EMACS_INT sep_len
 +        ptrdiff_t sep_len
            = bidi_at_paragraph_end (bidi_it->charpos + bidi_it->nchars,
                                     bidi_it->bytepos + bidi_it->ch_len);
          if (bidi_it->nchars <= 0)
@@@ -2477,6 -2477,6 +2477,6 @@@ bidi_dump_cached_states (void
    fputs ("\n", stderr);
    fputs ("pos ", stderr);
    for (i = 0; i < bidi_cache_idx; i++)
 -    fprintf (stderr, "%*"pI"d", ndigits, bidi_cache[i].charpos);
 +    fprintf (stderr, "%*"pD"d", ndigits, bidi_cache[i].charpos);
    fputs ("\n", stderr);
  }
diff --combined src/buffer.c
index f1ce9f4ec47ca595e4ea06915cd8ee5bd0c4dd4a,a482493fac76cdcabf5837c30a5ff88acbcb9880..afa7e915429386c1c8222fbfff38bcf009592d9a
@@@ -155,7 -155,7 +155,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.  */
@@@ -423,7 -423,7 +423,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));
@@@ -858,8 -858,8 +858,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))
@@@ -1475,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 ());
        UNGCPRO;
      }
  
-   /* Make this buffer not be current.
+   /* Run replace_buffer_in_windows before making another buffer current
+      since set-window-buffer-start-and-point will refuse to make another
+      buffer current if the selected window does not show the current
+      buffer.  (Bug#10114) */
+   replace_buffer_in_windows (buffer);
+      /* Make this buffer not be current.
       In the process, notice if this is the sole visible buffer
       and give up if so.  */
    if (b == current_buffer)
  
    /* These may run Lisp code and into infinite loops (if someone
       insisted on circular lists) so allow quitting here.  */
-   replace_buffer_in_windows (buffer);
    frames_discard_buffer (buffer);
  
    clear_charpos_cache (b);
  
    /* Reset the local variables, so that this buffer's local values
       won't be protected from GC.  They would be protected
-      if they happened to remain encached in their symbols.
+      if they happened to remain cached in their symbols.
       This gets rid of them for certain.  */
    swap_out_buffer_local_variables (b);
    reset_buffer_local_variables (b, 1);
@@@ -1746,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);
@@@ -1958,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
        {
@@@ -2055,12 -2061,12 +2060,12 @@@ DEFUN ("buffer-swap-text", Fbuffer_swap
                          (POINTER_TYPE **) &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);
@@@ -2153,7 -2159,7 +2158,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;
@@@ -2480,7 -2486,7 +2485,7 @@@ swap_out_buffer_local_variables (struc
        Lisp_Object sym = XCAR (XCAR (alist));
        eassert (XSYMBOL (sym)->redirect == SYMBOL_LOCALIZED);
        /* Need not do anything if some other buffer's binding is
-        now encached.  */
+        now cached.  */
        if (EQ (SYMBOL_BLV (XSYMBOL (sym))->where, buffer))
        {
          /* Symbol is set up for this buffer's old local value:
  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;
  };
  
@@@ -2950,7 -2956,7 +2955,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',
@@@ -3618,11 -3624,11 +3623,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;
      }
@@@ -3671,8 -3677,7 +3676,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);
@@@ -3778,7 -3786,7 +3783,7 @@@ DEFUN ("delete-overlay", Fdelete_overla
  {
    Lisp_Object buffer;
    struct buffer *b;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    CHECK_OVERLAY (overlay);
  
@@@ -3869,7 -3877,7 +3874,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);
@@@ -3917,7 -3925,7 +3922,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);
@@@ -3955,7 -3963,7 +3960,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);
@@@ -4011,11 -4019,9 +4016,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
@@@ -4082,7 -4088,7 +4087,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,
@@@ -4143,7 -4149,7 +4148,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));
@@@ -4263,7 -4269,7 +4268,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)
@@@ -4399,7 -4405,7 +4404,7 @@@ static int mmap_fd_1
  
  static int mmap_page_size;
  
- /* 1 means mmap has been intialized.  */
+ /* 1 means mmap has been initialized.  */
  
  static int mmap_initialized_p;
  
  #define MMAP_ALLOCATED_P(start, end) 1
  #endif
  
- /* Perform necessary intializations for the use of mmap.  */
+ /* Perform necessary initializations for the use of mmap.  */
  
  static void
  mmap_init (void)
@@@ -4794,7 -4800,7 +4799,7 @@@ alloc_buffer_text (struct buffer *b, pt
     shrink it.  */
  
  void
 -enlarge_buffer_text (struct buffer *b, EMACS_INT delta)
 +enlarge_buffer_text (struct buffer *b, ptrdiff_t delta)
  {
    POINTER_TYPE *p;
    ptrdiff_t nbytes = (BUF_Z_BYTE (b) - BUF_BEG_BYTE (b) + BUF_GAP_SIZE (b) + 1
diff --combined src/buffer.h
index 323c85a0c7710f6b2f0b5fe59abc3baf16ea41f6,fa65a4b81fdbcf81c58ca5ce109e80b03f8374cd..e2d4b555e1142a81302ef43ef8e9c5797309a7b9
@@@ -245,12 -245,12 +245,12 @@@ along with GNU Emacs.  If not, see <htt
  #define BUF_TEMP_SET_PT(buffer, position) \
    (temp_set_point ((buffer), (position)))
  
 -extern void set_point (EMACS_INT);
 -extern void temp_set_point (struct buffer *, EMACS_INT);
 -extern void set_point_both (EMACS_INT, EMACS_INT);
 +extern void set_point (ptrdiff_t);
 +extern void temp_set_point (struct buffer *, ptrdiff_t);
 +extern void set_point_both (ptrdiff_t, ptrdiff_t);
  extern void temp_set_point_both (struct buffer *,
 -                               EMACS_INT, EMACS_INT);
 -extern void enlarge_buffer_text (struct buffer *, EMACS_INT);
 +                               ptrdiff_t, ptrdiff_t);
 +extern void enlarge_buffer_text (struct buffer *, ptrdiff_t);
  
  \f
  /* Macros for setting the BEGV, ZV or PT of a given buffer.
@@@ -438,38 -438,38 +438,38 @@@ struct buffer_tex
         into a buffer's text to functions that malloc.  */
      unsigned char *beg;
  
 -    EMACS_INT gpt;            /* Char pos of gap in buffer.  */
 -    EMACS_INT z;              /* Char pos of end of buffer.  */
 -    EMACS_INT gpt_byte;               /* Byte pos of gap in buffer.  */
 -    EMACS_INT z_byte;         /* Byte pos of end of buffer.  */
 -    EMACS_INT gap_size;               /* Size of buffer's gap.  */
 -    int modiff;                       /* This counts buffer-modification events
 +    ptrdiff_t gpt;            /* Char pos of gap in buffer.  */
 +    ptrdiff_t z;              /* Char pos of end of buffer.  */
 +    ptrdiff_t gpt_byte;               /* Byte pos of gap in buffer.  */
 +    ptrdiff_t z_byte;         /* Byte pos of end of buffer.  */
 +    ptrdiff_t gap_size;               /* Size of buffer's gap.  */
 +    EMACS_INT modiff;         /* This counts buffer-modification events
                                   for this buffer.  It is incremented for
                                   each such event, and never otherwise
                                   changed.  */
 -    int chars_modiff;           /* This is modified with character change
 +    EMACS_INT chars_modiff;   /* This is modified with character change
                                   events for this buffer.  It is set to
                                   modiff for each such event, and never
                                   otherwise changed.  */
 -    int save_modiff;          /* Previous value of modiff, as of last
 +    EMACS_INT save_modiff;    /* Previous value of modiff, as of last
                                   time buffer visited or saved a file.  */
  
 -    int overlay_modiff;               /* Counts modifications to overlays.  */
 +    EMACS_INT overlay_modiff; /* Counts modifications to overlays.  */
  
      /* Minimum value of GPT - BEG since last redisplay that finished.  */
 -    EMACS_INT beg_unchanged;
 +    ptrdiff_t beg_unchanged;
  
      /* Minimum value of Z - GPT since last redisplay that finished.  */
 -    EMACS_INT end_unchanged;
 +    ptrdiff_t end_unchanged;
  
      /* MODIFF as of last redisplay that finished; if it matches MODIFF,
         beg_unchanged and end_unchanged contain no useful information.  */
 -    int unchanged_modified;
 +    EMACS_INT unchanged_modified;
  
      /* BUF_OVERLAY_MODIFF of current buffer, as of last redisplay that
         finished; if it matches BUF_OVERLAY_MODIFF, beg_unchanged and
         end_unchanged contain no useful information.  */
 -    int overlay_unchanged_modified;
 +    EMACS_INT overlay_unchanged_modified;
  
      /* Properties of this buffer's text.  */
      INTERVAL intervals;
@@@ -525,17 -525,17 +525,17 @@@ struct buffe
    struct buffer_text *text;
  
    /* Char position of point in buffer.  */
 -  EMACS_INT pt;
 +  ptrdiff_t pt;
    /* Byte position of point in buffer.  */
 -  EMACS_INT pt_byte;
 +  ptrdiff_t pt_byte;
    /* Char position of beginning of accessible range.  */
 -  EMACS_INT begv;
 +  ptrdiff_t begv;
    /* Byte position of beginning of accessible range.  */
 -  EMACS_INT begv_byte;
 +  ptrdiff_t begv_byte;
    /* Char position of end of accessible range.  */
 -  EMACS_INT zv;
 +  ptrdiff_t zv;
    /* Byte position of end of accessible range.  */
 -  EMACS_INT zv_byte;
 +  ptrdiff_t zv_byte;
  
    /* In an indirect buffer, this points to the base buffer.
       In an ordinary buffer, it is 0.  */
       modtime is actually set.  */
    off_t modtime_size;
    /* The value of text->modiff at the last auto-save.  */
 -  int auto_save_modified;
 +  EMACS_INT auto_save_modified;
    /* The value of text->modiff at the last display error.
       Redisplay of this buffer is inhibited until it changes again.  */
 -  int display_error_modiff;
 +  EMACS_INT display_error_modiff;
    /* The time at which we detected a failure to auto-save,
       Or 0 if we didn't have a failure.  */
    time_t auto_save_failure_time;
    /* Position in buffer at which display started
       the last time this buffer was displayed.  */
 -  EMACS_INT last_window_start;
 +  ptrdiff_t last_window_start;
  
    /* Set nonzero whenever the narrowing is changed in this buffer.  */
    int clip_changed;
    struct Lisp_Overlay *overlays_after;
  
    /* Position where the overlay lists are centered.  */
 -  EMACS_INT overlay_center;
 +  ptrdiff_t overlay_center;
  
    /* Everything from here down must be a Lisp_Object.  */
    /* buffer-local Lisp variables start at `undo_list',
@@@ -890,20 -890,20 +890,20 @@@ extern struct buffer buffer_local_symbo
  \f
  extern void delete_all_overlays (struct buffer *);
  extern void reset_buffer (struct buffer *);
 -extern void evaporate_overlays (EMACS_INT);
 +extern void evaporate_overlays (ptrdiff_t);
  extern 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 *len_ptr, ptrdiff_t *next_ptr,
 +                            ptrdiff_t *prev_ptr, int change_req);
  extern ptrdiff_t sort_overlays (Lisp_Object *, ptrdiff_t, struct window *);
 -extern void recenter_overlay_lists (struct buffer *, EMACS_INT);
 -extern EMACS_INT overlay_strings (EMACS_INT, struct window *, unsigned char **);
 +extern void recenter_overlay_lists (struct buffer *, ptrdiff_t);
 +extern ptrdiff_t overlay_strings (ptrdiff_t, struct window *, unsigned char **);
  extern void validate_region (Lisp_Object *, Lisp_Object *);
  extern void set_buffer_internal (struct buffer *);
  extern void set_buffer_internal_1 (struct buffer *);
  extern void set_buffer_temp (struct buffer *);
  extern void record_buffer (Lisp_Object);
  extern void buffer_slot_type_mismatch (Lisp_Object, int) NO_RETURN;
 -extern void fix_overlays_before (struct buffer *, EMACS_INT, EMACS_INT);
 +extern void fix_overlays_before (struct buffer *, ptrdiff_t, ptrdiff_t);
  extern void mmap_set_vars (int);
  
  /* Get overlays at POSN into array OVERLAYS with NOVERLAYS elements.
@@@ -978,7 -978,7 +978,7 @@@ extern int last_per_buffer_idx
     variable has an index > 0 associated with it, except when it always
     has buffer-local values, in which case the index is -1.  If this is
     0, this is a bug and means that the slot of VAR in
-    buffer_local_flags wasn't intiialized.  */
+    buffer_local_flags wasn't initialized.  */
  
  #define PER_BUFFER_VAR_IDX(VAR) \
      PER_BUFFER_IDX (PER_BUFFER_VAR_OFFSET (VAR))
diff --combined src/callint.c
index 5eb824b8c7435967a569360e68eb37d145b53996,80e24f6c8ee3728f4c58b8d1152904d93ef3029b..444892ef9cbbcf2a2bb92200fcc03eb659936f67
@@@ -78,7 -78,7 +78,7 @@@ c -- Character (no input method is used
  C -- Command name: symbol with interactive function definition.
  d -- Value of point as number.  Does not do I/O.
  D -- Directory name.
- e -- Parametrized event (i.e., one that's a list) that invoked this command.
+ e -- Parameterized event (i.e., one that's a list) that invoked this command.
       If used more than once, the Nth `e' returns the Nth parameterized event.
       This skips events that are integers or symbols.
  f -- Existing file name.
@@@ -257,11 -257,11 +257,11 @@@ invoke it.  If KEYS is omitted or nil, 
    Lisp_Object teml;
    Lisp_Object up_event;
    Lisp_Object enable;
 -  int speccount = SPECPDL_INDEX ();
 +  ptrdiff_t speccount = SPECPDL_INDEX ();
  
    /* The index of the next element of this_command_keys to examine for
       the 'e' interactive code.  */
 -  int next_event;
 +  ptrdiff_t next_event;
  
    Lisp_Object prefix_arg;
    char *string;
    char *tem1;
    int arg_from_tty = 0;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
 -  int key_count;
 +  ptrdiff_t key_count;
    int record_then_fail = 0;
  
    Lisp_Object save_this_command, save_last_command;
  
        case 'k':               /* Key sequence. */
          {
 -          int speccount1 = SPECPDL_INDEX ();
 +          ptrdiff_t speccount1 = SPECPDL_INDEX ();
            specbind (Qcursor_in_echo_area, Qt);
            /* Prompt in `minibuffer-prompt' face.  */
            Fput_text_property (make_number (0),
  
        case 'K':               /* Key sequence to be defined. */
          {
 -          int speccount1 = SPECPDL_INDEX ();
 +          ptrdiff_t speccount1 = SPECPDL_INDEX ();
            specbind (Qcursor_in_echo_area, Qt);
            /* Prompt in `minibuffer-prompt' face.  */
            Fput_text_property (make_number (0),
diff --combined src/casetab.c
index 64e47859d9bb23330503f40b9677df7f601f5626,575a48ed14696e8c3685cbcd8a8abe33a2260b4f..8778048072c183819bc9fc80b18824b46ad03ecb
@@@ -95,7 -95,7 +95,7 @@@ CANONICALIZE maps each character to a c
   any two characters that are related by case-conversion have the same
   canonical equivalent character; it may be nil, in which case it is
   deduced from DOWNCASE and UPCASE.
- EQUIVALENCES is a map that cyclicly permutes each equivalence class
+ EQUIVALENCES is a map that cyclically permutes each equivalence class
   (of characters with the same canonical equivalent); it may be nil,
   in which case it is deduced from CANONICALIZE.  */)
    (Lisp_Object table)
@@@ -194,7 -194,8 +194,7 @@@ set_identity (Lisp_Object table, Lisp_O
  {
    if (NATNUMP (elt))
      {
 -      int from;
 -      unsigned to;
 +      int from, to;
  
        if (CONSP (c))
        {
        }
        else
        from = to = XINT (c);
 -      for (to++; from < to; from++)
 +
 +      to++;
 +      lint_assume (to <= MAX_CHAR + 1);
 +      for (; from < to; from++)
        CHAR_TABLE_SET (table, from, make_number (from));
      }
  }
@@@ -221,7 -219,8 +221,7 @@@ shuffle (Lisp_Object table, Lisp_Objec
  {
    if (NATNUMP (elt))
      {
 -      int from;
 -      unsigned to;
 +      int from, to;
  
        if (CONSP (c))
        {
        else
        from = to = XINT (c);
  
 -      for (to++; from < to; from++)
 +      to++;
 +      lint_assume (to <= MAX_CHAR + 1);
 +      for (; from < to; from++)
        {
          Lisp_Object tem = Faref (table, elt);
          Faset (table, elt, make_number (from));
diff --combined src/ccl.c
index 97fca3bb032cec5a172e7b887dba6f4e6f64d5a9,491b925d75ca99c836095fab34976bc67e629df0..1c6f444920c95441550f96418027bb6a2a1e944e
+++ b/src/ccl.c
@@@ -47,7 -47,7 +47,7 @@@ static Lisp_Object Qcode_conversion_map
  static Lisp_Object Qcode_conversion_map_id;
  
  /* Symbols of ccl program have this property, a value of the property
-    is an index for Vccl_protram_table. */
+    is an index for Vccl_program_table. */
  static Lisp_Object Qccl_program_idx;
  
  /* Table of registered CCL programs.  Each element is a vector of
@@@ -552,7 -552,7 +552,7 @@@ static Lisp_Object Vccl_program_table
     But, when VALm is mapped to VALn and VALn is not a number, the
     mapping proceed as below:
  
-    If VALn is nil, the lastest map is ignored and the mapping of VALm
+    If VALn is nil, the last map is ignored and the mapping of VALm
     proceed to the next map.
  
     In VALn is t, VALm is reverted to reg[rrr] and the mapping of VALm
     If VALn is lambda, move to the next map set like reaching to the
     end of the current map set.
  
-    If VALn is a symbol, call the CCL program refered by it.
+    If VALn is a symbol, call the CCL program referred by it.
     Then, use reg[rrr] as a mapped value except for -1, -2 and -3.
     Such special values are regarded as nil, t, and lambda respectively.
  
@@@ -762,6 -762,9 +762,6 @@@ while (0
  #define GET_CCL_CODE(code, ccl_prog, ic)                      \
    GET_CCL_RANGE (code, ccl_prog, ic, CCL_CODE_MIN, CCL_CODE_MAX)
  
 -#define GET_CCL_INT(var, ccl_prog, ic)                                \
 -  GET_CCL_RANGE (var, ccl_prog, ic, INT_MIN, INT_MAX)
 -
  #define IN_INT_RANGE(val) ASCENDING_ORDER (INT_MIN, val, INT_MAX)
  
  /* Encode one character CH to multibyte form and write to the current
     : (charset = CHARSET_FROM_ID ((id)), DECODE_CHAR (charset, (code))))
  
  /* Encode character C by some of charsets in CHARSET_LIST.  Set ID to
-    the id of the used charset, ENCODED to the resulf of encoding.
+    the id of the used charset, ENCODED to the result of encoding.
     Assume that we can use the variable `charset'.  */
  
  #define CCL_ENCODE_CHAR(c, charset_list, id, encoded)         \
@@@ -942,14 -945,14 +942,14 @@@ ccl_driver (struct ccl_program *ccl, in
          break;
  
        case CCL_SetConst:      /* 00000000000000000000rrrXXXXX */
 -        GET_CCL_INT (reg[rrr], ccl_prog, ic++);
 +        reg[rrr] = XINT (ccl_prog[ic++]);
          break;
  
        case CCL_SetArray:      /* CCCCCCCCCCCCCCCCCCCCRRRrrrXXXXX */
          i = reg[RRR];
          j = field1 >> 3;
          if (0 <= i && i < j)
 -          GET_CCL_INT (reg[rrr], ccl_prog, ic + i);
 +          reg[rrr] = XINT (ccl_prog[ic + i]);
          ic += j;
          break;
  
          break;
  
        case CCL_WriteConstJump: /* A--D--D--R--E--S--S-000XXXXX */
 -        GET_CCL_INT (i, ccl_prog, ic);
 +        i = XINT (ccl_prog[ic]);
          CCL_WRITE_CHAR (i);
          ic += ADDR;
          break;
  
        case CCL_WriteConstReadJump: /* A--D--D--R--E--S--S-rrrXXXXX */
 -        GET_CCL_INT (i, ccl_prog, ic);
 +        i = XINT (ccl_prog[ic]);
          CCL_WRITE_CHAR (i);
          ic++;
          CCL_READ_CHAR (reg[rrr]);
          break;
  
        case CCL_WriteStringJump: /* A--D--D--R--E--S--S-000XXXXX */
 -        GET_CCL_INT (j, ccl_prog, ic++);
 +        j = XINT (ccl_prog[ic++]);
          CCL_WRITE_STRING (j);
          ic += ADDR - 1;
          break;
  
        case CCL_WriteArrayReadJump: /* A--D--D--R--E--S--S-rrrXXXXX */
          i = reg[rrr];
 -        GET_CCL_INT (j, ccl_prog, ic);
 +        j = XINT (ccl_prog[ic]);
          if (0 <= i && i < j)
            {
 -            GET_CCL_INT (i, ccl_prog, ic + 1 + i);
 +            i = XINT (ccl_prog[ic + 1 + i]);
              CCL_WRITE_CHAR (i);
            }
          ic += j + 2;
          /* fall through ... */
        case CCL_Branch:        /* CCCCCCCCCCCCCCCCCCCCrrrXXXXX */
        {
 -        int incr;
 -        GET_CCL_INT (incr, ccl_prog,
 -                     ic + (0 <= reg[rrr] && reg[rrr] < field1
 -                           ? reg[rrr]
 -                           : field1));
 +        int ioff = 0 <= reg[rrr] && reg[rrr] < field1 ? reg[rrr] : field1;
 +        int incr = XINT (ccl_prog[ic + ioff]);
          ic += incr;
        }
          break;
        case CCL_WriteExprConst:  /* 1:00000OPERATION000RRR000XXXXX */
          rrr = 7;
          i = reg[RRR];
 -        GET_CCL_INT (j, ccl_prog, ic);
 +        j = XINT (ccl_prog[ic]);
          op = field1 >> 6;
          jump_address = ic + 1;
          goto ccl_set_expr;
            /* If FFF is nonzero, the CCL program ID is in the
                 following code.  */
            if (rrr)
 -            GET_CCL_INT (prog_id, ccl_prog, ic++);
 +            prog_id = XINT (ccl_prog[ic++]);
            else
              prog_id = field1;
  
          i = reg[rrr];
          if (0 <= i && i < field1)
            {
 -            GET_CCL_INT (j, ccl_prog, ic + i);
 +            j = XINT (ccl_prog[ic + i]);
              CCL_WRITE_CHAR (j);
            }
          ic += field1;
          CCL_SUCCESS;
  
        case CCL_ExprSelfConst: /* 00000OPERATION000000rrrXXXXX */
 -        GET_CCL_INT (i, ccl_prog, ic++);
 +        i = XINT (ccl_prog[ic++]);
          op = field1 >> 6;
          goto ccl_expr_self;
  
  
        case CCL_SetExprConst:  /* 00000OPERATION000RRRrrrXXXXX */
          i = reg[RRR];
 -        GET_CCL_INT (j, ccl_prog, ic++);
 +        j = XINT (ccl_prog[ic++]);
          op = field1 >> 6;
          jump_address = ic;
          goto ccl_set_expr;
        case CCL_JumpCondExprConst: /* A--D--D--R--E--S--S-rrrXXXXX */
          i = reg[rrr];
          jump_address = ic + ADDR;
 -        GET_CCL_INT (op, ccl_prog, ic++);
 -        GET_CCL_INT (j, ccl_prog, ic++);
 +        op = XINT (ccl_prog[ic++]);
 +        j = XINT (ccl_prog[ic++]);
          rrr = 7;
          goto ccl_set_expr;
  
        case CCL_JumpCondExprReg:
          i = reg[rrr];
          jump_address = ic + ADDR;
 -        GET_CCL_INT (op, ccl_prog, ic++);
 +        op = XINT (ccl_prog[ic++]);
          GET_CCL_RANGE (j, ccl_prog, ic++, 0, 7);
          j = reg[j];
          rrr = 7;
  
            case CCL_TranslateCharacterConstTbl:
              {
 -              EMACS_INT eop;
 +              ptrdiff_t eop;
                GET_CCL_RANGE (eop, ccl_prog, ic++, 0,
                               (VECTORP (Vtranslation_table_vector)
                                ? ASIZE (Vtranslation_table_vector)
            case CCL_IterateMultipleMap:
              {
                Lisp_Object map, content, attrib, value;
 -              EMACS_INT point, size;
 +              EMACS_INT point;
 +              ptrdiff_t size;
                int fin_ic;
  
 -              GET_CCL_INT (j, ccl_prog, ic++); /* number of maps. */
 +              j = XINT (ccl_prog[ic++]); /* number of maps. */
                fin_ic = ic + j;
                op = reg[rrr];
                if ((j > reg[RRR]) && (j >= 0))
  
                for (;i < j;i++)
                  {
 -
 +                  if (!VECTORP (Vcode_conversion_map_vector)) continue;
                    size = ASIZE (Vcode_conversion_map_vector);
                    point = XINT (ccl_prog[ic++]);
                    if (! (0 <= point && point < size)) continue;
            case CCL_MapMultiple:
              {
                Lisp_Object map, content, attrib, value;
 -              int point, size, map_vector_size;
 +              EMACS_INT point;
 +              ptrdiff_t size, map_vector_size;
                int map_set_rest_length, fin_ic;
                int current_ic = this_ic;
  
                stack_idx_of_map_multiple = 0;
  
                /* Get number of maps and separators.  */
 -              GET_CCL_INT (map_set_rest_length, ccl_prog, ic++);
 +              map_set_rest_length = XINT (ccl_prog[ic++]);
  
                fin_ic = ic + map_set_rest_length;
                op = reg[rrr];
                        break;
                      }
                  }
 +              if (!VECTORP (Vcode_conversion_map_vector))
 +                CCL_INVALID_CMD;
                map_vector_size = ASIZE (Vcode_conversion_map_vector);
  
                do {
                  for (;map_set_rest_length > 0;i++, ic++, map_set_rest_length--)
                    {
 -                    GET_CCL_INT (point, ccl_prog, ic);
 +                    point = XINT (ccl_prog[ic]);
                      if (point < 0)
                        {
                          /* +1 is for including separator. */
                int point;
                j = XINT (ccl_prog[ic++]); /* map_id */
                op = reg[rrr];
 -              if (j >= ASIZE (Vcode_conversion_map_vector))
 +              if (! (VECTORP (Vcode_conversion_map_vector)
 +                     && j < ASIZE (Vcode_conversion_map_vector)))
                  {
                    reg[RRR] = -1;
                    break;
                  }
                map = XCDR (map);
                if (! (VECTORP (map)
 +                     && 0 < ASIZE (map)
                       && INTEGERP (AREF (map, 0))
                       && XINT (AREF (map, 0)) <= op
                       && op - XINT (AREF (map, 0)) + 1 < ASIZE (map)))
                    reg[RRR] = -1;
                    break;
                  }
 -              point = XINT (AREF (map, 0));
 -              point = op - point + 1;
 +              point = op - XINT (AREF (map, 0)) + 1;
                reg[RRR] = 0;
                content = AREF (map, point);
                if (NILP (content))
                  reg[RRR] = -1;
 -              else if (INTEGERP (content))
 +              else if (TYPE_RANGED_INTEGERP (int, content))
                  reg[rrr] = XINT (content);
                else if (EQ (content, Qt));
                else if (CONSP (content))
                  {
                    attrib = XCAR (content);
                    value = XCDR (content);
 -                  if (!INTEGERP (attrib) || !INTEGERP (value))
 +                  if (!INTEGERP (attrib)
 +                      || !TYPE_RANGED_INTEGERP (int, value))
                      continue;
                    reg[rrr] = XINT (value);
                    break;
     function converts symbols of code conversion maps and character
     translation tables embedded in the CCL code into their ID numbers.
  
 -   The return value is a vector (CCL itself or a new vector in which
 -   all symbols are resolved), Qt if resolving of some symbol failed,
 +   The return value is a new vector in which all symbols are resolved,
 +   Qt if resolving of some symbol failed,
     or nil if CCL contains invalid data.  */
  
  static Lisp_Object
@@@ -1820,15 -1820,13 +1820,15 @@@ resolve_symbol_ccl_program (Lisp_Objec
    int i, veclen, unresolved = 0;
    Lisp_Object result, contents, val;
  
 -  result = ccl;
 +  if (! (CCL_HEADER_MAIN < ASIZE (ccl) && ASIZE (ccl) <= INT_MAX))
 +    return Qnil;
 +  result = Fcopy_sequence (ccl);
    veclen = ASIZE (result);
  
    for (i = 0; i < veclen; i++)
      {
        contents = AREF (result, i);
 -      if (INTEGERP (contents))
 +      if (TYPE_RANGED_INTEGERP (int, contents))
        continue;
        else if (CONSP (contents)
               && SYMBOLP (XCAR (contents))
          /* This is the new style for embedding symbols.  The form is
             (SYMBOL . PROPERTY).  (get SYMBOL PROPERTY) should give
             an index number.  */
 -
 -        if (EQ (result, ccl))
 -          result =  Fcopy_sequence (ccl);
 -
          val = Fget (XCAR (contents), XCDR (contents));
 -        if (NATNUMP (val))
 +        if (RANGED_INTEGERP (0, val, INT_MAX))
            ASET (result, i, val);
          else
            unresolved = 1;
          /* This is the old style for embedding symbols.  This style
               may lead to a bug if, for instance, a translation table
               and a code conversion map have the same name.  */
 -        if (EQ (result, ccl))
 -          result = Fcopy_sequence (ccl);
 -
          val = Fget (contents, Qtranslation_table_id);
 -        if (NATNUMP (val))
 +        if (RANGED_INTEGERP (0, val, INT_MAX))
            ASET (result, i, val);
          else
            {
              val = Fget (contents, Qcode_conversion_map_id);
 -            if (NATNUMP (val))
 +            if (RANGED_INTEGERP (0, val, INT_MAX))
                ASET (result, i, val);
              else
                {
                  val = Fget (contents, Qccl_program_idx);
 -                if (NATNUMP (val))
 +                if (RANGED_INTEGERP (0, val, INT_MAX))
                    ASET (result, i, val);
                  else
                    unresolved = 1;
        return Qnil;
      }
  
 +  if (! (0 <= XINT (AREF (result, CCL_HEADER_BUF_MAG))
 +       && ASCENDING_ORDER (0, XINT (AREF (result, CCL_HEADER_EOF)),
 +                           ASIZE (ccl))))
 +    return Qnil;
 +
    return (unresolved ? Qt : result);
  }
  
     symbols, return Qnil.  */
  
  static Lisp_Object
 -ccl_get_compiled_code (Lisp_Object ccl_prog, int *idx)
 +ccl_get_compiled_code (Lisp_Object ccl_prog, ptrdiff_t *idx)
  {
    Lisp_Object val, slot;
  
@@@ -2015,7 -2015,7 +2015,7 @@@ programs.  */
      error ("Length of vector REGISTERS is not 8");
  
    for (i = 0; i < 8; i++)
 -    ccl.reg[i] = (INTEGERP (AREF (reg, i))
 +    ccl.reg[i] = (TYPE_RANGED_INTEGERP (int, AREF (reg, i))
                  ? XINT (AREF (reg, i))
                  : 0);
  
@@@ -2084,7 -2084,7 +2084,7 @@@ usage: (ccl-execute-on-string CCL-PROGR
      {
        if (NILP (AREF (status, i)))
        ASET (status, i, make_number (0));
 -      if (INTEGERP (AREF (status, i)))
 +      if (TYPE_RANGED_INTEGERP (int, AREF (status, i)))
        ccl.reg[i] = XINT (AREF (status, i));
      }
    if (INTEGERP (AREF (status, i)))
@@@ -2187,8 -2187,8 +2187,8 @@@ If it is nil, just reserve NAME as a CC
  Return index number of the registered CCL program.  */)
       (Lisp_Object name, Lisp_Object ccl_prog)
  {
 -  int len = ASIZE (Vccl_program_table);
 -  int idx;
 +  ptrdiff_t len = ASIZE (Vccl_program_table);
 +  ptrdiff_t idx;
    Lisp_Object resolved;
  
    CHECK_SYMBOL (name);
  
    if (idx == len)
      /* Extend the table.  */
 -    Vccl_program_table = larger_vector (Vccl_program_table, len * 2, Qnil);
 +    Vccl_program_table = larger_vector (Vccl_program_table, 1, -1);
  
    {
      Lisp_Object elt;
@@@ -2262,16 -2262,12 +2262,16 @@@ DEFUN ("register-code-conversion-map", 
  Return index number of the registered map.  */)
    (Lisp_Object symbol, Lisp_Object map)
  {
 -  int len = ASIZE (Vcode_conversion_map_vector);
 -  int i;
 +  ptrdiff_t len;
 +  ptrdiff_t i;
    Lisp_Object idx;
  
    CHECK_SYMBOL (symbol);
    CHECK_VECTOR (map);
 +  if (! VECTORP (Vcode_conversion_map_vector))
 +    error ("Invalid code-conversion-map-vector");
 +
 +  len = ASIZE (Vcode_conversion_map_vector);
  
    for (i = 0; i < len; i++)
      {
  
    if (i == len)
      Vcode_conversion_map_vector = larger_vector (Vcode_conversion_map_vector,
 -                                               len * 2, Qnil);
 +                                               1, -1);
  
    idx = make_number (i);
    Fput (symbol, Qcode_conversion_map, map);
diff --combined src/character.c
index d5d89381aaf12e8e8eafef408c8a698a081ebf31,88b1f11b96bda53d546d0ec09e6dc903db6ca5ff..5e2a7b9461cd985f4bc3ecc6ee17cd2cece0960a
@@@ -67,8 -67,8 +67,8 @@@ static Lisp_Object Qchar_script_table
  /* If character code C has modifier masks, reflect them to the
     character code if possible.  Return the resulting code.  */
  
 -int
 -char_resolve_modifier_mask (int c)
 +EMACS_INT
 +char_resolve_modifier_mask (EMACS_INT c)
  {
    /* A non-ASCII character can't reflect modifier bits to the code.  */
    if (! ASCII_CHAR_P ((c & ~CHAR_MODIFIER_MASK)))
@@@ -340,12 -340,12 +340,12 @@@ usage: (char-width CHAR)  */
     characters and bytes of the substring in *NCHARS and *NBYTES
     respectively.  */
  
 -EMACS_INT
 -c_string_width (const unsigned char *str, EMACS_INT len, int precision,
 -              EMACS_INT *nchars, EMACS_INT *nbytes)
 +ptrdiff_t
 +c_string_width (const unsigned char *str, ptrdiff_t len, int precision,
 +              ptrdiff_t *nchars, ptrdiff_t *nbytes)
  {
 -  EMACS_INT i = 0, i_byte = 0;
 -  EMACS_INT width = 0;
 +  ptrdiff_t i = 0, i_byte = 0;
 +  ptrdiff_t width = 0;
    struct Lisp_Char_Table *dp = buffer_display_table ();
  
    while (i_byte < len)
     current buffer.  The width is measured by how many columns it
     occupies on the screen.  */
  
 -EMACS_INT
 -strwidth (const char *str, EMACS_INT len)
 +ptrdiff_t
 +strwidth (const char *str, ptrdiff_t len)
  {
    return c_string_width ((const unsigned char *) str, len, -1, NULL, NULL);
  }
     PRECISION, and set number of characters and bytes of the substring
     in *NCHARS and *NBYTES respectively.  */
  
 -EMACS_INT
 -lisp_string_width (Lisp_Object string, EMACS_INT precision,
 -                 EMACS_INT *nchars, EMACS_INT *nbytes)
 +ptrdiff_t
 +lisp_string_width (Lisp_Object string, ptrdiff_t precision,
 +                 ptrdiff_t *nchars, ptrdiff_t *nbytes)
  {
 -  EMACS_INT len = SCHARS (string);
 +  ptrdiff_t len = SCHARS (string);
    /* This set multibyte to 0 even if STRING is multibyte when it
       contains only ascii and eight-bit-graphic, but that's
       intentional.  */
    int multibyte = len < SBYTES (string);
    unsigned char *str = SDATA (string);
 -  EMACS_INT i = 0, i_byte = 0;
 -  EMACS_INT width = 0;
 +  ptrdiff_t i = 0, i_byte = 0;
 +  ptrdiff_t width = 0;
    struct Lisp_Char_Table *dp = buffer_display_table ();
  
    while (i < len)
      {
 -      EMACS_INT chars, bytes, thiswidth;
 +      ptrdiff_t chars, bytes, thiswidth;
        Lisp_Object val;
        ptrdiff_t cmp_id;
 -      EMACS_INT ignore, end;
 +      ptrdiff_t ignore, end;
  
        if (find_composition (i, -1, &ignore, &end, &val, string)
          && ((cmp_id = get_composition_id (i, i_byte, end - i, val, string))
@@@ -511,8 -511,8 +511,8 @@@ usage: (string-width STRING)  */
     However, if the current buffer has enable-multibyte-characters =
     nil, we treat each byte as a character.  */
  
 -EMACS_INT
 -chars_in_text (const unsigned char *ptr, EMACS_INT nbytes)
 +ptrdiff_t
 +chars_in_text (const unsigned char *ptr, ptrdiff_t nbytes)
  {
    /* current_buffer is null at early stages of Emacs initialization.  */
    if (current_buffer == 0
     sequences while assuming that there's no invalid sequence.  It
     ignores enable-multibyte-characters.  */
  
 -EMACS_INT
 -multibyte_chars_in_text (const unsigned char *ptr, EMACS_INT nbytes)
 +ptrdiff_t
 +multibyte_chars_in_text (const unsigned char *ptr, ptrdiff_t nbytes)
  {
    const unsigned char *endp = ptr + nbytes;
 -  EMACS_INT chars = 0;
 +  ptrdiff_t chars = 0;
  
    while (ptr < endp)
      {
 -      EMACS_INT len = MULTIBYTE_LENGTH (ptr, endp);
 +      int len = MULTIBYTE_LENGTH (ptr, endp);
  
        if (len == 0)
        abort ();
     represented by 2-byte in a multibyte text.  */
  
  void
 -parse_str_as_multibyte (const unsigned char *str, EMACS_INT len,
 -                      EMACS_INT *nchars, EMACS_INT *nbytes)
 +parse_str_as_multibyte (const unsigned char *str, ptrdiff_t len,
 +                      ptrdiff_t *nchars, ptrdiff_t *nbytes)
  {
    const unsigned char *endp = str + len;
 -  EMACS_INT n, chars = 0, bytes = 0;
 +  int n;
 +  ptrdiff_t chars = 0, bytes = 0;
  
    if (len >= MAX_MULTIBYTE_LENGTH)
      {
     area and that is enough.  Return the number of bytes of the
     resulting text.  */
  
 -EMACS_INT
 -str_as_multibyte (unsigned char *str, EMACS_INT len, EMACS_INT nbytes,
 -                EMACS_INT *nchars)
 +ptrdiff_t
 +str_as_multibyte (unsigned char *str, ptrdiff_t len, ptrdiff_t nbytes,
 +                ptrdiff_t *nchars)
  {
    unsigned char *p = str, *endp = str + nbytes;
    unsigned char *to;
 -  EMACS_INT chars = 0;
 +  ptrdiff_t chars = 0;
    int n;
  
    if (nbytes >= MAX_MULTIBYTE_LENGTH)
  }
  
  /* Parse unibyte string at STR of LEN bytes, and return the number of
-    bytes it may ocupy when converted to multibyte string by
+    bytes it may occupy when converted to multibyte string by
     `str_to_multibyte'.  */
  
 -EMACS_INT
 -count_size_as_multibyte (const unsigned char *str, EMACS_INT len)
 +ptrdiff_t
 +count_size_as_multibyte (const unsigned char *str, ptrdiff_t len)
  {
    const unsigned char *endp = str + len;
 -  EMACS_INT bytes;
 +  ptrdiff_t bytes;
  
    for (bytes = 0; str < endp; str++)
      {
     that we can use LEN bytes at STR as a work area and that is
     enough.  */
  
 -EMACS_INT
 -str_to_multibyte (unsigned char *str, EMACS_INT len, EMACS_INT bytes)
 +ptrdiff_t
 +str_to_multibyte (unsigned char *str, ptrdiff_t len, ptrdiff_t bytes)
  {
    unsigned char *p = str, *endp = str + bytes;
    unsigned char *to;
     actually converts characters in the range 0x80..0xFF to
     unibyte.  */
  
 -EMACS_INT
 -str_as_unibyte (unsigned char *str, EMACS_INT bytes)
 +ptrdiff_t
 +str_as_unibyte (unsigned char *str, ptrdiff_t bytes)
  {
    const unsigned char *p = str, *endp = str + bytes;
    unsigned char *to;
     of that character code.
     Note: Currently the arg ACCEPT_LATIN_1 is not used.  */
  
 -EMACS_INT
 -str_to_unibyte (const unsigned char *src, unsigned char *dst, EMACS_INT chars, int accept_latin_1)
 +ptrdiff_t
 +str_to_unibyte (const unsigned char *src, unsigned char *dst, ptrdiff_t chars, int accept_latin_1)
  {
 -  EMACS_INT i;
 +  ptrdiff_t i;
  
    for (i = 0; i < chars; i++)
      {
  }
  
  
 -static EMACS_INT
 +static ptrdiff_t
  string_count_byte8 (Lisp_Object string)
  {
    int multibyte = STRING_MULTIBYTE (string);
 -  EMACS_INT nbytes = SBYTES (string);
 +  ptrdiff_t nbytes = SBYTES (string);
    unsigned char *p = SDATA (string);
    unsigned char *pend = p + nbytes;
 -  EMACS_INT count = 0;
 +  ptrdiff_t count = 0;
    int c, len;
  
    if (multibyte)
  Lisp_Object
  string_escape_byte8 (Lisp_Object string)
  {
 -  EMACS_INT nchars = SCHARS (string);
 -  EMACS_INT nbytes = SBYTES (string);
 +  ptrdiff_t nchars = SCHARS (string);
 +  ptrdiff_t nbytes = SBYTES (string);
    int multibyte = STRING_MULTIBYTE (string);
 -  EMACS_INT byte8_count;
 +  ptrdiff_t byte8_count;
    const unsigned char *src, *src_end;
    unsigned char *dst;
    Lisp_Object val;
@@@ -924,6 -923,7 +924,6 @@@ usage: (unibyte-string &rest BYTES)  */
    (ptrdiff_t n, Lisp_Object *args)
  {
    ptrdiff_t i;
 -  int c;
    unsigned char *buf, *p;
    Lisp_Object str;
    USE_SAFE_ALLOCA;
  
    for (i = 0; i < n; i++)
      {
 -      CHECK_NATNUM (args[i]);
 -      c = XFASTINT (args[i]);
 -      if (c >= 256)
 -      args_out_of_range_3 (args[i], make_number (0), make_number (255));
 -      *p++ = c;
 +      CHECK_RANGED_INTEGER (0, args[i], 255);
 +      *p++ = XINT (args[i]);
      }
  
    str = make_string_from_bytes ((char *) buf, n, p - buf);
@@@ -950,7 -953,7 +950,7 @@@ code.  Unresolved modifiers are kept i
  usage: (char-resolve-modifiers CHAR)  */)
    (Lisp_Object character)
  {
 -  int c;
 +  EMACS_INT c;
  
    CHECK_NUMBER (character);
    c = XINT (character);
@@@ -970,7 -973,7 +970,7 @@@ character is not ASCII nor 8-bit charac
    (Lisp_Object position, Lisp_Object string)
  {
    int c;
 -  EMACS_INT pos;
 +  ptrdiff_t pos;
    unsigned char *p;
  
    if (NILP (string))
diff --combined src/character.h
index 2e1372eaf94a0b5377b1bdcfce6e0a8edb144e85,5ae6cb8c49ca2a4e20350c2124a427be7db24de3..cc76ab213fcab25580a40f989678b0a3a85ea29d
@@@ -596,7 -596,7 +596,7 @@@ sanitize_char_width (EMACS_INT width
     ? ASCII_CHAR_WIDTH (c)     \
     : sanitize_char_width (XINT (CHAR_TABLE_REF (Vchar_width_table, c))))
  
- /* If C is a variation selector, return the index numnber of the
+ /* If C is a variation selector, return the index of the
     variation selector (1..256).  Otherwise, return 0.  */
  
  #define CHAR_VARIATION_SELECTOR_P(c)          \
@@@ -655,7 -655,7 +655,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/charset.c
index 8f16771b855bb0dd244c1e81da71c1eeda8ccbfd,3c15f1bee54c0da9f222cf7874c83a94d2c71374..ec90a64341e5dcf095629d8aa2aae6385543e5d8
@@@ -118,25 -118,24 +118,25 @@@ int iso_charset_table[ISO_MAX_DIMENSION
  
  #define CODE_POINT_TO_INDEX(charset, code)                            \
    ((charset)->code_linear_p                                           \
 -   ? (code) - (charset)->min_code                                     \
 +   ? (int) ((code) - (charset)->min_code)                             \
     : (((charset)->code_space_mask[(code) >> 24] & 0x8)                        \
        && ((charset)->code_space_mask[((code) >> 16) & 0xFF] & 0x4)    \
        && ((charset)->code_space_mask[((code) >> 8) & 0xFF] & 0x2)     \
        && ((charset)->code_space_mask[(code) & 0xFF] & 0x1))           \
 -   ? (((((code) >> 24) - (charset)->code_space[12])                   \
 -       * (charset)->code_space[11])                                   \
 -      + (((((code) >> 16) & 0xFF) - (charset)->code_space[8])         \
 -       * (charset)->code_space[7])                                    \
 -      + (((((code) >> 8) & 0xFF) - (charset)->code_space[4])          \
 -       * (charset)->code_space[3])                                    \
 -      + (((code) & 0xFF) - (charset)->code_space[0])                  \
 -      - ((charset)->char_index_offset))                                       \
 +   ? (int) (((((code) >> 24) - (charset)->code_space[12])             \
 +           * (charset)->code_space[11])                               \
 +          + (((((code) >> 16) & 0xFF) - (charset)->code_space[8])     \
 +             * (charset)->code_space[7])                              \
 +          + (((((code) >> 8) & 0xFF) - (charset)->code_space[4])      \
 +             * (charset)->code_space[3])                              \
 +          + (((code) & 0xFF) - (charset)->code_space[0])              \
 +          - ((charset)->char_index_offset))                           \
     : -1)
  
  
 -/* Convert the character index IDX to code-point CODE for CHARSET.
 -   It is assumed that IDX is in a valid range.  */
 +/* Return the code-point for the character index IDX in CHARSET.
 +   IDX should be an unsigned int variable in a valid range (which is
 +   always in nonnegative int range too).  IDX contains garbage afterwards.  */
  
  #define INDEX_TO_CODE_POINT(charset, idx)                                  \
    ((charset)->code_linear_p                                                \
@@@ -167,9 -166,9 +167,9 @@@ static struc
       maximum character of the current charset.  */
    int min_char, max_char;
  
-   /* A Unicode character correspoinding to the code indice 0 (i.e. the
+   /* A Unicode character corresponding to the code index 0 (i.e. the
       minimum code-point) of the current charset, or -1 if the code
-      indice 0 is not a Unicode character.  This is checked when
+      index 0 is not a Unicode character.  This is checked when
       table.encoder[CHAR] is zero.  */
    int zero_index_char;
  
@@@ -364,8 -363,7 +364,8 @@@ load_charset_map (struct charset *chars
              && CHARSET_COMPACT_CODES_P (charset))
            for (; from_index < lim_index; from_index++, from_c++)
              {
 -              unsigned code = INDEX_TO_CODE_POINT (charset, from_index);
 +              unsigned code = from_index;
 +              code = INDEX_TO_CODE_POINT (charset, code);
  
                if (NILP (CHAR_TABLE_REF (table, from_c)))
                  CHAR_TABLE_SET (table, from_c, make_number (code));
@@@ -484,8 -482,7 +484,8 @@@ load_charset_map_from_file (struct char
    FILE *fp;
    Lisp_Object suffixes;
    struct charset_map_entries *head, *entries;
 -  int n_entries, count;
 +  int n_entries;
 +  ptrdiff_t count;
    USE_SAFE_ALLOCA;
  
    suffixes = Fcons (build_string (".map"),
                       sizeof (struct charset_map_entries));
          entries = entries->next;
          memset (entries, 0, sizeof (struct charset_map_entries));
 +        n_entries = 0;
        }
 -      idx = n_entries % 0x10000;
 +      idx = n_entries;
        entries->entry[idx].from = from;
        entries->entry[idx].to = to;
        entries->entry[idx].c = c;
@@@ -580,7 -576,7 +580,7 @@@ load_charset_map_from_vector (struct ch
      {
        Lisp_Object val, val2;
        unsigned from, to;
 -      int c;
 +      EMACS_INT c;
        int idx;
  
        val = AREF (vec, i);
        {
          val2 = XCDR (val);
          val = XCAR (val);
 -        CHECK_NATNUM (val);
 -        CHECK_NATNUM (val2);
          from = XFASTINT (val);
          to = XFASTINT (val2);
        }
        else
 -      {
 -        CHECK_NATNUM (val);
 -        from = to = XFASTINT (val);
 -      }
 +      from = to = XFASTINT (val);
        val = AREF (vec, i + 1);
        CHECK_NATNUM (val);
        c = XFASTINT (val);
@@@ -820,6 -821,7 +820,6 @@@ range of code points (in CHARSET) of ta
      from = CHARSET_MIN_CODE (cs);
    else
      {
 -      CHECK_NATNUM (from_code);
        from = XINT (from_code);
        if (from < CHARSET_MIN_CODE (cs))
        from = CHARSET_MIN_CODE (cs);
      to = CHARSET_MAX_CODE (cs);
    else
      {
 -      CHECK_NATNUM (to_code);
        to = XINT (to_code);
        if (to > CHARSET_MAX_CODE (cs))
        to = CHARSET_MAX_CODE (cs);
@@@ -873,15 -876,12 +873,15 @@@ usage: (define-charset-internal ...)  *
    val = args[charset_arg_code_space];
    for (i = 0, dimension = 0, nchars = 1; ; i++)
      {
 +      Lisp_Object min_byte_obj, max_byte_obj;
        int min_byte, max_byte;
  
 -      min_byte = XINT (Faref (val, make_number (i * 2)));
 -      max_byte = XINT (Faref (val, make_number (i * 2 + 1)));
 -      if (min_byte < 0 || min_byte > max_byte || max_byte >= 256)
 -      error ("Invalid :code-space value");
 +      min_byte_obj = Faref (val, make_number (i * 2));
 +      max_byte_obj = Faref (val, make_number (i * 2 + 1));
 +      CHECK_RANGED_INTEGER (0, min_byte_obj, 255);
 +      min_byte = XINT (min_byte_obj);
 +      CHECK_RANGED_INTEGER (min_byte, max_byte_obj, 255);
 +      max_byte = XINT (max_byte_obj);
        charset.code_space[i * 4] = min_byte;
        charset.code_space[i * 4 + 1] = max_byte;
        charset.code_space[i * 4 + 2] = max_byte - min_byte + 1;
      charset.dimension = dimension;
    else
      {
 -      CHECK_NATNUM (val);
 +      CHECK_RANGED_INTEGER (1, val, 4);
        charset.dimension = XINT (val);
 -      if (charset.dimension < 1 || charset.dimension > 4)
 -      args_out_of_range_3 (val, make_number (1), make_number (4));
      }
  
    charset.code_linear_p
    charset.min_code = (charset.code_space[0]
                      | (charset.code_space[4] << 8)
                      | (charset.code_space[8] << 16)
 -                    | (charset.code_space[12] << 24));
 +                    | ((unsigned) charset.code_space[12] << 24));
    charset.max_code = (charset.code_space[1]
                      | (charset.code_space[5] << 8)
                      | (charset.code_space[9] << 16)
 -                    | (charset.code_space[13] << 24));
 +                    | ((unsigned) charset.code_space[13] << 24));
    charset.char_index_offset = 0;
  
    val = args[charset_arg_min_code];
  
        if (code < charset.min_code
          || code > charset.max_code)
 -      args_out_of_range_3 (make_number (charset.min_code),
 -                           make_number (charset.max_code), val);
 +      args_out_of_range_3 (make_fixnum_or_float (charset.min_code),
 +                           make_fixnum_or_float (charset.max_code), val);
        charset.char_index_offset = CODE_POINT_TO_INDEX (&charset, code);
        charset.min_code = code;
      }
  
        if (code < charset.min_code
          || code > charset.max_code)
 -      args_out_of_range_3 (make_number (charset.min_code),
 -                           make_number (charset.max_code), val);
 +      args_out_of_range_3 (make_fixnum_or_float (charset.min_code),
 +                           make_fixnum_or_float (charset.max_code), val);
        charset.max_code = code;
      }
  
        charset.invalid_code = 0;
        else
        {
 -        XSETINT (val, charset.max_code + 1);
 -        if (XINT (val) == charset.max_code + 1)
 +        if (charset.max_code < UINT_MAX)
            charset.invalid_code = charset.max_code + 1;
          else
            error ("Attribute :invalid-code must be specified");
        }
      }
    else
 -    {
 -      CHECK_NATNUM (val);
 -      charset.invalid_code = XFASTINT (val);
 -    }
 +    charset.invalid_code = cons_to_unsigned (val, UINT_MAX);
  
    val = args[charset_arg_iso_final];
    if (NILP (val))
      charset.iso_revision = -1;
    else
      {
 -      CHECK_NUMBER (val);
 -      if (XINT (val) > 63)
 -      args_out_of_range (make_number (63), val);
 +      CHECK_RANGED_INTEGER (-1, val, 63);
        charset.iso_revision = XINT (val);
      }
  
    if (! NILP (args[charset_arg_code_offset]))
      {
        val = args[charset_arg_code_offset];
 -      CHECK_NUMBER (val);
 +      CHECK_CHARACTER (val);
  
        charset.method = CHARSET_METHOD_OFFSET;
        charset.code_offset = XINT (val);
  
 -      i = CODE_POINT_TO_INDEX (&charset, charset.min_code);
 -      charset.min_char = i + charset.code_offset;
        i = CODE_POINT_TO_INDEX (&charset, charset.max_code);
 -      charset.max_char = i + charset.code_offset;
 -      if (charset.max_char > MAX_CHAR)
 +      if (MAX_CHAR - charset.code_offset < i)
        error ("Unsupported max char: %d", charset.max_char);
 +      charset.max_char = i + charset.code_offset;
 +      i = CODE_POINT_TO_INDEX (&charset, charset.min_code);
 +      charset.min_char = i + charset.code_offset;
  
        i = (charset.min_char >> 7) << 7;
        for (; i < 0x10000 && i <= charset.max_char; i += 128)
              car_part = XCAR (elt);
              cdr_part = XCDR (elt);
              CHECK_CHARSET_GET_ID (car_part, this_id);
 -            CHECK_NUMBER (cdr_part);
 +            CHECK_TYPE_RANGED_INTEGER (int, cdr_part);
              offset = XINT (cdr_part);
            }
          else
@@@ -1387,8 -1395,8 +1387,8 @@@ Optional third argument DEUNIFY, if non
      }
    else if (CHAR_TABLE_P (Vchar_unify_table))
      {
 -      int min_code = CHARSET_MIN_CODE (cs);
 -      int max_code = CHARSET_MAX_CODE (cs);
 +      unsigned min_code = CHARSET_MIN_CODE (cs);
 +      unsigned max_code = CHARSET_MAX_CODE (cs);
        int min_char = DECODE_CHAR (cs, min_code);
        int max_char = DECODE_CHAR (cs, max_code);
  
@@@ -1503,7 -1511,7 +1503,7 @@@ string_xstring_p (Lisp_Object string
     It may lookup a translation table TABLE if supplied.  */
  
  static void
 -find_charsets_in_text (const unsigned char *ptr, EMACS_INT nchars, EMACS_INT nbytes, Lisp_Object charsets, Lisp_Object table, int multibyte)
 +find_charsets_in_text (const unsigned char *ptr, ptrdiff_t nchars, ptrdiff_t nbytes, Lisp_Object charsets, Lisp_Object table, int multibyte)
  {
    const unsigned char *pend = ptr + nbytes;
  
@@@ -1550,7 -1558,7 +1550,7 @@@ only `ascii', `eight-bit-control', and 
    (Lisp_Object beg, Lisp_Object end, Lisp_Object table)
  {
    Lisp_Object charsets;
 -  EMACS_INT from, from_byte, to, stop, stop_byte;
 +  ptrdiff_t from, from_byte, to, stop, stop_byte;
    int i;
    Lisp_Object val;
    int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
@@@ -1832,7 -1840,7 +1832,7 @@@ encode_char (struct charset *charset, i
      }
    else                                /* method == CHARSET_METHOD_OFFSET */
      {
 -      int code_index = c - CHARSET_CODE_OFFSET (charset);
 +      unsigned code_index = c - CHARSET_CODE_OFFSET (charset);
  
        code = INDEX_TO_CODE_POINT (charset, code_index);
      }
@@@ -2074,7 -2082,7 +2074,7 @@@ that case, find the charset from what s
  DEFUN ("charset-after", Fcharset_after, Scharset_after, 0, 1, 0,
         doc: /*
  Return charset of a character in the current buffer at position POS.
- If POS is nil, it defauls to the current point.
+ If POS is nil, it defaults to the current point.
  If POS is out of range, the value is nil.  */)
    (Lisp_Object pos)
  {
diff --combined src/chartab.c
index c3dd1fe5b1525b6bf7808a61e0b91c34bf09bb7a,8d903749284e538d23ba29fd131d52f3771aea78..e125296261241546c1b82eb04b0581776bfe1c0d
@@@ -107,9 -107,9 +107,9 @@@ the char-table has no extra slot.  */
    else
      {
        CHECK_NATNUM (n);
 -      n_extras = XINT (n);
 -      if (n_extras > 10)
 +      if (XINT (n) > 10)
        args_out_of_range (n, Qnil);
 +      n_extras = XINT (n);
      }
  
    size = VECSIZE (struct Lisp_Char_Table) - 1 + n_extras;
@@@ -646,7 -646,7 +646,7 @@@ or a character code.  Return VALUE.  */
      }
    else if (EQ (range, Qnil))
      XCHAR_TABLE (char_table)->defalt = value;
 -  else if (INTEGERP (range))
 +  else if (CHARACTERP (range))
      char_table_set (char_table, XINT (range), value);
    else if (CONSP (range))
      {
@@@ -747,7 -747,7 +747,7 @@@ equivalent and can be merged.  It defau
     ARG is passed to C_FUNCTION when that is called.
  
     It returns the value of last character covered by TABLE (not the
-    value inheritted from the parent), and by side-effect, the car part
+    value inherited from the parent), and by side-effect, the car part
     of RANGE is updated to the minimum character C where C and all the
     following characters in TABLE have the same value.  */
  
@@@ -1223,7 -1223,7 +1223,7 @@@ static int uniprop_decoder_coun
  static uniprop_decoder_t
  uniprop_get_decoder (Lisp_Object table)
  {
 -  int i;
 +  EMACS_INT i;
  
    if (! INTEGERP (XCHAR_TABLE (table)->extras[1]))
      return NULL;
@@@ -1303,7 -1303,7 +1303,7 @@@ static int uniprop_encoder_coun
  static uniprop_decoder_t
  uniprop_get_encoder (Lisp_Object table)
  {
 -  int i;
 +  EMACS_INT i;
  
    if (! INTEGERP (XCHAR_TABLE (table)->extras[2]))
      return NULL;
diff --combined src/coding.c
index b0dfc498addd48898733208ba6b19c0066102b65,5026809941300f988a3e393b4c2fce1d0cc3a19e..74cf232cfb29182e930af815a5f91ca279a9e685
@@@ -159,7 -159,7 +159,7 @@@ detect_coding_XXX (struct coding_syste
    const unsigned char *src = coding->source;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int found = 0;
    ...;
  
@@@ -266,7 -266,7 +266,7 @@@ encode_coding_XXX (struct coding_syste
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
    unsigned char *adjusted_dst_end = dst_end - _MAX_BYTES_PRODUCED_IN_LOOP_;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
  
    for (; charbuf < charbuf_end && dst < adjusted_dst_end; charbuf++)
      {
@@@ -847,33 -847,33 +847,33 @@@ static int encode_coding_ccl (struct co
  static void decode_coding_raw_text (struct coding_system *);
  static int encode_coding_raw_text (struct coding_system *);
  
- static void coding_set_source (struct coding_system *);
- static void coding_set_destination (struct coding_system *);
 -static EMACS_INT coding_set_source (struct coding_system *);
 -static EMACS_INT coding_set_destination (struct coding_system *);
 -static void coding_alloc_by_realloc (struct coding_system *, EMACS_INT);
++static ptrdiff_t coding_set_source (struct coding_system *);
++static ptrdiff_t coding_set_destination (struct coding_system *);
 +static void coding_alloc_by_realloc (struct coding_system *, ptrdiff_t);
  static void coding_alloc_by_making_gap (struct coding_system *,
 -                                        EMACS_INT, EMACS_INT);
 +                                        ptrdiff_t, ptrdiff_t);
  static unsigned char *alloc_destination (struct coding_system *,
 -                                         EMACS_INT, unsigned char *);
 +                                         ptrdiff_t, unsigned char *);
  static void setup_iso_safe_charsets (Lisp_Object);
- static unsigned char *encode_designation_at_bol (struct coding_system *,
-                                                  int *, unsigned char *);
+ static int encode_designation_at_bol (struct coding_system *,
+                                     int *, int *, unsigned char *);
  static int detect_eol (const unsigned char *,
 -                       EMACS_INT, enum coding_category);
 +                       ptrdiff_t, enum coding_category);
  static Lisp_Object adjust_coding_eol_type (struct coding_system *, int);
  static void decode_eol (struct coding_system *);
  static Lisp_Object get_translation_table (Lisp_Object, int, int *);
  static Lisp_Object get_translation (Lisp_Object, int *, int *);
  static int produce_chars (struct coding_system *, Lisp_Object, int);
  static inline void produce_charset (struct coding_system *, int *,
 -                                    EMACS_INT);
 -static void produce_annotation (struct coding_system *, EMACS_INT);
 +                                    ptrdiff_t);
 +static void produce_annotation (struct coding_system *, ptrdiff_t);
  static int decode_coding (struct coding_system *);
 -static inline int *handle_composition_annotation (EMACS_INT, EMACS_INT,
 +static inline int *handle_composition_annotation (ptrdiff_t, ptrdiff_t,
                                                    struct coding_system *,
 -                                                  int *, EMACS_INT *);
 -static inline int *handle_charset_annotation (EMACS_INT, EMACS_INT,
 +                                                  int *, ptrdiff_t *);
 +static inline int *handle_charset_annotation (ptrdiff_t, ptrdiff_t,
                                                struct coding_system *,
 -                                              int *, EMACS_INT *);
 +                                              int *, ptrdiff_t *);
  static void consume_chars (struct coding_system *, Lisp_Object, int);
  static int encode_coding (struct coding_system *);
  static Lisp_Object make_conversion_work_buffer (int);
@@@ -915,27 -915,68 +915,68 @@@ record_conversion_result (struct coding
      }
  }
  
- /* This wrapper macro is used to preserve validity of pointers into
-    buffer text across calls to decode_char, which could cause
-    relocation of buffers if it loads a charset map, because loading a
-    charset map allocates large structures.  */
+ /* These wrapper macros are used to preserve validity of pointers into
+    buffer text across calls to decode_char, encode_char, etc, which
+    could cause relocation of buffers if it loads a charset map,
+    because loading a charset map allocates large structures.  */
  #define CODING_DECODE_CHAR(coding, src, src_base, src_end, charset, code, c) \
    do {                                                                             \
 -    EMACS_INT offset;                                                      \
++    ptrdiff_t offset;                                                      \
+                                                                            \
      charset_map_loaded = 0;                                                \
      c = DECODE_CHAR (charset, code);                                       \
-     if (charset_map_loaded)                                                \
+     if (charset_map_loaded                                                 \
+       && (offset = coding_set_source (coding)))                            \
        {                                                                            \
-       const unsigned char *orig = coding->source;                          \
-       ptrdiff_t offset;                                                    \
-                                                                            \
-       coding_set_source (coding);                                          \
-       offset = coding->source - orig;                                      \
        src += offset;                                                       \
        src_base += offset;                                                  \
        src_end += offset;                                                   \
        }                                                                            \
    } while (0)
  
 -    EMACS_INT offset;                                                 \
+ #define CODING_ENCODE_CHAR(coding, dst, dst_end, charset, c, code)    \
+   do {                                                                        \
 -    EMACS_INT offset;                                                 \
++    ptrdiff_t offset;                                                 \
+                                                                       \
+     charset_map_loaded = 0;                                           \
+     code = ENCODE_CHAR (charset, c);                                  \
+     if (charset_map_loaded                                            \
+       && (offset = coding_set_destination (coding)))                  \
+       {                                                                       \
+       dst += offset;                                                  \
+       dst_end += offset;                                              \
+       }                                                                       \
+   } while (0)
+ #define CODING_CHAR_CHARSET(coding, dst, dst_end, c, charset_list, code_return, charset) \
+   do {                                                                        \
 -    EMACS_INT offset;                                                 \
++    ptrdiff_t offset;                                                 \
+                                                                       \
+     charset_map_loaded = 0;                                           \
+     charset = char_charset (c, charset_list, code_return);            \
+     if (charset_map_loaded                                            \
+       && (offset = coding_set_destination (coding)))                  \
+       {                                                                       \
+       dst += offset;                                                  \
+       dst_end += offset;                                              \
+       }                                                                       \
+   } while (0)
+ #define CODING_CHAR_CHARSET_P(coding, dst, dst_end, c, charset, result)       \
+   do {                                                                        \
++    ptrdiff_t offset;                                                 \
+                                                                       \
+     charset_map_loaded = 0;                                           \
+     result = CHAR_CHARSET_P (c, charset);                             \
+     if (charset_map_loaded                                            \
+       && (offset = coding_set_destination (coding)))                  \
+       {                                                                       \
+       dst += offset;                                                  \
+       dst_end += offset;                                              \
+       }                                                                       \
+   } while (0)
  
  /* If there are at least BYTES length of room at dst, allocate memory
     for coding->destination and update dst and dst_end.  We don't have
    do {                                                                \
      if (dst + (bytes) >= dst_end)                             \
        {                                                               \
 -      EMACS_INT more_bytes = charbuf_end - charbuf + (bytes); \
 +      ptrdiff_t more_bytes = charbuf_end - charbuf + (bytes); \
                                                                \
        dst = alloc_destination (coding, more_bytes, dst);      \
        dst_end = coding->destination + coding->dst_bytes;      \
         | ((p)[-1] & 0x3F))))
  
  
- static void
+ /* Update coding->source from coding->src_object, and return how many
+    bytes coding->source was changed.  */
 -static EMACS_INT
++static ptrdiff_t
  coding_set_source (struct coding_system *coding)
  {
+   const unsigned char *orig = coding->source;
    if (BUFFERP (coding->src_object))
      {
        struct buffer *buf = XBUFFER (coding->src_object);
        /* Otherwise, the source is C string and is never relocated
         automatically.  Thus we don't have to update anything.  */
      }
+   return coding->source - orig;
  }
  
- static void
+ /* Update coding->destination from coding->dst_object, and return how
+    many bytes coding->destination was changed.  */
 -static EMACS_INT
++static ptrdiff_t
  coding_set_destination (struct coding_system *coding)
  {
+   const unsigned char *orig = coding->destination;
    if (BUFFERP (coding->dst_object))
      {
        if (BUFFERP (coding->src_object) && coding->src_pos < 0)
        /* Otherwise, the destination is C string and is never relocated
         automatically.  Thus we don't have to update anything.  */
      }
+   return coding->destination - orig;
  }
  
  
  static void
 -coding_alloc_by_realloc (struct coding_system *coding, EMACS_INT bytes)
 +coding_alloc_by_realloc (struct coding_system *coding, ptrdiff_t bytes)
  {
    if (STRING_BYTES_BOUND - coding->dst_bytes < bytes)
      string_overflow ();
  
  static void
  coding_alloc_by_making_gap (struct coding_system *coding,
 -                          EMACS_INT gap_head_used, EMACS_INT bytes)
 +                          ptrdiff_t gap_head_used, ptrdiff_t bytes)
  {
    if (EQ (coding->src_object, coding->dst_object))
      {
         consumed data at the tail.  To preserve those data, we at
         first make the gap size to zero, then increase the gap
         size.  */
 -      EMACS_INT add = GAP_SIZE;
 +      ptrdiff_t add = GAP_SIZE;
  
        GPT += gap_head_used, GPT_BYTE += gap_head_used;
        GAP_SIZE = 0; ZV += add; Z += add; ZV_BYTE += add; Z_BYTE += add;
  
  
  static unsigned char *
 -alloc_destination (struct coding_system *coding, EMACS_INT nbytes,
 +alloc_destination (struct coding_system *coding, ptrdiff_t nbytes,
                   unsigned char *dst)
  {
 -  EMACS_INT offset = dst - coding->destination;
 +  ptrdiff_t offset = dst - coding->destination;
  
    if (BUFFERP (coding->dst_object))
      {
@@@ -1213,7 -1267,7 +1267,7 @@@ detect_coding_utf_8 (struct coding_syst
    const unsigned char *src = coding->source, *src_base;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int bom_found = 0;
    int found = 0;
  
@@@ -1298,7 -1352,7 +1352,7 @@@ decode_coding_utf_8 (struct coding_syst
    const unsigned char *src_base;
    int *charbuf = coding->charbuf + coding->charbuf_used;
    int *charbuf_end = coding->charbuf + coding->charbuf_size;
 -  EMACS_INT consumed_chars = 0, consumed_chars_base = 0;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base = 0;
    int multibytep = coding->src_multibyte;
    enum utf_bom_type bom = CODING_UTF_8_BOM (coding);
    int eol_dos =
@@@ -1449,7 -1503,7 +1503,7 @@@ encode_coding_utf_8 (struct coding_syst
    int *charbuf_end = charbuf + coding->charbuf_used;
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    int c;
  
    if (CODING_UTF_8_BOM (coding) == utf_with_bom)
@@@ -1607,7 -1661,7 +1661,7 @@@ decode_coding_utf_16 (struct coding_sys
    int *charbuf = coding->charbuf + coding->charbuf_used;
    /* We may produces at most 3 chars in one loop.  */
    int *charbuf_end = coding->charbuf + coding->charbuf_size - 2;
 -  EMACS_INT consumed_chars = 0, consumed_chars_base = 0;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base = 0;
    int multibytep = coding->src_multibyte;
    enum utf_bom_type bom = CODING_UTF_16_BOM (coding);
    enum utf_16_endian_type endian = CODING_UTF_16_ENDIAN (coding);
@@@ -1734,7 -1788,7 +1788,7 @@@ encode_coding_utf_16 (struct coding_sys
    int safe_room = 8;
    enum utf_bom_type bom = CODING_UTF_16_BOM (coding);
    int big_endian = CODING_UTF_16_ENDIAN (coding) == utf_16_big_endian;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    int c;
  
    if (bom != utf_without_bom)
@@@ -1868,7 -1922,7 +1922,7 @@@ detect_coding_emacs_mule (struct coding
    const unsigned char *src = coding->source, *src_base;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int c;
    int found = 0;
  
@@@ -2338,10 -2392,10 +2392,10 @@@ decode_coding_emacs_mule (struct coding
      = coding->charbuf + coding->charbuf_size - (MAX_ANNOTATION_LENGTH * 3)
        /* We can produce up to 2 characters in a loop.  */
        - 1;
 -  EMACS_INT consumed_chars = 0, consumed_chars_base;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT char_offset = coding->produced_char;
 -  EMACS_INT last_offset = char_offset;
 +  ptrdiff_t char_offset = coding->produced_char;
 +  ptrdiff_t last_offset = char_offset;
    int last_id = charset_ascii;
    int eol_dos =
      !inhibit_eol_conversion && EQ (CODING_ID_EOL_TYPE (coding->id), Qdos);
             original pointer to buffer text, and fix up all related
             pointers after the call.  */
          const unsigned char *orig = coding->source;
 -        EMACS_INT offset;
 +        ptrdiff_t offset;
  
          c = emacs_mule_char (coding, src_base, &nbytes, &nchars, &id,
                               cmp_status);
@@@ -2594,7 -2648,7 +2648,7 @@@ encode_coding_emacs_mule (struct coding
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
    int safe_room = 8;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    Lisp_Object attrs, charset_list;
    int c;
    int preferred_charset_id = -1;
  
          if (preferred_charset_id >= 0)
            {
+             int result;
              charset = CHARSET_FROM_ID (preferred_charset_id);
-             if (CHAR_CHARSET_P (c, charset))
+             CODING_CHAR_CHARSET_P (coding, dst, dst_end, c, charset, result);
+             if (result)
                code = ENCODE_CHAR (charset, c);
              else
-               charset = char_charset (c, charset_list, &code);
+               CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                                    &code, charset);
            }
          else
-           charset = char_charset (c, charset_list, &code);
+           CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                                &code, charset);
          if (! charset)
            {
              c = coding->default_char;
                  EMIT_ONE_ASCII_BYTE (c);
                  continue;
                }
-             charset = char_charset (c, charset_list, &code);
+             CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                                  &code, charset);
            }
          dimension = CHARSET_DIMENSION (charset);
          emacs_mule_id = CHARSET_EMACS_MULE_ID (charset);
@@@ -2881,7 -2941,7 +2941,7 @@@ setup_iso_safe_charsets (Lisp_Object at
    Lisp_Object request;
    Lisp_Object reg_usage;
    Lisp_Object tail;
 -  int reg94, reg96;
 +  EMACS_INT reg94, reg96;
    int flags = XINT (AREF (attrs, coding_attr_iso_flags));
    int max_charset_id;
  
@@@ -2952,7 -3012,7 +3012,7 @@@ detect_coding_iso_2022 (struct coding_s
    int single_shifting = 0;
    int id;
    int c, c1;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int i;
    int rejected = 0;
    int found = 0;
@@@ -3462,7 -3522,7 +3522,7 @@@ decode_coding_iso_2022 (struct coding_s
       loop and one more charset annotation at the end.  */
    int *charbuf_end
      = coding->charbuf + coding->charbuf_size - (MAX_ANNOTATION_LENGTH * 3);
 -  EMACS_INT consumed_chars = 0, consumed_chars_base;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base;
    int multibytep = coding->src_multibyte;
    /* Charsets invoked to graphic plane 0 and 1 respectively.  */
    int charset_id_0 = CODING_ISO_INVOKED_CHARSET (coding, 0);
    int c;
    struct composition_status *cmp_status = CODING_ISO_CMP_STATUS (coding);
    Lisp_Object attrs = CODING_ID_ATTRS (coding->id);
 -  EMACS_INT char_offset = coding->produced_char;
 -  EMACS_INT last_offset = char_offset;
 +  ptrdiff_t char_offset = coding->produced_char;
 +  ptrdiff_t last_offset = char_offset;
    int last_id = charset_ascii;
    int eol_dos =
      !inhibit_eol_conversion && EQ (CODING_ID_EOL_TYPE (coding->id), Qdos);
  
  #define ENCODE_ISO_CHARACTER(charset, c)                                 \
    do {                                                                           \
-     unsigned code = ENCODE_CHAR ((charset), (c));                        \
 -    int code;                                                            \
++    unsigned code;                                                       \
+     CODING_ENCODE_CHAR (coding, dst, dst_end, (charset), (c), code);     \
                                                                           \
      if (CHARSET_DIMENSION (charset) == 1)                                \
        ENCODE_ISO_CHARACTER_DIMENSION1 ((charset), code);                 \
  static unsigned char *
  encode_invocation_designation (struct charset *charset,
                               struct coding_system *coding,
 -                             unsigned char *dst, EMACS_INT *p_nchars)
 +                             unsigned char *dst, ptrdiff_t *p_nchars)
  {
    int multibytep = coding->dst_multibyte;
 -  EMACS_INT produced_chars = *p_nchars;
 +  ptrdiff_t produced_chars = *p_nchars;
    int reg;                    /* graphic register number */
    int id = CHARSET_ID (charset);
  
  
  
  /* Produce designation sequences of charsets in the line started from
-    SRC to a place pointed by DST, and return updated DST.
+    CHARBUF to a place pointed by DST, and return the number of
+    produced bytes.  DST should not directly point a buffer text area
+    which may be relocated by char_charset call.
  
     If the current block ends before any end-of-line, we may fail to
     find all the necessary designations.  */
  
- static unsigned char *
- encode_designation_at_bol (struct coding_system *coding, int *charbuf,
+ static int
+ encode_designation_at_bol (struct coding_system *coding,
+                          int *charbuf, int *charbuf_end,
                           unsigned char *dst)
  {
+   unsigned char *orig = dst;
    struct charset *charset;
    /* Table of charsets to be designated to each graphic register.  */
    int r[4];
    int c, found = 0, reg;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    int multibytep = coding->dst_multibyte;
    Lisp_Object attrs;
    Lisp_Object charset_list;
    for (reg = 0; reg < 4; reg++)
      r[reg] = -1;
  
-   while (found < 4)
+   while (charbuf < charbuf_end && found < 4)
      {
        int id;
  
          ENCODE_DESIGNATION (CHARSET_FROM_ID (r[reg]), reg, coding);
      }
  
-   return dst;
+   return dst - orig;
  }
  
  /* See the above "GENERAL NOTES on `encode_coding_XXX ()' functions".  */
@@@ -4351,7 -4416,7 +4416,7 @@@ encode_coding_iso_2022 (struct coding_s
    int bol_designation
      = (CODING_ISO_FLAGS (coding) & CODING_ISO_FLAG_DESIGNATE_AT_BOL
         && CODING_ISO_BOL (coding));
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    Lisp_Object attrs, eol_type, charset_list;
    int ascii_compatible;
    int c;
  
        if (bol_designation)
        {
-         unsigned char *dst_prev = dst;
          /* We have to produce designation sequences if any now.  */
-         dst = encode_designation_at_bol (coding, charbuf, dst);
-         bol_designation = 0;
+         unsigned char desig_buf[16];
+         int nbytes;
 -        EMACS_INT offset;
++        ptrdiff_t offset;
+         charset_map_loaded = 0;
+         nbytes = encode_designation_at_bol (coding, charbuf, charbuf_end,
+                                             desig_buf);
+         if (charset_map_loaded
+             && (offset = coding_set_destination (coding)))
+           {
+             dst += offset;
+             dst_end += offset;
+           }
+         memcpy (dst, desig_buf, nbytes);
+         dst += nbytes;
          /* We are sure that designation sequences are all ASCII bytes.  */
-         produced_chars += dst - dst_prev;
+         produced_chars += nbytes;
+         bol_designation = 0;
+         ASSURE_DESTINATION (safe_room);
        }
  
        c = *charbuf++;
  
          if (preferred_charset_id >= 0)
            {
+             int result;
              charset = CHARSET_FROM_ID (preferred_charset_id);
-             if (! CHAR_CHARSET_P (c, charset))
-               charset = char_charset (c, charset_list, NULL);
+             CODING_CHAR_CHARSET_P (coding, dst, dst_end, c, charset, result);
+             if (! result)
+               CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                                    NULL, charset);
            }
          else
-           charset = char_charset (c, charset_list, NULL);
+           CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                                NULL, charset);
          if (!charset)
            {
              if (coding->mode & CODING_MODE_SAFE_ENCODING)
              else
                {
                  c = coding->default_char;
-                 charset = char_charset (c, charset_list, NULL);
+                 CODING_CHAR_CHARSET (coding, dst, dst_end, c,
+                                      charset_list, NULL, charset);
                }
            }
          ENCODE_ISO_CHARACTER (charset, c);
@@@ -4539,7 -4623,7 +4623,7 @@@ detect_coding_sjis (struct coding_syste
    const unsigned char *src = coding->source, *src_base;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int found = 0;
    int c;
    Lisp_Object attrs, charset_list;
@@@ -4596,7 -4680,7 +4680,7 @@@ detect_coding_big5 (struct coding_syste
    const unsigned char *src = coding->source, *src_base;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int found = 0;
    int c;
  
@@@ -4647,13 -4731,13 +4731,13 @@@ decode_coding_sjis (struct coding_syste
       the end.  */
    int *charbuf_end
      = coding->charbuf + coding->charbuf_size - (MAX_ANNOTATION_LENGTH * 2);
 -  EMACS_INT consumed_chars = 0, consumed_chars_base;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base;
    int multibytep = coding->src_multibyte;
    struct charset *charset_roman, *charset_kanji, *charset_kana;
    struct charset *charset_kanji2;
    Lisp_Object attrs, charset_list, val;
 -  EMACS_INT char_offset = coding->produced_char;
 -  EMACS_INT last_offset = char_offset;
 +  ptrdiff_t char_offset = coding->produced_char;
 +  ptrdiff_t last_offset = char_offset;
    int last_id = charset_ascii;
    int eol_dos =
      !inhibit_eol_conversion && EQ (CODING_ID_EOL_TYPE (coding->id), Qdos);
@@@ -4765,12 -4849,12 +4849,12 @@@ decode_coding_big5 (struct coding_syste
       the end.  */
    int *charbuf_end
      = coding->charbuf + coding->charbuf_size - (MAX_ANNOTATION_LENGTH * 2);
 -  EMACS_INT consumed_chars = 0, consumed_chars_base;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base;
    int multibytep = coding->src_multibyte;
    struct charset *charset_roman, *charset_big5;
    Lisp_Object attrs, charset_list, val;
 -  EMACS_INT char_offset = coding->produced_char;
 -  EMACS_INT last_offset = char_offset;
 +  ptrdiff_t char_offset = coding->produced_char;
 +  ptrdiff_t last_offset = char_offset;
    int last_id = charset_ascii;
    int eol_dos =
      !inhibit_eol_conversion && EQ (CODING_ID_EOL_TYPE (coding->id), Qdos);
@@@ -4867,7 -4951,7 +4951,7 @@@ encode_coding_sjis (struct coding_syste
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
    int safe_room = 4;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    Lisp_Object attrs, charset_list, val;
    int ascii_compatible;
    struct charset *charset_kanji, *charset_kana;
        else
        {
          unsigned code;
-         struct charset *charset = char_charset (c, charset_list, &code);
+         struct charset *charset;
+         CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                              &code, charset);
  
          if (!charset)
            {
              else
                {
                  c = coding->default_char;
-                 charset = char_charset (c, charset_list, &code);
+                 CODING_CHAR_CHARSET (coding, dst, dst_end, c,
+                                      charset_list, &code, charset);
                }
            }
          if (code == CHARSET_INVALID_CODE (charset))
@@@ -4958,7 -5045,7 +5045,7 @@@ encode_coding_big5 (struct coding_syste
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
    int safe_room = 4;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    Lisp_Object attrs, charset_list, val;
    int ascii_compatible;
    struct charset *charset_big5;
        else
        {
          unsigned code;
-         struct charset *charset = char_charset (c, charset_list, &code);
+         struct charset *charset;
+         CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                              &code, charset);
  
          if (! charset)
            {
              else
                {
                  c = coding->default_char;
-                 charset = char_charset (c, charset_list, &code);
+                 CODING_CHAR_CHARSET (coding, dst, dst_end, c,
+                                      charset_list, &code, charset);
                }
            }
          if (code == CHARSET_INVALID_CODE (charset))
@@@ -5033,10 -5123,10 +5123,10 @@@ detect_coding_ccl (struct coding_syste
    const unsigned char *src = coding->source, *src_base;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int found = 0;
    unsigned char *valids;
 -  EMACS_INT head_ascii = coding->head_ascii;
 +  ptrdiff_t head_ascii = coding->head_ascii;
    Lisp_Object attrs;
  
    detect_info->checked |= CATEGORY_MASK_CCL;
@@@ -5073,7 -5163,7 +5163,7 @@@ decode_coding_ccl (struct coding_syste
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int *charbuf = coding->charbuf + coding->charbuf_used;
    int *charbuf_end = coding->charbuf + coding->charbuf_size;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    int multibytep = coding->src_multibyte;
    struct ccl_program *ccl = &coding->spec.ccl->ccl;
    int source_charbuf[1024];
@@@ -5145,7 -5235,7 +5235,7 @@@ encode_coding_ccl (struct coding_syste
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
    int destination_charbuf[1024];
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    int i;
    Lisp_Object attrs, charset_list;
  
        && coding->mode & CODING_MODE_LAST_BLOCK)
      ccl->last_block = 1;
  
-   while (charbuf < charbuf_end)
+   do
      {
        ccl_driver (ccl, charbuf, destination_charbuf,
                  charbuf_end - charbuf, 1024, charset_list);
          || ccl->status == CCL_STAT_INVALID_CMD)
        break;
      }
+   while (charbuf < charbuf_end);
  
    switch (ccl->status)
      {
@@@ -5232,7 -5323,7 +5323,7 @@@ encode_coding_raw_text (struct coding_s
    int *charbuf_end = coding->charbuf + coding->charbuf_used;
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    int c;
  
    if (multibytep)
@@@ -5315,10 -5406,10 +5406,10 @@@ detect_coding_charset (struct coding_sy
    const unsigned char *src = coding->source, *src_base;
    const unsigned char *src_end = coding->source + coding->src_bytes;
    int multibytep = coding->src_multibyte;
 -  EMACS_INT consumed_chars = 0;
 +  ptrdiff_t consumed_chars = 0;
    Lisp_Object attrs, valids, name;
    int found = 0;
 -  EMACS_INT head_ascii = coding->head_ascii;
 +  ptrdiff_t head_ascii = coding->head_ascii;
    int check_latin_extra = 0;
  
    detect_info->checked |= CATEGORY_MASK_CHARSET;
@@@ -5422,12 -5513,12 +5513,12 @@@ decode_coding_charset (struct coding_sy
       the end.  */
    int *charbuf_end
      = coding->charbuf + coding->charbuf_size - (MAX_ANNOTATION_LENGTH * 2);
 -  EMACS_INT consumed_chars = 0, consumed_chars_base;
 +  ptrdiff_t consumed_chars = 0, consumed_chars_base;
    int multibytep = coding->src_multibyte;
    Lisp_Object attrs = CODING_ID_ATTRS (coding->id);
    Lisp_Object valids;
 -  EMACS_INT char_offset = coding->produced_char;
 -  EMACS_INT last_offset = char_offset;
 +  ptrdiff_t char_offset = coding->produced_char;
 +  ptrdiff_t last_offset = char_offset;
    int last_id = charset_ascii;
    int eol_dos =
      !inhibit_eol_conversion && EQ (CODING_ID_EOL_TYPE (coding->id), Qdos);
@@@ -5548,7 -5639,7 +5639,7 @@@ encode_coding_charset (struct coding_sy
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
    int safe_room = MAX_MULTIBYTE_LENGTH;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced_chars = 0;
    Lisp_Object attrs, charset_list;
    int ascii_compatible;
    int c;
        }
        else
        {
-         charset = char_charset (c, charset_list, &code);
+         CODING_CHAR_CHARSET (coding, dst, dst_end, c, charset_list,
+                              &code, charset);
          if (charset)
            {
              if (CHARSET_DIMENSION (charset) == 1)
@@@ -6095,7 -6188,7 +6188,7 @@@ complement_process_encoding_system (Lis
  #define MAX_EOL_CHECK_COUNT 3
  
  static int
 -detect_eol (const unsigned char *source, EMACS_INT src_bytes,
 +detect_eol (const unsigned char *source, ptrdiff_t src_bytes,
            enum coding_category category)
  {
    const unsigned char *src = source, *src_end = src + src_bytes;
@@@ -6456,7 -6549,7 +6549,7 @@@ decode_eol (struct coding_system *codin
      }
    else if (EQ (eol_type, Qdos))
      {
 -      EMACS_INT n = 0;
 +      ptrdiff_t n = 0;
  
        if (NILP (coding->dst_object))
        {
        }
        else
        {
 -        EMACS_INT pos_byte = coding->dst_pos_byte;
 -        EMACS_INT pos = coding->dst_pos;
 -        EMACS_INT pos_end = pos + coding->produced_char - 1;
 +        ptrdiff_t pos_byte = coding->dst_pos_byte;
 +        ptrdiff_t pos = coding->dst_pos;
 +        ptrdiff_t pos_end = pos + coding->produced_char - 1;
  
          while (pos < pos_end)
            {
@@@ -6613,8 -6706,8 +6706,8 @@@ get_translation (Lisp_Object trans, in
      {
        Lisp_Object val = XCAR (trans);
        Lisp_Object from = XCAR (val);
 -      int len = ASIZE (from);
 -      int i;
 +      ptrdiff_t len = ASIZE (from);
 +      ptrdiff_t i;
  
        for (i = 0; i < len; i++)
        {
@@@ -6636,8 -6729,8 +6729,8 @@@ produce_chars (struct coding_system *co
  {
    unsigned char *dst = coding->destination + coding->produced;
    unsigned char *dst_end = coding->destination + coding->dst_bytes;
 -  EMACS_INT produced;
 -  EMACS_INT produced_chars = 0;
 +  ptrdiff_t produced;
 +  ptrdiff_t produced_chars = 0;
    int carryover = 0;
  
    if (! coding->chars_at_source)
  
          if (c >= 0)
            {
 -            EMACS_INT from_nchars = 1, to_nchars = 1;
 +            ptrdiff_t from_nchars = 1, to_nchars = 1;
              Lisp_Object trans = Qnil;
  
              LOOKUP_TRANSLATION_TABLE (translation_table, c, trans);
          if (coding->src_multibyte)
            {
              int multibytep = 1;
 -            EMACS_INT consumed_chars = 0;
 +            ptrdiff_t consumed_chars = 0;
  
              while (1)
                {
                        dst_end = (unsigned char *) src;
                      if (dst == dst_end)
                        {
 -                        EMACS_INT offset = src - coding->source;
 +                        ptrdiff_t offset = src - coding->source;
  
                          dst = alloc_destination (coding, src_end - src + 1,
                                                   dst);
                      dst_end = (unsigned char *) src;
                    if (dst >= dst_end - 1)
                      {
 -                      EMACS_INT offset = src - coding->source;
 -                      EMACS_INT more_bytes;
 +                      ptrdiff_t offset = src - coding->source;
 +                      ptrdiff_t more_bytes;
  
                        if (EQ (coding->src_object, coding->dst_object))
                          more_bytes = ((src_end - src) / 2) + 2;
        {
          if (!EQ (coding->src_object, coding->dst_object))
            {
 -            EMACS_INT require = coding->src_bytes - coding->dst_bytes;
 +            ptrdiff_t require = coding->src_bytes - coding->dst_bytes;
  
              if (require > 0)
                {
 -                EMACS_INT offset = src - coding->source;
 +                ptrdiff_t offset = src - coding->source;
  
                  dst = alloc_destination (coding, require, dst);
                  coding_set_source (coding);
   */
  
  static inline void
 -produce_composition (struct coding_system *coding, int *charbuf, EMACS_INT pos)
 +produce_composition (struct coding_system *coding, int *charbuf, ptrdiff_t pos)
  {
    int len;
 -  EMACS_INT to;
 +  ptrdiff_t to;
    enum composition_method method;
    Lisp_Object components;
  
   */
  
  static inline void
 -produce_charset (struct coding_system *coding, int *charbuf, EMACS_INT pos)
 +produce_charset (struct coding_system *coding, int *charbuf, ptrdiff_t pos)
  {
 -  EMACS_INT from = pos - charbuf[2];
 +  ptrdiff_t from = pos - charbuf[2];
    struct charset *charset = CHARSET_FROM_ID (charbuf[3]);
  
    Fput_text_property (make_number (from), make_number (pos),
  
  
  static void
 -produce_annotation (struct coding_system *coding, EMACS_INT pos)
 +produce_annotation (struct coding_system *coding, ptrdiff_t pos)
  {
    int *charbuf = coding->charbuf;
    int *charbuf_end = charbuf + coding->charbuf_used;
@@@ -7013,7 -7106,7 +7106,7 @@@ decode_coding (struct coding_system *co
      }
    do
      {
 -      EMACS_INT pos = coding->dst_pos + coding->produced_char;
 +      ptrdiff_t pos = coding->dst_pos + coding->produced_char;
  
        coding_set_source (coding);
        coding->annotated = 0;
     return BUF.  */
  
  static inline int *
 -handle_composition_annotation (EMACS_INT pos, EMACS_INT limit,
 +handle_composition_annotation (ptrdiff_t pos, ptrdiff_t limit,
                               struct coding_system *coding, int *buf,
 -                             EMACS_INT *stop)
 +                             ptrdiff_t *stop)
  {
 -  EMACS_INT start, end;
 +  ptrdiff_t start, end;
    Lisp_Object prop;
  
    if (! find_composition (pos, limit, &start, &end, &prop, coding->src_object)
          if (method != COMPOSITION_RELATIVE)
            {
              Lisp_Object components;
 -            int len, i, i_byte;
 +            ptrdiff_t i, len, i_byte;
  
              components = COMPOSITION_COMPONENTS (prop);
              if (VECTORP (components))
     property value is non-nil (limiting by LIMIT), and return BUF.  */
  
  static inline int *
 -handle_charset_annotation (EMACS_INT pos, EMACS_INT limit,
 +handle_charset_annotation (ptrdiff_t pos, ptrdiff_t limit,
                           struct coding_system *coding, int *buf,
 -                         EMACS_INT *stop)
 +                         ptrdiff_t *stop)
  {
    Lisp_Object val, next;
    int id;
@@@ -7218,12 -7311,12 +7311,12 @@@ consume_chars (struct coding_system *co
    int *buf_end = coding->charbuf + coding->charbuf_size;
    const unsigned char *src = coding->source + coding->consumed;
    const unsigned char *src_end = coding->source + coding->src_bytes;
 -  EMACS_INT pos = coding->src_pos + coding->consumed_char;
 -  EMACS_INT end_pos = coding->src_pos + coding->src_chars;
 +  ptrdiff_t pos = coding->src_pos + coding->consumed_char;
 +  ptrdiff_t end_pos = coding->src_pos + coding->src_chars;
    int multibytep = coding->src_multibyte;
    Lisp_Object eol_type;
    int c;
 -  EMACS_INT stop, stop_composition, stop_charset;
 +  ptrdiff_t stop, stop_composition, stop_charset;
    int *lookup_buf = NULL;
  
    if (! NILP (translation_table))
  
        if (! multibytep)
        {
 -        EMACS_INT bytes;
 +        int bytes;
  
          if (coding->encoder == encode_coding_raw_text
              || coding->encoder == encode_coding_ccl)
        *buf++ = c;
        else
        {
 -        int from_nchars = 1, to_nchars = 1;
 +        ptrdiff_t from_nchars = 1, to_nchars = 1;
          int *lookup_buf_end;
          const unsigned char *p = src;
          int i;
              else
                {
                  to_nchars = ASIZE (trans);
 -                if (buf + to_nchars > buf_end)
 +                if (buf_end - buf < to_nchars)
                    break;
                  c = XINT (AREF (trans, 0));
                }
@@@ -7498,9 -7591,9 +7591,9 @@@ code_conversion_save (int with_work_buf
  
  int
  decode_coding_gap (struct coding_system *coding,
 -                 EMACS_INT chars, EMACS_INT bytes)
 +                 ptrdiff_t chars, ptrdiff_t bytes)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object attrs;
  
    code_conversion_save (0, 0);
    attrs = CODING_ID_ATTRS (coding->id);
    if (! NILP (CODING_ATTR_POST_READ (attrs)))
      {
 -      EMACS_INT prev_Z = Z, prev_Z_BYTE = Z_BYTE;
 +      ptrdiff_t prev_Z = Z, prev_Z_BYTE = Z_BYTE;
        Lisp_Object val;
  
        TEMP_SET_PT_BOTH (coding->dst_pos, coding->dst_pos_byte);
  void
  decode_coding_object (struct coding_system *coding,
                      Lisp_Object src_object,
 -                    EMACS_INT from, EMACS_INT from_byte,
 -                    EMACS_INT to, EMACS_INT to_byte,
 +                    ptrdiff_t from, ptrdiff_t from_byte,
 +                    ptrdiff_t to, ptrdiff_t to_byte,
                      Lisp_Object dst_object)
  {
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    unsigned char *destination IF_LINT (= NULL);
 -  EMACS_INT dst_bytes IF_LINT (= 0);
 -  EMACS_INT chars = to - from;
 -  EMACS_INT bytes = to_byte - from_byte;
 +  ptrdiff_t dst_bytes IF_LINT (= 0);
 +  ptrdiff_t chars = to - from;
 +  ptrdiff_t bytes = to_byte - from_byte;
    Lisp_Object attrs;
    int saved_pt = -1, saved_pt_byte IF_LINT (= 0);
    int need_marker_adjustment = 0;
    if (! NILP (CODING_ATTR_POST_READ (attrs)))
      {
        struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
 -      EMACS_INT prev_Z = Z, prev_Z_BYTE = Z_BYTE;
 +      ptrdiff_t prev_Z = Z, prev_Z_BYTE = Z_BYTE;
        Lisp_Object val;
  
        TEMP_SET_PT_BOTH (coding->dst_pos, coding->dst_pos_byte);
  void
  encode_coding_object (struct coding_system *coding,
                      Lisp_Object src_object,
 -                    EMACS_INT from, EMACS_INT from_byte,
 -                    EMACS_INT to, EMACS_INT to_byte,
 +                    ptrdiff_t from, ptrdiff_t from_byte,
 +                    ptrdiff_t to, ptrdiff_t to_byte,
                      Lisp_Object dst_object)
  {
 -  int count = SPECPDL_INDEX ();
 -  EMACS_INT chars = to - from;
 -  EMACS_INT bytes = to_byte - from_byte;
 +  ptrdiff_t count = SPECPDL_INDEX ();
 +  ptrdiff_t chars = to - from;
 +  ptrdiff_t bytes = to_byte - from_byte;
    Lisp_Object attrs;
    int saved_pt = -1, saved_pt_byte IF_LINT (= 0);
    int need_marker_adjustment = 0;
@@@ -8019,7 -8112,7 +8112,7 @@@ are lower-case).  */
    (Lisp_Object prompt, Lisp_Object default_coding_system)
  {
    Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    if (SYMBOLP (default_coding_system))
      default_coding_system = SYMBOL_NAME (default_coding_system);
@@@ -8071,7 -8164,7 +8164,7 @@@ function `define-coding-system'.  */
  
  Lisp_Object
  detect_coding_system (const unsigned char *src,
 -                    EMACS_INT src_chars, EMACS_INT src_bytes,
 +                    ptrdiff_t src_chars, ptrdiff_t src_bytes,
                      int highest, int multibytep,
                      Lisp_Object coding_system)
  {
@@@ -8391,8 -8484,8 +8484,8 @@@ If optional argument HIGHEST is non-nil
  highest priority.  */)
    (Lisp_Object start, Lisp_Object end, Lisp_Object highest)
  {
 -  int from, to;
 -  int from_byte, to_byte;
 +  ptrdiff_t from, to;
 +  ptrdiff_t from_byte, to_byte;
  
    CHECK_NUMBER_COERCE_MARKER (start);
    CHECK_NUMBER_COERCE_MARKER (end);
@@@ -8472,7 -8565,7 +8565,7 @@@ DEFUN ("find-coding-systems-region-inte
    (Lisp_Object start, Lisp_Object end, Lisp_Object exclude)
  {
    Lisp_Object coding_attrs_list, safe_codings;
 -  EMACS_INT start_byte, end_byte;
 +  ptrdiff_t start_byte, end_byte;
    const unsigned char *p, *pbeg, *pend;
    int c;
    Lisp_Object tail, elt, work_table;
            }
          if (charset_map_loaded)
            {
 -            EMACS_INT p_offset = p - pbeg, pend_offset = pend - pbeg;
 +            ptrdiff_t p_offset = p - pbeg, pend_offset = pend - pbeg;
  
              if (STRINGP (start))
                pbeg = SDATA (start);
@@@ -8604,11 -8697,11 +8697,11 @@@ for un-encodable characters.  In that c
  to the string.  */)
    (Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object count, Lisp_Object string)
  {
 -  int n;
 +  EMACS_INT n;
    struct coding_system coding;
    Lisp_Object attrs, charset_list, translation_table;
    Lisp_Object positions;
 -  int from, to;
 +  ptrdiff_t from, to;
    const unsigned char *p, *stop, *pend;
    int ascii_compatible;
  
        CHECK_STRING (string);
        CHECK_NATNUM (start);
        CHECK_NATNUM (end);
 +      if (! (XINT (start) <= XINT (end) && XINT (end) <= SCHARS (string)))
 +      args_out_of_range_3 (string, start, end);
        from = XINT (start);
        to = XINT (end);
 -      if (from > to
 -        || to > SCHARS (string))
 -      args_out_of_range_3 (string, start, end);
        if (! STRING_MULTIBYTE (string))
        return Qnil;
        p = SDATA (string) + string_char_to_byte (string, from);
@@@ -8719,8 -8813,8 +8812,8 @@@ is nil.  */
    (Lisp_Object start, Lisp_Object end, Lisp_Object coding_system_list)
  {
    Lisp_Object list;
 -  EMACS_INT start_byte, end_byte;
 -  int pos;
 +  ptrdiff_t start_byte, end_byte;
 +  ptrdiff_t pos;
    const unsigned char *p, *pbeg, *pend;
    int c;
    Lisp_Object tail, elt, attrs;
            }
          if (charset_map_loaded)
            {
 -            EMACS_INT p_offset = p - pbeg, pend_offset = pend - pbeg;
 +            ptrdiff_t p_offset = p - pbeg, pend_offset = pend - pbeg;
  
              if (STRINGP (start))
                pbeg = SDATA (start);
@@@ -8826,7 -8920,7 +8919,7 @@@ code_convert_region (Lisp_Object start
                     int encodep, int norecord)
  {
    struct coding_system coding;
 -  EMACS_INT from, from_byte, to, to_byte;
 +  ptrdiff_t from, from_byte, to, to_byte;
    Lisp_Object src_object;
  
    CHECK_NUMBER_COERCE_MARKER (start);
@@@ -8914,7 -9008,7 +9007,7 @@@ code_convert_string (Lisp_Object string
                     Lisp_Object dst_object, int encodep, int nocopy, int norecord)
  {
    struct coding_system coding;
 -  EMACS_INT chars, bytes;
 +  ptrdiff_t chars, bytes;
  
    CHECK_STRING (string);
    if (NILP (coding_system))
@@@ -9207,7 -9301,7 +9300,7 @@@ frame's terminal device.  */
      = TERMINAL_TERMINAL_CODING (get_terminal (terminal, 1));
    Lisp_Object coding_system = CODING_ID_NAME (terminal_coding->id);
  
-   /* For backward compatibility, return nil if it is `undecided'. */
+   /* For backward compatibility, return nil if it is `undecided'.  */
    return (! EQ (coding_system, Qundecided) ? coding_system : Qnil);
  }
  
@@@ -9289,9 -9383,9 +9382,9 @@@ usage: (find-operation-coding-system OP
      error ("Too few arguments");
    operation = args[0];
    if (!SYMBOLP (operation)
 -      || !NATNUMP (target_idx = Fget (operation, Qtarget_idx)))
 +      || (target_idx = Fget (operation, Qtarget_idx), !NATNUMP (target_idx)))
      error ("Invalid first argument");
 -  if (nargs < 1 + XFASTINT (target_idx))
 +  if (nargs <= 1 + XFASTINT (target_idx))
      error ("Too few arguments for operation `%s'",
           SDATA (SYMBOL_NAME (operation)));
    target = args[XFASTINT (target_idx) + 1];
@@@ -9510,12 -9604,8 +9603,12 @@@ usage: (define-coding-system-internal .
          charset_list = Vemacs_mule_charset_list;
        }
        for (tail = charset_list; CONSP (tail); tail = XCDR (tail))
 -      if (max_charset_id < XFASTINT (XCAR (tail)))
 -        max_charset_id = XFASTINT (XCAR (tail));
 +      {
 +        if (! RANGED_INTEGERP (0, XCAR (tail), INT_MAX - 1))
 +          error ("Invalid charset-list");
 +        if (max_charset_id < XFASTINT (XCAR (tail)))
 +          max_charset_id = XFASTINT (XCAR (tail));
 +      }
      }
    else
      {
          val = Fcar (tail);
          if (INTEGERP (val))
            {
 -            from = to = XINT (val);
 -            if (from < 0 || from > 255)
 +            if (! (0 <= XINT (val) && XINT (val) <= 255))
                args_out_of_range_3 (val, make_number (0), make_number (255));
 +            from = to = XINT (val);
            }
          else
            {
              CHECK_CONS (val);
              CHECK_NATNUM_CAR (val);
 -            CHECK_NATNUM_CDR (val);
 -            from = XINT (XCAR (val));
 -            if (from > 255)
 +            CHECK_NUMBER_CDR (val);
 +            if (XINT (XCAR (val)) > 255)
                args_out_of_range_3 (XCAR (val),
                                     make_number (0), make_number (255));
 -            to = XINT (XCDR (val));
 -            if (to < from || to > 255)
 +            from = XINT (XCAR (val));
 +            if (! (from <= XINT (XCDR (val)) && XINT (XCDR (val)) <= 255))
                args_out_of_range_3 (XCDR (val),
                                     XCAR (val), make_number (255));
 +            to = XINT (XCDR (val));
            }
          for (i = from; i <= to; i++)
            SSET (valids, i, 1);
  
        flags = args[coding_arg_iso2022_flags];
        CHECK_NATNUM (flags);
 -      i = XINT (flags);
 +      i = XINT (flags) & INT_MAX;
        if (EQ (args[coding_arg_charset_list], Qiso_2022))
 -      flags = make_number (i | CODING_ISO_FLAG_FULL_SUPPORT);
 +      i |= CODING_ISO_FLAG_FULL_SUPPORT;
 +      flags = make_number (i);
  
        ASET (attrs, coding_attr_iso_initial, initial);
        ASET (attrs, coding_attr_iso_usage, reg_usage);
diff --combined src/coding.h
index 2165fa237122fddae017cc1384f2845c4a0e75f7,b694e6c6b6ea31ca9251ef9bd2d50b3be1b19d8a..711e41ed5b8dd26686e8a4d2db05fdb45a7631b9
@@@ -449,25 -449,25 +449,25 @@@ struct coding_syste
       -1 in setup_coding_system, and updated by detect_coding.  So,
       when this is equal to the byte length of the text being
       converted, we can skip the actual conversion process.  */
 -  EMACS_INT head_ascii;
 +  ptrdiff_t head_ascii;
  
    /* The following members are set by encoding/decoding routine.  */
 -  EMACS_INT produced, produced_char, consumed, consumed_char;
 +  ptrdiff_t produced, produced_char, consumed, consumed_char;
  
    /* Number of error source data found in a decoding routine.  */
    int errors;
  
-   /* Store the positions of error source data. */
+   /* Store the positions of error source data.  */
 -  EMACS_INT *error_positions;
 +  ptrdiff_t *error_positions;
  
    /* Finish status of code conversion.  */
    enum coding_result_code result;
  
 -  EMACS_INT src_pos, src_pos_byte, src_chars, src_bytes;
 +  ptrdiff_t src_pos, src_pos_byte, src_chars, src_bytes;
    Lisp_Object src_object;
    const unsigned char *source;
  
 -  EMACS_INT dst_pos, dst_pos_byte, dst_bytes;
 +  ptrdiff_t dst_pos, dst_pos_byte, dst_bytes;
    Lisp_Object dst_object;
    unsigned char *destination;
  
@@@ -704,13 -704,13 +704,13 @@@ extern Lisp_Object coding_inherit_eol_t
  extern Lisp_Object complement_process_encoding_system (Lisp_Object);
  
  extern int decode_coding_gap (struct coding_system *,
 -                              EMACS_INT, EMACS_INT);
 +                              ptrdiff_t, ptrdiff_t);
  extern void decode_coding_object (struct coding_system *,
 -                                  Lisp_Object, EMACS_INT, EMACS_INT,
 -                                  EMACS_INT, EMACS_INT, Lisp_Object);
 +                                  Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                                  ptrdiff_t, ptrdiff_t, Lisp_Object);
  extern void encode_coding_object (struct coding_system *,
 -                                  Lisp_Object, EMACS_INT, EMACS_INT,
 -                                  EMACS_INT, EMACS_INT, Lisp_Object);
 +                                  Lisp_Object, ptrdiff_t, ptrdiff_t,
 +                                  ptrdiff_t, ptrdiff_t, Lisp_Object);
  
  /* Macros for backward compatibility.  */
  
diff --combined src/data.c
index 7b30e91b12f343982d24108e8473c593119cd64a,0ebb17a2e01a9e516ea3ee11b1432291b7ad18ff..2337b0a4952e4c518b6347bf8a4497cebcf63ac5
@@@ -839,7 -839,7 +839,7 @@@ do_symval_forwarding (register union Li
  
      case Lisp_Fwd_Kboard_Obj:
        /* We used to simply use current_kboard here, but from Lisp
-        code, it's value is often unexpected.  It seems nicer to
+        code, its value is often unexpected.  It seems nicer to
         allow constructions like this to work as intuitively expected:
  
         (with-selected-frame frame
@@@ -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));
diff --combined src/dbusbind.c
index 352f2fc1ff8bf2cb3e70489e02a4fcee1a6fb1ae,7984be3564b8053a7a4e87b69296e70226d6db23..7801ec259bb9b3db3a56d9cbf9c33e46f02e62e5
@@@ -184,7 -184,7 +184,7 @@@ static int xd_in_read_queued_messages 
  #endif
  
  /* This was a macro.  On Solaris 2.11 it was said to compile for
-    hours, when optimzation is enabled.  So we have transferred it into
+    hours, when optimization is enabled.  So we have transferred it into
     a function.  */
  /* Determine the DBusType of a given Lisp symbol.  OBJECT must be one
     of the predefined D-Bus type symbols.  */
@@@ -485,7 -485,7 +485,7 @@@ xd_append_arg (unsigned int dtype, Lisp
        }
  
        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);
        }
  
        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);
        }
  
        case DBUS_TYPE_INT32:
 -      CHECK_NUMBER (object);
 +      CHECK_TYPE_RANGED_INTEGER (dbus_int32_t, object);
        {
          dbus_int32_t val = XINT (object);
          XD_DEBUG_MESSAGE ("%c %d", dtype, val);
  #ifdef DBUS_TYPE_UNIX_FD
        case DBUS_TYPE_UNIX_FD:
  #endif
 -      CHECK_NATNUM (object);
 +      CHECK_TYPE_RANGED_INTEGER (dbus_uint32_t, object);
        {
          dbus_uint32_t val = XFASTINT (object);
          XD_DEBUG_MESSAGE ("%c %u", dtype, val);
        }
  
        case DBUS_TYPE_UINT64:
 -      CHECK_NATNUM (object);
 +      CHECK_TYPE_RANGED_INTEGER (dbus_uint64_t, object);
        {
          dbus_uint64_t val = XFASTINT (object);
          XD_DEBUG_MESSAGE ("%c %"pI"d", dtype, XFASTINT (object));
@@@ -1145,7 -1145,7 +1145,7 @@@ usage: (dbus-call-method BUS SERVICE PA
    if ((i+2 <= nargs) && (EQ ((args[i]), QCdbus_timeout)))
      {
        CHECK_NATNUM (args[i+1]);
 -      timeout = XFASTINT (args[i+1]);
 +      timeout = min (XFASTINT (args[i+1]), INT_MAX);
        i = i+2;
      }
  
@@@ -1328,7 -1328,7 +1328,7 @@@ usage: (dbus-call-method-asynchronousl
    if ((i+2 <= nargs) && (EQ ((args[i]), QCdbus_timeout)))
      {
        CHECK_NATNUM (args[i+1]);
 -      timeout = XFASTINT (args[i+1]);
 +      timeout = min (XFASTINT (args[i+1]), INT_MAX);
        i = i+2;
      }
  
diff --combined src/dired.c
index 3a3adfb50829e29401e97cd53f4e440d82e6fcd8,2b5f3b406415c312e43529b30617717815819f73..1d112db8a93752ac27dd442c9a7d8669ab13e8f4
@@@ -86,7 -86,7 +86,7 @@@ static Lisp_Object Qfile_name_all_compl
  static Lisp_Object Qfile_attributes;
  static Lisp_Object Qfile_attributes_lessp;
  
 -static int scmp (const char *, const char *, int);
 +static ptrdiff_t scmp (const char *, const char *, ptrdiff_t);
  static Lisp_Object Ffile_attributes (Lisp_Object, Lisp_Object);
  \f
  #ifdef WINDOWSNT
@@@ -117,11 -117,11 +117,11 @@@ Lisp_Objec
  directory_files_internal (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, int attrs, Lisp_Object id_format)
  {
    DIR *d;
 -  int directory_nbytes;
 +  ptrdiff_t directory_nbytes;
    Lisp_Object list, dirfilename, encoded_directory;
    struct re_pattern_buffer *bufp = NULL;
    int needsep = 0;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
    DIRENTRY *dp;
  #ifdef WINDOWSNT
  
        if (DIRENTRY_NONEMPTY (dp))
        {
 -        int len;
 +        ptrdiff_t len;
          int wanted = 0;
          Lisp_Object name, finalname;
-         struct gcpro inner_gcpro1, inner_gcpro2;
+         struct gcpro gcpro1, gcpro2;
  
          len = NAMLEN (dp);
          name = finalname = make_unibyte_string (dp->d_name, len);
-         GCPRO2_VAR (finalname, name, inner_gcpro);
+         GCPRO2 (finalname, name);
  
          /* Note: DECODE_FILE can GC; it should protect its argument,
             though.  */
              if (!NILP (full))
                {
                  Lisp_Object fullname;
 -                int nbytes = len + directory_nbytes + needsep;
 -                int nchars;
 +                ptrdiff_t nbytes = len + directory_nbytes + needsep;
 +                ptrdiff_t nchars;
  
                  fullname = make_uninit_multibyte_string (nbytes, nbytes);
                  memcpy (SDATA (fullname), SDATA (directory),
                  /* Construct an expanded filename for the directory entry.
                     Use the decoded names for input to Ffile_attributes.  */
                  Lisp_Object decoded_fullname, fileattrs;
-                 struct gcpro innermost_gcpro1, innermost_gcpro2;
+                 struct gcpro gcpro1, gcpro2;
  
                  decoded_fullname = fileattrs = Qnil;
-                 GCPRO2_VAR (decoded_fullname, fileattrs, innermost_gcpro);
+                 GCPRO2 (decoded_fullname, fileattrs);
  
                  /* Both Fexpand_file_name and Ffile_attributes can GC.  */
                  decoded_fullname = Fexpand_file_name (name, directory);
                  fileattrs = Ffile_attributes (decoded_fullname, id_format);
  
                  list = Fcons (Fcons (finalname, fileattrs), list);
-                 UNGCPRO_VAR (innermost_gcpro);
+                 UNGCPRO;
                }
              else
                list = Fcons (finalname, list);
            }
  
-         UNGCPRO_VAR (inner_gcpro);
+         UNGCPRO;
        }
      }
  
@@@ -449,7 -449,7 +449,7 @@@ static Lisp_Objec
  file_name_completion (Lisp_Object file, Lisp_Object dirname, int all_flag, int ver_flag, Lisp_Object predicate)
  {
    DIR *d;
 -  int bestmatchsize = 0;
 +  ptrdiff_t bestmatchsize = 0;
    int matchcount = 0;
    /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
       If ALL_FLAG is 0, BESTMATCH is either nil
       well as "." and "..".  Until shown otherwise, assume we can't exclude
       anything.  */
    int includeall = 1;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
  
    elt = Qnil;
    while (1)
      {
        DIRENTRY *dp;
 -      int len;
 +      ptrdiff_t len;
        int canexclude = 0;
  
        errno = 0;
         completions when making a list of them.  */
        if (!all_flag)
        {
 -        int skip;
 +        ptrdiff_t skip;
  
  #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
          /* If this entry matches the current bestmatch, the only
                for (tem = Vcompletion_ignored_extensions;
                     CONSP (tem); tem = XCDR (tem))
                  {
 -                  int elt_len;
 +                  ptrdiff_t elt_len;
                    char *p1;
  
                    elt = XCAR (tem);
        if (!NILP (predicate))
        {
          Lisp_Object val;
-         struct gcpro inner_gcpro1;
+         struct gcpro gcpro1;
  
-         GCPRO1_VAR (name, inner_gcpro);
+         GCPRO1 (name);
          val = call1 (predicate, name);
-         UNGCPRO_VAR (inner_gcpro);
+         UNGCPRO;
  
          if (NILP (val))
            continue;
  
        /* Suitably record this match.  */
  
 -      matchcount++;
 +      matchcount += matchcount <= 1;
  
        if (all_flag)
        bestmatch = Fcons (name, bestmatch);
        {
          Lisp_Object zero = make_number (0);
          /* FIXME: This is a copy of the code in Ftry_completion.  */
 -        int compare = min (bestmatchsize, SCHARS (name));
 +        ptrdiff_t compare = min (bestmatchsize, SCHARS (name));
          Lisp_Object cmp
            = Fcompare_strings (bestmatch, zero,
                                make_number (compare),
                                name, zero,
                                make_number (compare),
                                completion_ignore_case ? Qt : Qnil);
 -        int matchsize
 +        ptrdiff_t matchsize
            = (EQ (cmp, Qt)     ? compare
               : XINT (cmp) < 0 ? - XINT (cmp) - 1
               :                  XINT (cmp) - 1);
     Return -1 if strings match,
     else number of chars that match at the beginning.  */
  
 -static int
 -scmp (const char *s1, const char *s2, int len)
 +static ptrdiff_t
 +scmp (const char *s1, const char *s2, ptrdiff_t len)
  {
 -  register int l = len;
 +  register ptrdiff_t l = len;
  
    if (completion_ignore_case)
      {
  static int
  file_name_completion_stat (Lisp_Object dirname, DIRENTRY *dp, struct stat *st_addr)
  {
 -  int len = NAMLEN (dp);
 -  int pos = SCHARS (dirname);
 +  ptrdiff_t len = NAMLEN (dp);
 +  ptrdiff_t pos = SCHARS (dirname);
    int value;
 -  char *fullname = (char *) alloca (len + pos + 2);
 +  char *fullname;
 +  USE_SAFE_ALLOCA;
 +  SAFE_ALLOCA (fullname, char *, len + pos + 2);
  
  #ifdef MSDOS
    /* Some fields of struct stat are *very* expensive to compute on MS-DOS,
  #ifdef MSDOS
    _djstat_flags = save_djstat_flags;
  #endif /* MSDOS */
 +  SAFE_FREE ();
    return value;
  }
  \f
diff --combined src/dispextern.h
index ccb85e7422e03dad0fff8a3987a0981787dc29f2,5228a71ba3faf8ec9520471e3c460d73a325d6a5..9d5feea6024952fe0908137a37e1fd2bf8888872
@@@ -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
    {
      /* Metrics of a partial glyph of an image (type == IMAGE_GLYPH).  */
      struct glyph_slice img;
-     /* Start and end indices of glyphs of a graphme cluster of a
+     /* Start and end indices of glyphs of a grapheme cluster of a
         composition (type == COMPOSITE_GLYPH).  */
      struct { int from, to; } cmp;
      /* Pixel offsets for upper and lower part of the acronym.  */
@@@ -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.  */
@@@ -2649,11 -2649,11 +2649,11 @@@ struct redisplay_interfac
    void (*flush_display) (struct frame *f);
  
    /* Flush the display of frame F if non-NULL.  This is called
-      during redisplay, and should be NULL on systems which flushes
+      during redisplay, and should be NULL on systems which flush
       automatically before reading input.  */
    void (*flush_display_optional) (struct frame *f);
  
-   /* Clear the mouse hightlight in window W, if there is any.  */
+   /* Clear the mouse highlight in window W, if there is any.  */
    void (*clear_window_mouse_face) (struct window *w);
  
    /* Set *LEFT and *RIGHT to the left and right overhang of GLYPH on
@@@ -2984,7 -2984,7 +2984,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);
@@@ -2995,11 -2995,11 +2995,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
@@@ -3021,18 -3021,18 +3021,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 *);
@@@ -3042,15 -3042,15 +3042,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 *);
  
@@@ -3096,7 -3096,7 +3096,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 *,
@@@ -3127,9 -3127,7 +3127,7 @@@ void w32_init_fringe (struct redisplay_
  void w32_reset_fringes (void);
  #endif
  
- #if XASSERTS
  extern unsigned row_hash (struct glyph_row *);
- #endif
  
  /* Defined in image.c */
  
@@@ -3204,19 -3202,19 +3202,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;
@@@ -3282,11 -3280,11 +3280,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 *);
@@@ -3306,7 -3304,7 +3304,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
index 88f75414074352920d910e4bf6fc2c3b70d949b5,2c0e74d0dde851efa09b32da6937835533fe900a..e53e3fdf80db27fff7049135db9c3baba5ac2336
@@@ -108,7 -108,7 +108,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 *);
@@@ -431,7 -431,7 +431,7 @@@ margin_glyphs_to_reserve (struct windo
  
  #if XASSERTS
  /* Return non-zero if ROW's hash value is correct, zero if not.  */
static int
+ int
  verify_row_hash (struct glyph_row *row)
  {
    return row->hash == row_hash (row);
@@@ -608,7 -608,6 +608,6 @@@ adjust_glyph_matrix (struct window *w, 
                  row->glyphs[LAST_AREA]
                    = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
                }
-             xassert (!row->enabled_p || verify_row_hash (row));
              ++row;
            }
        }
@@@ -759,7 -758,7 +758,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);
@@@ -1001,7 -1000,7 +1000,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;
  
@@@ -2543,7 -2542,8 +2542,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);
@@@ -3575,12 -3575,11 +3574,11 @@@ update_window (struct window *w, int fo
  
        rif->update_window_begin_hook (w);
        yb = window_text_bottom_y (w);
-       /* If window has a header line, update it before everything else.
-        Adjust y-positions of other rows by the header line height.  */
        row = desired_matrix->rows;
        end = row + desired_matrix->nrows - 1;
  
+       /* Take note of the header line, if there is one.  We will
+        update it below, after updating all of the window's lines.  */
        if (row->mode_line_p)
        {
          header_line_row = row;
  
        /* Update the rest of the lines.  */
        for (; row < end && (force_p || !input_pending); ++row)
+       /* scrolling_window resets the enabled_p flag of the rows it
+          reuses from current_matrix.  */
        if (row->enabled_p)
          {
            int vpos = MATRIX_ROW_VPOS (row, desired_matrix);
@@@ -4550,18 -4551,69 +4550,69 @@@ scrolling_window (struct window *w, in
          {
            rif->clear_window_mouse_face (w);
            rif->scroll_run_hook (w, r);
+         }
  
-           /* Invalidate runs that copy from where we copied to.  */
-           for (j = i + 1; j < nruns; ++j)
+       /* Truncate runs that copy to where we copied to, and
+          invalidate runs that copy from where we copied to.  */
+       for (j = nruns - 1; j > i; --j)
+         {
+           struct run *p = runs[j];
+           int truncated_p = 0;
+           if (p->nrows > 0
+               && p->desired_y < r->desired_y + r->height
+               && p->desired_y + p->height > r->desired_y)
              {
-               struct run *p = runs[j];
+               if (p->desired_y < r->desired_y)
+                 {
+                   p->nrows = r->desired_vpos - p->desired_vpos;
+                   p->height = r->desired_y - p->desired_y;
+                   truncated_p = 1;
+                 }
+               else
+                 {
+                   int nrows_copied = (r->desired_vpos + r->nrows
+                                       - p->desired_vpos);
+                   if (p->nrows <= nrows_copied)
+                     p->nrows = 0;
+                   else
+                     {
+                       int height_copied = (r->desired_y + r->height
+                                            - p->desired_y);
+                       p->current_vpos += nrows_copied;
+                       p->desired_vpos += nrows_copied;
+                       p->nrows -= nrows_copied;
+                       p->current_y += height_copied;
+                       p->desired_y += height_copied;
+                       p->height -= height_copied;
+                       truncated_p = 1;
+                     }
+                 }
+             }
  
-               if ((p->current_y >= r->desired_y
+           if (r->current_y != r->desired_y
+               /* The condition below is equivalent to
+                  ((p->current_y >= r->desired_y
                     && p->current_y < r->desired_y + r->height)
-                   || (p->current_y + p->height >= r->desired_y
+                   || (p->current_y + p->height > r->desired_y
                        && (p->current_y + p->height
-                           < r->desired_y + r->height)))
-                 p->nrows = 0;
+                           <= r->desired_y + r->height)))
+                  because we have 0 < p->height <= r->height.  */
+               && p->current_y < r->desired_y + r->height
+               && p->current_y + p->height > r->desired_y)
+             p->nrows = 0;
+           /* Reorder runs by copied pixel lines if truncated.  */
+           if (truncated_p && p->nrows > 0)
+             {
+               int k = nruns - 1;
+               while (runs[k]->nrows == 0 || runs[k]->height < p->height)
+                 k--;
+               memmove (runs + j, runs + j + 1, (k - j) * sizeof (*runs));
+               runs[k] = p;
              }
          }
  
            to_overlapped_p = to->overlapped_p;
            from->redraw_fringe_bitmaps_p = from->fringe_bitmap_periodic_p;
            assign_row (to, from);
-           to->enabled_p = 1, from->enabled_p = 0;
+           /* The above `assign_row' actually does swap, so if we had
+              an overlap in the copy destination of two runs, then
+              the second run would assign a previously disabled bogus
+              row.  But thanks to the truncation code in the
+              preceding for-loop, we no longer have such an overlap,
+              and thus the assigned row should always be enabled.  */
+           xassert (to->enabled_p);
+           from->enabled_p = 0;
            to->overlapped_p = to_overlapped_p;
          }
        }
@@@ -5415,7 -5474,7 +5473,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;
@@@ -5681,7 -5740,7 +5739,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))
@@@ -5899,38 -5958,6 +5957,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
@@@ -5941,24 -5968,39 +5999,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;
@@@ -5989,20 -6031,27 +6047,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);
@@@ -6022,7 -6071,7 +6080,7 @@@ perform a full redisplay even if input 
  Return t if redisplay was performed, nil otherwise.  */)
    (Lisp_Object force)
  {
 -  int count;
 +  ptrdiff_t count;
  
    swallow_events (1);
    if ((detect_input_pending_run_timers (1)
@@@ -6068,7 -6117,7 +6126,7 @@@ pass nil for VARIABLE.  */
  {
    Lisp_Object state, tail, frame, buf;
    Lisp_Object *vecp, *end;
 -  int n;
 +  ptrdiff_t n;
  
    if (! NILP (variable))
      {
diff --combined src/emacs.c
index a5d2f619b8ca0556c4e40e73d0696228e774af62,6bfc0dc60d0f42dffe991a297fdba2065cbcb2b2..4c8d3298495fc788e7b4e0d3381c8a4b629c4bfe
@@@ -112,15 -112,15 +112,15 @@@ int gdb_use_union EXTERNALLY_VISIBLE  
  #else
  int gdb_use_union EXTERNALLY_VISIBLE = 1;
  #endif
 -EMACS_INT gdb_valbits EXTERNALLY_VISIBLE = VALBITS;
 -EMACS_INT gdb_gctypebits EXTERNALLY_VISIBLE = GCTYPEBITS;
 +int gdb_valbits EXTERNALLY_VISIBLE = VALBITS;
 +int gdb_gctypebits EXTERNALLY_VISIBLE = GCTYPEBITS;
  #if defined (DATA_SEG_BITS) && ! defined (USE_LSB_TAG)
 -EMACS_INT gdb_data_seg_bits EXTERNALLY_VISIBLE = DATA_SEG_BITS;
 +uintptr_t gdb_data_seg_bits EXTERNALLY_VISIBLE = DATA_SEG_BITS;
  #else
 -EMACS_INT gdb_data_seg_bits EXTERNALLY_VISIBLE = 0;
 +uintptr_t gdb_data_seg_bits EXTERNALLY_VISIBLE = 0;
  #endif
 -EMACS_INT PVEC_FLAG EXTERNALLY_VISIBLE = PSEUDOVECTOR_FLAG;
 -EMACS_INT gdb_array_mark_flag EXTERNALLY_VISIBLE = ARRAY_MARK_FLAG;
 +ptrdiff_t PVEC_FLAG EXTERNALLY_VISIBLE = PSEUDOVECTOR_FLAG;
 +ptrdiff_t gdb_array_mark_flag EXTERNALLY_VISIBLE = ARRAY_MARK_FLAG;
  /* GDB might say "No enum type named pvec_type" if we don't have at
     least one symbol with that type, and then xbacktrace could fail.  */
  enum pvec_type gdb_pvec_type EXTERNALLY_VISIBLE = PVEC_TYPE_MASK;
@@@ -154,6 -154,8 +154,8 @@@ Lisp_Object Qfile_name_handler_alist
  
  Lisp_Object Qrisky_local_variable;
  
+ Lisp_Object Qkill_emacs;
  /* If non-zero, Emacs should not attempt to use a window-specific code,
     but instead should use the virtual terminal under which it was started.  */
  int inhibit_window_system;
@@@ -397,7 -399,7 +399,7 @@@ init_cmdargs (int argc, char **argv, in
  {
    register int i;
    Lisp_Object name, dir, handler;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object raw_name;
  
    initial_argv = argv;
@@@ -2019,15 -2021,10 +2021,15 @@@ all of which are called before Emacs i
    if (STRINGP (Vauto_save_list_file_name))
      unlink (SSDATA (Vauto_save_list_file_name));
  
 -  exit_code = EXIT_SUCCESS;
 -  if (noninteractive && (fflush (stdout) || ferror (stdout)))
 +  if (INTEGERP (arg))
 +    exit_code = (XINT (arg) < 0
 +               ? XINT (arg) | INT_MIN
 +               : XINT (arg) & INT_MAX);
 +  else if (noninteractive && (fflush (stdout) || ferror (stdout)))
      exit_code = EXIT_FAILURE;
 -  exit (INTEGERP (arg) ? XINT (arg) : exit_code);
 +  else
 +    exit_code = EXIT_SUCCESS;
 +  exit (exit_code);
  }
  
  
@@@ -2137,7 -2134,7 +2139,7 @@@ You must run Emacs in batch mode in ord
  {
    Lisp_Object tem;
    Lisp_Object symbol;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    check_pure_size ();
  
@@@ -2399,6 -2396,7 +2401,7 @@@ syms_of_emacs (void
  {
    DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
    DEFSYM (Qrisky_local_variable, "risky-local-variable");
+   DEFSYM (Qkill_emacs, "kill-emacs");
  
  #ifndef CANNOT_DUMP
    defsubr (&Sdump_emacs);
diff --combined src/eval.c
index c6bf2ccef1db39c348f3780e5d4f32c41586ea89,079c7ecb6c2306f6ddbc062c3bb27cde9cb1979b..b604df8f35be4d7d8d131e080378f1d50ebc62d1
@@@ -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.  */
@@@ -177,7 -177,7 +177,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;
  
@@@ -373,14 -373,23 +373,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;
@@@ -393,12 -402,31 +393,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,
@@@ -730,8 -758,8 +730,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");
@@@ -805,9 -833,9 +805,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",
@@@ -955,7 -983,7 +955,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);
@@@ -1018,7 -1046,7 +1018,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;
@@@ -1321,7 -1349,7 +1321,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));
@@@ -1601,6 -1629,18 +1601,18 @@@ static Lisp_Object find_handler_clause 
  static int maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
                                Lisp_Object data);
  
+ void
+ process_quit_flag (void)
+ {
+   Lisp_Object flag = Vquit_flag;
+   Vquit_flag = Qnil;
+   if (EQ (flag, Qkill_emacs))
+     Fkill_emacs (Qnil);
+   if (EQ (Vthrow_on_input, flag))
+     Fthrow (Vthrow_on_input, Qt);
+   Fsignal (Qquit, Qnil);
+ }
  DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
         doc: /* Signal an error.  Args are ERROR-SYMBOL and associated DATA.
  This function does not return.
@@@ -2095,7 -2135,7 +2107,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;
  
@@@ -2142,7 -2182,7 +2154,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));
@@@ -2376,8 -2416,7 +2388,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;
@@@ -3027,8 -3066,7 +3039,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;
@@@ -3073,7 -3111,7 +3085,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;
  
@@@ -3212,8 -3250,12 +3224,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;
  }
  
@@@ -3351,7 -3395,7 +3363,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;
@@@ -3431,7 -3475,7 +3443,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);
  
@@@ -3701,7 -3745,7 +3713,7 @@@ When lexical binding is not being used
  A value of `(t)' indicates an empty environment, otherwise it is an
  alist of active lexical bindings.  */);
    Vinternal_interpreter_environment = Qnil;
-   /* Don't export this variable to Elisp, so noone can mess with it
+   /* Don't export this variable to Elisp, so no one can mess with it
       (Just imagine if someone makes it buffer-local).  */
    Funintern (Qinternal_interpreter_environment, Qnil);
  
diff --combined src/fileio.c
index 110977b3a602f0523ef93c2fdbee884bfab20fa2,fb021cee5a47a57a1ac72aeacd41769e715c8a34..3139e634c803888ac7007d26c416715468d0ad4a
@@@ -62,7 -62,7 +62,7 @@@ along with GNU Emacs.  If not, see <htt
  
  #ifdef DOS_NT
  /* On Windows, drive letters must be alphabetic - on DOS, the Netware
-    redirector allows the six letters between 'Z' and 'a' as well. */
+    redirector allows the six letters between 'Z' and 'a' as well.  */
  #ifdef MSDOS
  #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
  #endif
@@@ -70,7 -70,7 +70,7 @@@
  #define IS_DRIVE(x) isalpha ((unsigned char) (x))
  #endif
  /* Need to lower-case the drive letter, or else expanded
-    filenames will sometimes compare inequal, because
+    filenames will sometimes compare unequal, because
     `expand-file-name' doesn't always down-case the drive letter.  */
  #define DRIVE_LETTER(x) (tolower ((unsigned char) (x)))
  #endif
@@@ -145,9 -145,9 +145,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
@@@ -257,7 -257,7 +257,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;
  
@@@ -338,7 -338,7 +338,7 @@@ Given a Unix syntax file name, returns 
  
    while (p != beg && !IS_DIRECTORY_SEP (p[-1])
  #ifdef DOS_NT
-        /* only recognise drive specifier at the beginning */
+        /* only recognize drive specifier at the beginning */
         && !(p[-1] == ':'
              /* handle the "/:d:foo" and "/:foo" cases correctly  */
              && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
@@@ -401,7 -401,7 +401,7 @@@ or the entire name if it contains no sl
  
    while (p != beg && !IS_DIRECTORY_SEP (p[-1])
  #ifdef DOS_NT
-        /* only recognise drive specifier at beginning */
+        /* only recognize drive specifier at beginning */
         && !(p[-1] == ':'
              /* handle the "/:d:foo" case correctly  */
              && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
@@@ -1553,7 -1553,7 +1553,7 @@@ those `/' is discarded.  */
    if (p)
      /* Start over with the new string, so we check the file-name-handler
         again.  Important with filenames like "/home/foo//:/hello///there"
-        which whould substitute to "/:/hello///there" rather than "/there".  */
+        which would substitute to "/:/hello///there" rather than "/there".  */
      return Fsubstitute_in_file_name
        (make_specified_string (p, -1, endp - p, multibyte));
  
@@@ -1813,12 -1813,12 +1813,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
@@@ -2210,7 -2210,7 +2210,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,
@@@ -3055,8 -3055,6 +3055,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
@@@ -3101,8 -3099,8 +3101,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;
@@@ -3178,16 -3176,16 +3178,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;
  
        conversion_buffer = code_conversion_save (1, multibyte);
  
        {
          /* 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) */
+         /* `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),
      adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
                         inserted);
  
+   /* Call after-change hooks for the inserted text, aside from the case
+      of normal visiting (not with REPLACE), which is done in a new buffer
+      "before" the buffer is changed.  */
+   if (inserted > 0 && total > 0
+       && (NILP (visit) || !NILP (replace)))
+     {
+       signal_after_change (PT, 0, inserted);
+       update_compositions (PT, PT, CHECK_BORDER);
+     }
    /* Now INSERTED is measured in characters.  */
  
   handled:
                      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
          /* If REPLACE is non-nil and we succeeded in not replacing the
             beginning or end of the buffer text with the file's contents,
             call format-decode with `point' positioned at the beginning
-            of the buffer and `inserted' equalling the number of
+            of the buffer and `inserted' equaling the number of
             characters in the buffer.  Otherwise, format-decode might
             fail to correctly analyze the beginning or end of the buffer.
             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
        unbind_to (count1, Qnil);
      }
  
-   /* Call after-change hooks for the inserted text, aside from the case
-      of normal visiting (not with REPLACE), which is done in a new buffer
-      "before" the buffer is changed.  */
-   if (inserted > 0 && total > 0
-       && (NILP (visit) || !NILP (replace)))
-     {
-       signal_after_change (PT, 0, inserted);
-       update_compositions (PT, PT, CHECK_BORDER);
-     }
    if (!NILP (visit)
        && current_buffer->modtime == -1)
      {
@@@ -4468,7 -4462,7 +4469,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;
@@@ -4868,13 -4862,13 +4869,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))
@@@ -5231,7 -5225,7 +5232,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
index 2c9559f742b258205615ffb399f75b4c58a0d93d,04b51d10d9bb7481519a44037fde5969f3ef17e6..121143439e074f7f97a4988530e4eaef418a6963
+++ b/src/fns.c
@@@ -250,8 -250,8 +250,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 -341,8 +345,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 -465,8 +469,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 -476,8 +480,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 -883,7 +894,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 -916,7 +927,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 -1010,7 +1021,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 -1043,7 +1054,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 -1092,12 +1103,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 -1145,27 +1156,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 -1213,47 +1213,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 -1601,7 +1595,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 -2079,7 +2073,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 -2146,7 +2140,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 -2214,7 +2206,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 -2324,12 +2316,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 -2362,7 +2354,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 -2649,7 +2642,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 -2952,9 +2945,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 -2965,9 +2958,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 -3023,7 +3016,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 -3163,11 +3156,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 -3225,7 +3218,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;
  
    return decoded_string;
  }
  
- /* Base64-decode the data at FROM of LENGHT bytes into TO.  If
+ /* Base64-decode the data at FROM of LENGTH bytes into TO.  If
     MULTIBYTE is nonzero, the decoded result should be in multibyte
     form.  If NCHARS_RETRUN 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 -3432,23 +3425,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 -3569,6 +3570,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 -3599,7 +3604,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 -3720,9 +3726,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 -3806,7 +3813,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 -3858,7 +3865,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 -3907,7 +3914,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 -3945,7 +3952,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 -4526,7 +4533,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 -4575,10 +4582,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.c
index cb27155f09defb60d9f38add762f369287a0b430,6ab65281a48b3051608d8fd87a9c2562069fcaae..64ac36d364c3ac6c1abf00945c3b9605d56f9b15
@@@ -238,7 -238,7 +238,7 @@@ font_intern_prop (const char *str, ptrd
    ptrdiff_t i;
    Lisp_Object tem;
    Lisp_Object obarray;
 -  EMACS_INT nbytes, nchars;
 +  ptrdiff_t nbytes, nchars;
  
    if (len == 1 && *str == '*')
      return Qnil;
@@@ -364,7 -364,7 +364,7 @@@ font_style_to_value (enum font_property
    else
      {
        int i, last_n;
 -      int numeric = XINT (val);
 +      EMACS_INT numeric = XINT (val);
  
        for (i = 0, last_n = -1; i < len; i++)
        {
@@@ -518,7 -518,7 +518,7 @@@ font_prop_validate_style (Lisp_Object s
                                   : FONT_WIDTH_INDEX);
    if (INTEGERP (val))
      {
 -      int n = XINT (val);
 +      EMACS_INT n = XINT (val);
        if (((n >> 4) & 0xF)
          >= ASIZE (AREF (font_style_table, prop - FONT_WEIGHT_INDEX)))
        val = Qerror;
@@@ -614,7 -614,7 +614,7 @@@ static const struc
    /* Function to validate PROP's value VAL, or NULL if any value is
       ok.  The value is VAL or its regularized value if VAL is valid,
       and Qerror if not.  */
-   Lisp_Object (*validater) (Lisp_Object prop, Lisp_Object val);
+   Lisp_Object (*validator) (Lisp_Object prop, Lisp_Object val);
  } font_property_table[] =
    { { &QCtype, font_prop_validate_symbol },
      { &QCfoundry, font_prop_validate_symbol },
@@@ -672,7 -672,7 +672,7 @@@ font_prop_validate (int idx, Lisp_Objec
        if (idx < 0)
        return val;
      }
-   validated = (font_property_table[idx].validater) (prop, val);
+   validated = (font_property_table[idx].validator) (prop, val);
    if (EQ (validated, Qerror))
      signal_error ("invalid font property", Fcons (prop, val));
    return validated;
@@@ -825,7 -825,7 +825,7 @@@ font_expand_wildcards (Lisp_Object *fie
      range_mask = (range_mask << 1) | 1;
  
    /* The triplet RANGE_FROM, RANGE_TO, and RANGE_MASK is a
-      position-based retriction for FIELD[I].  */
+      position-based restriction for FIELD[I].  */
    for (i = 0, range_from = 0, range_to = 14 - n; i < n;
         i++, range_from++, range_to++, range_mask <<= 1)
      {
        else
        {
          /* The triplet FROM, TO, and MASK is a value-based
-            retriction for FIELD[I].  */
+            restriction for FIELD[I].  */
          int from, to;
          unsigned mask;
  
          if (INTEGERP (val))
            {
 -            int numeric = XINT (val);
 +            EMACS_INT numeric = XINT (val);
  
              if (i + 1 == n)
                from = to = XLFD_ENCODING_INDEX,
@@@ -1740,8 -1740,7 +1740,8 @@@ static in
  check_gstring (Lisp_Object gstring)
  {
    Lisp_Object val;
 -  int i, j;
 +  ptrdiff_t i;
 +  int j;
  
    CHECK_VECTOR (gstring);
    val = AREF (gstring, 0);
@@@ -2434,7 -2433,7 +2434,7 @@@ font_match_p (Lisp_Object spec, Lisp_Ob
                  /* All characters in the list must be supported.  */
                  for (; CONSP (val2); val2 = XCDR (val2))
                    {
 -                    if (! NATNUMP (XCAR (val2)))
 +                    if (! CHARACTERP (XCAR (val2)))
                        continue;
                      if (font_encode_char (font, XFASTINT (XCAR (val2)))
                          == FONT_INVALID_CODE)
                  /* At most one character in the vector must be supported.  */
                  for (i = 0; i < ASIZE (val2); i++)
                    {
 -                    if (! NATNUMP (AREF (val2, i)))
 +                    if (! CHARACTERP (AREF (val2, i)))
                        continue;
                      if (font_encode_char (font, XFASTINT (AREF (val2, i)))
                          != FONT_INVALID_CODE)
@@@ -3077,7 -3076,6 +3077,7 @@@ font_find_for_lface (FRAME_PTR f, Lisp_
    Lisp_Object foundry[3], *family, registry[3], adstyle[3];
    int pixel_size;
    int i, j, k, l;
 +  USE_SAFE_ALLOCA;
  
    registry[0] = AREF (spec, FONT_REGISTRY_INDEX);
    if (NILP (registry[0]))
    else
      {
        Lisp_Object alters
-       = Fassoc_string (val, Vface_alternative_font_family_alist,
-                          /* Font family names are case-sensitive under NS. */
- #ifndef HAVE_NS
-                        Qt
- #else
-                        Qnil
- #endif
-                        );
+       = Fassoc_string (val, Vface_alternative_font_family_alist, Qt);
  
        if (! NILP (alters))
        {
 -        family = alloca ((sizeof family[0]) * (XINT (Flength (alters)) + 2));
 +        EMACS_INT alterslen = XFASTINT (Flength (alters));
 +        SAFE_ALLOCA_LISP (family, alterslen + 2);
          for (i = 0; CONSP (alters); i++, alters = XCDR (alters))
            family[i] = XCAR (alters);
          if (NILP (AREF (spec, FONT_FAMILY_INDEX)))
            }
        }
      }
 +
 +  SAFE_FREE ();
    return Qnil;
  }
  
@@@ -3616,7 -3604,7 +3609,7 @@@ font_filter_properties (Lisp_Object fon
     STRING.  */
  
  static Lisp_Object
 -font_at (int c, EMACS_INT pos, struct face *face, struct window *w,
 +font_at (int c, ptrdiff_t pos, struct face *face, struct window *w,
         Lisp_Object string)
  {
    FRAME_PTR f;
        {
          if (multibyte)
            {
 -            EMACS_INT pos_byte = CHAR_TO_BYTE (pos);
 +            ptrdiff_t pos_byte = CHAR_TO_BYTE (pos);
  
              c = FETCH_CHAR (pos_byte);
            }
          multibyte = STRING_MULTIBYTE (string);
          if (multibyte)
            {
 -            EMACS_INT pos_byte = string_char_to_byte (string, pos);
 +            ptrdiff_t pos_byte = string_char_to_byte (string, pos);
  
              str = SDATA (string) + pos_byte;
              c = STRING_CHAR (str);
    if (! face)
      {
        int face_id;
 -      EMACS_INT endptr;
 +      ptrdiff_t endptr;
  
        if (STRINGP (string))
        face_id = face_at_string_position (w, string, pos, 0, -1, -1, &endptr,
     It is assured that the current buffer (or STRING) is multibyte.  */
  
  Lisp_Object
 -font_range (EMACS_INT pos, EMACS_INT *limit, struct window *w, struct face *face, Lisp_Object string)
 +font_range (ptrdiff_t pos, ptrdiff_t *limit, struct window *w, struct face *face, Lisp_Object string)
  {
 -  EMACS_INT pos_byte, ignore;
 +  ptrdiff_t pos_byte, ignore;
    int c;
    Lisp_Object font_object = Qnil;
  
@@@ -4107,7 -4095,7 +4100,7 @@@ how close they are to PREFER.  */
    (Lisp_Object font_spec, Lisp_Object frame, Lisp_Object num, Lisp_Object prefer)
  {
    Lisp_Object vec, list;
 -  int n = 0;
 +  EMACS_INT n = 0;
  
    if (NILP (frame))
      frame = selected_frame;
  font_fill_lglyph_metrics (Lisp_Object glyph, Lisp_Object font_object)
  {
    struct font *font = XFONT_OBJECT (font_object);
 -  unsigned code;
 -  /* ecode used in LGLYPH_SET_CODE to avoid compiler warnings.  */
 -  EMACS_INT ecode = font->driver->encode_char (font, LGLYPH_CHAR (glyph));
 +  unsigned code = font->driver->encode_char (font, LGLYPH_CHAR (glyph));
    struct font_metrics metrics;
  
 -  LGLYPH_SET_CODE (glyph, ecode);
 -  code = ecode;
 +  LGLYPH_SET_CODE (glyph, code);
    font->driver->text_extents (font, &code, 1, &metrics);
    LGLYPH_SET_LBEARING (glyph, metrics.lbearing);
    LGLYPH_SET_RBEARING (glyph, metrics.rbearing);
@@@ -4299,7 -4290,7 +4292,7 @@@ created glyph-string.  Otherwise, the v
  {
    struct font *font;
    Lisp_Object font_object, n, glyph;
 -  EMACS_INT i, j, from, to;
 +  ptrdiff_t i, j, from, to;
  
    if (! composition_gstring_p (gstring))
      signal_error ("Invalid glyph-string: ", gstring);
        if (INTEGERP (n))
        break;
        gstring = larger_vector (gstring,
 -                             ASIZE (gstring) + LGSTRING_GLYPH_LEN (gstring),
 -                             Qnil);
 +                             LGSTRING_GLYPH_LEN (gstring), -1);
      }
    if (i == 3 || XINT (n) == 0)
      return Qnil;
@@@ -4526,7 -4518,7 +4519,7 @@@ DEFUN ("open-font", Fopen_font, Sopen_f
         doc: /* Open FONT-ENTITY.  */)
    (Lisp_Object font_entity, Lisp_Object size, Lisp_Object frame)
  {
 -  int isize;
 +  EMACS_INT isize;
  
    CHECK_FONT_ENTITY (font_entity);
    if (NILP (frame))
        isize = POINT_TO_PIXEL (XFLOAT_DATA (size), XFRAME (frame)->resy);
        else
        isize = XINT (size);
 +      if (! (INT_MIN <= isize && isize <= INT_MAX))
 +      args_out_of_range (font_entity, size);
        if (isize == 0)
        isize = 120;
      }
@@@ -4647,14 -4637,14 +4640,14 @@@ the corresponding element is nil.  */
     Lisp_Object object)
  {
    struct font *font;
 -  int i, len;
 +  ptrdiff_t i, len;
    Lisp_Object *chars, vec;
    USE_SAFE_ALLOCA;
  
    CHECK_FONT_GET_OBJECT (font_object, font);
    if (NILP (object))
      {
 -      EMACS_INT charpos, bytepos;
 +      ptrdiff_t charpos, bytepos;
  
        validate_region (&from, &to);
        if (EQ (from, to))
@@@ -4760,22 -4750,22 +4753,22 @@@ the current buffer.  It defaults to th
    (Lisp_Object position, Lisp_Object window, Lisp_Object string)
  {
    struct window *w;
 -  EMACS_INT pos;
 +  ptrdiff_t pos;
  
    if (NILP (string))
      {
        CHECK_NUMBER_COERCE_MARKER (position);
 -      pos = XINT (position);
 -      if (pos < BEGV || pos >= ZV)
 +      if (! (BEGV <= XINT (position) && XINT (position) < ZV))
        args_out_of_range_3 (position, make_number (BEGV), make_number (ZV));
 +      pos = XINT (position);
      }
    else
      {
        CHECK_NUMBER (position);
        CHECK_STRING (string);
 -      pos = XINT (position);
 -      if (pos < 0 || pos >= SCHARS (string))
 +      if (! (0 < XINT (position) && XINT (position) < SCHARS (string)))
        args_out_of_range (string, position);
 +      pos = XINT (position);
      }
    if (NILP (window))
      window = selected_window;
diff --combined src/font.h
index f49f06a1fbc6f1ed13ab28aa205600042a5cf29e,8ca7c9c19c4082ef022852953ea2b649d1e19b3f..72ee15c5e00bd20a60ea7a1ad5701e50a5f41a19
@@@ -705,7 -705,7 +705,7 @@@ struct font_drive
  
  
  /* Chain of font drivers.  There's one global font driver list
-    (font_driver_list in font.c).  In addition, each frame has it's own
+    (font_driver_list in font.c).  In addition, each frame has its own
     font driver list at FRAME_PTR->font_driver_list.  */
  
  struct font_driver_list
  
  
  /* Chain of arbitrary data specific to each font driver.  Each frame
-    has it's own font data list at FRAME_PTR->font_data_list.  */
+    has its own font data list at FRAME_PTR->font_data_list.  */
  
  struct font_data_list
  {
@@@ -793,7 -793,7 +793,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/fontset.c
index ae9194686953813c512f8103f11c7567bc33f77a,605d807aa3c95da7fa06791f74d0756a8d133a83..b5b36822a2d106c221c90ea0ba953afe270a1ea3
@@@ -166,7 -166,7 +166,7 @@@ along with GNU Emacs.  If not, see <htt
     These structures are hidden from the other codes than this file.
     The other codes handle fontsets only by their ID numbers.  They
     usually use the variable name `fontset' for IDs.  But, in this
-    file, we always use varialbe name `id' for IDs, and name `fontset'
+    file, we always use variable name `id' for IDs, and name `fontset'
     for an actual fontset object, i.e., char-table.
  
  */
@@@ -416,11 -416,9 +416,11 @@@ reorder_font_vector (Lisp_Object font_g
  
              for (tail = Vcharset_ordered_list;
                   ! EQ (tail, Vcharset_non_preferred_head) && CONSP (tail);
 -                 score += 0x100, tail = XCDR (tail))
 +                 tail = XCDR (tail))
                if (EQ (encoding, XCAR (tail)))
                  break;
 +              else if (score <= min (INT_MAX, MOST_POSITIVE_FIXNUM) - 0x100)
 +                score += 0x100;
            }
          else
            {
@@@ -633,7 -631,7 +633,7 @@@ fontset_find_font (Lisp_Object fontset
            {
              /* Something strange happened, perhaps because of a
                 Font-backend problem.  Too avoid crashing, record
-                that this spec is unsable.  It may be better to find
+                that this spec is unusable.  It may be better to find
                 another font of the same spec, but currently we don't
                 have such an API.  */
              RFONT_DEF_SET_FACE (rfont_def, -1);
@@@ -789,7 -787,7 +789,7 @@@ make_fontset (Lisp_Object frame, Lisp_O
    while (!NILP (AREF (Vfontset_table, id))) id++;
  
    if (id + 1 == size)
 -    Vfontset_table = larger_vector (Vfontset_table, size + 32, Qnil);
 +    Vfontset_table = larger_vector (Vfontset_table, 1, -1);
  
    fontset = Fmake_char_table (Qfontset, Qnil);
  
@@@ -907,7 -905,7 +907,7 @@@ face_suitable_for_char_p (struct face *
  
  
  /* Return ID of face suitable for displaying character C on frame F.
-    FACE must be reazlied for ASCII characters in advance.  Called from
+    FACE must be realized for ASCII characters in advance.  Called from
     the macro FACE_FOR_CHAR.  */
  
  int
@@@ -1348,7 -1346,7 +1348,7 @@@ accumulate_script_ranges (Lisp_Object a
  
     In FONTSET, set FONT_DEF in a fashion specified by ADD for
     characters in RANGE and ranges in SCRIPT_RANGE_LIST before RANGE.
-    The consumed ranges are poped up from SCRIPT_RANGE_LIST, and the
+    The consumed ranges are popped up from SCRIPT_RANGE_LIST, and the
     new SCRIPT_RANGE_LIST is stored in ARG.
  
     If ASCII is nil, don't set FONT_DEF for ASCII characters.  It is
@@@ -1702,7 -1700,7 +1702,7 @@@ FONT-SPEC is a vector, a cons, or a str
  static Lisp_Object auto_fontset_alist;
  
  /* Number of automatically created fontsets.  */
 -static printmax_t num_auto_fontsets;
 +static ptrdiff_t num_auto_fontsets;
  
  /* Return a fontset synthesized from FONT-OBJECT.  This is called from
     x_new_font when FONT-OBJECT is used for the default ASCII font of a
@@@ -1729,9 -1727,9 +1729,9 @@@ fontset_from_font (Lisp_Object font_obj
      alias = intern ("fontset-startup");
    else
      {
 -      char temp[sizeof "fontset-auto" + INT_STRLEN_BOUND (printmax_t)];
 +      char temp[sizeof "fontset-auto" + INT_STRLEN_BOUND (ptrdiff_t)];
  
 -      sprintf (temp, "fontset-auto%"pMd, num_auto_fontsets - 1);
 +      sprintf (temp, "fontset-auto%"pD"d", num_auto_fontsets - 1);
        alias = intern (temp);
      }
    fontset_spec = copy_font_spec (font_spec);
@@@ -1818,7 -1816,7 +1818,7 @@@ DEFUN ("internal-char-font", Finternal_
         doc: /* For internal use only.  */)
    (Lisp_Object position, Lisp_Object ch)
  {
 -  EMACS_INT pos, pos_byte, dummy;
 +  ptrdiff_t pos, pos_byte, dummy;
    int face_id;
    int c;
    struct frame *f;
        struct window *w;
  
        CHECK_NUMBER_COERCE_MARKER (position);
 -      pos = XINT (position);
 -      if (pos < BEGV || pos >= ZV)
 +      if (! (BEGV <= XINT (position) && XINT (position) < ZV))
        args_out_of_range_3 (position, make_number (BEGV), make_number (ZV));
 +      pos = XINT (position);
        pos_byte = CHAR_TO_BYTE (pos);
        if (NILP (ch))
        c = FETCH_CHAR (pos_byte);
diff --combined src/frame.c
index dbee6a8092b21424b8fa0b600f967975f7bb17e0,bd97c5f18c76545c53afc80f182c919a50c060fc..00653af74d668bc6b31947c87a957a5265c9b4d4
@@@ -374,7 -374,7 +374,7 @@@ make_frame (int mini_p
  
      /* Use set_window_buffer, not Fset_window_buffer, and don't let
         hooks be run by it.  The reason is that the whole frame/window
-        arrangement is not yet fully intialized at this point.  Windows
+        arrangement is not yet fully initialized at this point.  Windows
         don't have the right size, glyph matrices aren't initialized
         etc.  Running Lisp functions at this point surely ends in a
         SEGV.  */
@@@ -1612,8 -1612,8 +1612,8 @@@ before calling this function on it, lik
    (Lisp_Object frame, Lisp_Object x, Lisp_Object y)
  {
    CHECK_LIVE_FRAME (frame);
 -  CHECK_NUMBER (x);
 -  CHECK_NUMBER (y);
 +  CHECK_TYPE_RANGED_INTEGER (int, x);
 +  CHECK_TYPE_RANGED_INTEGER (int, y);
  
    /* I think this should be done with a hook.  */
  #ifdef HAVE_WINDOW_SYSTEM
@@@ -1653,8 -1653,8 +1653,8 @@@ before calling this function on it, lik
    (Lisp_Object frame, Lisp_Object x, Lisp_Object y)
  {
    CHECK_LIVE_FRAME (frame);
 -  CHECK_NUMBER (x);
 -  CHECK_NUMBER (y);
 +  CHECK_TYPE_RANGED_INTEGER (int, x);
 +  CHECK_TYPE_RANGED_INTEGER (int, y);
  
    /* I think this should be done with a hook.  */
  #ifdef HAVE_WINDOW_SYSTEM
@@@ -1712,7 -1712,7 +1712,7 @@@ If omitted, FRAME defaults to the curre
  }
  
  /* Update the display_time slot of the buffers shown in WINDOW
-    and all its descendents.  */
+    and all its descendants.  */
  
  static void
  make_frame_visible_1 (Lisp_Object window)
@@@ -1929,7 -1929,7 +1929,7 @@@ request a switch to FOCUS-FRAME, and `l
  FOCUS-FRAME after reading an event typed at FRAME.
  
  If FOCUS-FRAME is omitted or nil, any existing redirection is
- cancelled, and the frame again receives its own keystrokes.
+ canceled, and the frame again receives its own keystrokes.
  
  Focus redirection is useful for temporarily redirecting keystrokes to
  a surrogate minibuffer frame when a frame doesn't have its own
@@@ -2046,7 -2046,7 +2046,7 @@@ store_in_alist (Lisp_Object *alistptr, 
  }
  
  static int
 -frame_name_fnn_p (char *str, EMACS_INT len)
 +frame_name_fnn_p (char *str, ptrdiff_t len)
  {
    if (len > 1 && str[0] == 'F' && '0' <= str[1] && str[1] <= '9')
      {
@@@ -2330,7 -2330,7 +2330,7 @@@ If FRAME is nil, describe the currentl
              if (STRINGP (value) && !FRAME_WINDOW_P (f))
                {
                  const char *color_name;
 -                EMACS_INT csz;
 +                ptrdiff_t csz;
  
                  if (EQ (parameter, Qbackground_color))
                    {
@@@ -2406,13 -2406,12 +2406,13 @@@ use is not recommended.  Explicitly che
  #endif
  
      {
 -      int length = XINT (Flength (alist));
 -      int i;
 -      Lisp_Object *parms
 -      = (Lisp_Object *) alloca (length * sizeof (Lisp_Object));
 -      Lisp_Object *values
 -      = (Lisp_Object *) alloca (length * sizeof (Lisp_Object));
 +      EMACS_INT length = XFASTINT (Flength (alist));
 +      ptrdiff_t i;
 +      Lisp_Object *parms;
 +      Lisp_Object *values;
 +      USE_SAFE_ALLOCA;
 +      SAFE_ALLOCA_LISP (parms, 2 * length);
 +      values = parms + length;
  
        /* Extract parm names and values into those vectors.  */
  
              || EQ (prop, Qbackground_color))
            update_face_from_frame_parameter (f, prop, val);
        }
 +
 +      SAFE_FREE ();
      }
    return Qnil;
  }
@@@ -2578,7 -2575,7 +2578,7 @@@ but that the idea of the actual height 
  {
    register struct frame *f;
  
 -  CHECK_NUMBER (lines);
 +  CHECK_TYPE_RANGED_INTEGER (int, lines);
    if (NILP (frame))
      frame = selected_frame;
    CHECK_LIVE_FRAME (frame);
@@@ -2605,7 -2602,7 +2605,7 @@@ but that the idea of the actual width o
    (Lisp_Object frame, Lisp_Object cols, Lisp_Object pretend)
  {
    register struct frame *f;
 -  CHECK_NUMBER (cols);
 +  CHECK_TYPE_RANGED_INTEGER (int, cols);
    if (NILP (frame))
      frame = selected_frame;
    CHECK_LIVE_FRAME (frame);
@@@ -2632,8 -2629,8 +2632,8 @@@ DEFUN ("set-frame-size", Fset_frame_siz
    register struct frame *f;
  
    CHECK_LIVE_FRAME (frame);
 -  CHECK_NUMBER (cols);
 -  CHECK_NUMBER (rows);
 +  CHECK_TYPE_RANGED_INTEGER (int, cols);
 +  CHECK_TYPE_RANGED_INTEGER (int, rows);
    f = XFRAME (frame);
  
    /* I think this should be done with a hook.  */
@@@ -2664,8 -2661,8 +2664,8 @@@ the rightmost or bottommost possible po
    register struct frame *f;
  
    CHECK_LIVE_FRAME (frame);
 -  CHECK_NUMBER (xoffset);
 -  CHECK_NUMBER (yoffset);
 +  CHECK_TYPE_RANGED_INTEGER (int, xoffset);
 +  CHECK_TYPE_RANGED_INTEGER (int, yoffset);
    f = XFRAME (frame);
  
    /* I think this should be done with a hook.  */
@@@ -2884,12 -2881,12 +2884,12 @@@ x_set_frame_parameters (FRAME_PTR f, Li
        prop = parms[i];
        val = values[i];
  
 -      if (EQ (prop, Qwidth) && NATNUMP (val))
 +      if (EQ (prop, Qwidth) && RANGED_INTEGERP (0, val, INT_MAX))
          {
            size_changed = 1;
            width = XFASTINT (val);
          }
 -      else if (EQ (prop, Qheight) && NATNUMP (val))
 +      else if (EQ (prop, Qheight) && RANGED_INTEGERP (0, val, INT_MAX))
          {
            size_changed = 1;
            height = XFASTINT (val);
      }
  
    /* Don't die if just one of these was set.  */
 -  if (EQ (left, Qunbound))
 +  if (! TYPE_RANGED_INTEGERP (int, left))
      {
        left_no_change = 1;
        if (f->left_pos < 0)
        else
        XSETINT (left, f->left_pos);
      }
 -  if (EQ (top, Qunbound))
 +  if (! TYPE_RANGED_INTEGERP (int, top))
      {
        top_no_change = 1;
        if (f->top_pos < 0)
      }
  
    /* If one of the icon positions was not set, preserve or default it.  */
 -  if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
 +  if (! TYPE_RANGED_INTEGERP (int, icon_left))
      {
        icon_left_no_change = 1;
        icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
        if (NILP (icon_left))
        XSETINT (icon_left, 0);
      }
 -  if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
 +  if (! TYPE_RANGED_INTEGERP (int, icon_top))
      {
        icon_top_no_change = 1;
        icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
@@@ -3165,7 -3162,7 +3165,7 @@@ x_set_line_spacing (struct frame *f, Li
  {
    if (NILP (new_value))
      f->extra_line_spacing = 0;
 -  else if (NATNUMP (new_value))
 +  else if (RANGED_INTEGERP (0, new_value, INT_MAX))
      f->extra_line_spacing = XFASTINT (new_value);
    else
      signal_error ("Invalid line-spacing", new_value);
@@@ -3374,7 -3371,7 +3374,7 @@@ x_set_fringe_width (struct frame *f, Li
  void
  x_set_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
  {
 -  CHECK_NUMBER (arg);
 +  CHECK_TYPE_RANGED_INTEGER (int, arg);
  
    if (XINT (arg) == f->border_width)
      return;
@@@ -3390,7 -3387,7 +3390,7 @@@ x_set_internal_border_width (struct fra
  {
    int old = FRAME_INTERNAL_BORDER_WIDTH (f);
  
 -  CHECK_NUMBER (arg);
 +  CHECK_TYPE_RANGED_INTEGER (int, arg);
    FRAME_INTERNAL_BORDER_WIDTH (f) = XINT (arg);
    if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
      FRAME_INTERNAL_BORDER_WIDTH (f) = 0;
@@@ -4127,7 -4124,7 +4127,7 @@@ x_figure_window_size (struct frame *f, 
        f->top_pos = 0;
        else
        {
 -        CHECK_NUMBER (tem0);
 +        CHECK_TYPE_RANGED_INTEGER (int, tem0);
          f->top_pos = XINT (tem0);
          if (f->top_pos < 0)
            window_prompting |= YNegative;
        f->left_pos = 0;
        else
        {
 -        CHECK_NUMBER (tem1);
 +        CHECK_TYPE_RANGED_INTEGER (int, tem1);
          f->left_pos = XINT (tem1);
          if (f->left_pos < 0)
            window_prompting |= XNegative;
diff --combined src/fringe.c
index 727547b1ab700e2106bd756beb36afab7c22b4ce,da896e07b76744c7e636ab4c07625a666e5b3e8e..edc254fa3f248afb9a7a3431831145085339fe80
@@@ -35,7 -35,7 +35,7 @@@ along with GNU Emacs.  If not, see <htt
     Logical bitmaps are used internally to denote things like
     'end-of-buffer', 'left-truncation', 'overlay-arrow', etc.
  
-    Physical bitmaps specify the visual appearence of the bitmap,
+    Physical bitmaps specify the visual appearance of the bitmap,
     e.g. 'bottom-left-angle', 'left-arrow', 'left-triangle', etc.
     User defined bitmaps are physical bitmaps.
  
@@@ -474,7 -474,7 +474,7 @@@ int max_used_fringe_bitmap = MAX_STANDA
  int
  lookup_fringe_bitmap (Lisp_Object bitmap)
  {
 -  int bn;
 +  EMACS_INT bn;
  
    bitmap = Fget (bitmap, Qfringe);
    if (!INTEGERP (bitmap))
@@@ -696,7 -696,7 +696,7 @@@ static in
  get_logical_fringe_bitmap (struct window *w, Lisp_Object bitmap, int right_p, int partial_p)
  {
    Lisp_Object cmap, bm1 = Qnil, bm2 = Qnil, bm;
 -  int ln1 = 0, ln2 = 0;
 +  EMACS_INT ln1 = 0, ln2 = 0;
    int ix1 = right_p;
    int ix2 = ix1 + (partial_p ? 2 : 0);
  
@@@ -928,7 -928,7 +928,7 @@@ update_window_fringes (struct window *w
    int top_ind_rn, bot_ind_rn;
    int top_ind_min_y, bot_ind_max_y;
  
-   /* top_ind_rn is set to a nonnegative value whenver
+   /* top_ind_rn is set to a nonnegative value whenever
       row->indicate_bob_p is set, so it's OK that top_row_ends_at_zv_p
       is not initialized here.  Similarly for bot_ind_rn,
       row->indicate_eob_p and bot_row_ends_at_zv_p.  */
@@@ -1555,7 -1555,7 +1555,7 @@@ If BITMAP already exists, the existing 
    else
      {
        CHECK_NUMBER (height);
 -      fb.height = min (XINT (height), 255);
 +      fb.height = max (0, min (XINT (height), 255));
        if (fb.height > h)
        {
          fill1 = (fb.height - h) / 2;
    else
      {
        CHECK_NUMBER (width);
 -      fb.width = min (XINT (width), 255);
 +      fb.width = max (0, min (XINT (width), 255));
      }
  
    fb.period = 0;
@@@ -1704,7 -1704,7 +1704,7 @@@ Return nil if POS is not visible in WIN
  {
    struct window *w;
    struct glyph_row *row;
 -  int textpos;
 +  ptrdiff_t textpos;
  
    if (NILP (window))
      window = selected_window;
    if (!NILP (pos))
      {
        CHECK_NUMBER_COERCE_MARKER (pos);
 +      if (! (BEGV <= XINT (pos) && XINT (pos) <= ZV))
 +      args_out_of_range (window, pos);
        textpos = XINT (pos);
      }
    else if (w == XWINDOW (selected_window))
diff --combined src/ftfont.c
index 9da4a98d6924e30131a058d048e6eb202b2c235b,bab97e44fabe28a6c5667e5159047bbc14c967e0..2f0643a31e0133c61f01d52b009b776cd8ccf622
@@@ -164,6 -164,13 +164,13 @@@ get_adstyle_property (FcPattern *p
    char *str, *end;
    Lisp_Object adstyle;
  
+ #ifdef FC_FONTFORMAT
+   if ((FcPatternGetString (p, FC_FONTFORMAT, 0, &fcstr) == FcResultMatch)
+       && xstrcasecmp ((char *) fcstr, "bdf") != 0
+       && xstrcasecmp ((char *) fcstr, "pcf") != 0)
+     /* Not a BDF nor PCF font.  */
+     return Qnil;
+ #endif
    if (FcPatternGetString (p, FC_STYLE, 0, &fcstr) != FcResultMatch)
      return Qnil;
    str = (char *) fcstr;
@@@ -272,7 -279,7 +279,7 @@@ ftfont_pattern_entity (FcPattern *p, Li
      }
    else
      {
-       /* As this font is not scalable, parhaps this is a BDF or PCF
+       /* As this font is not scalable, perhaps this is a BDF or PCF
         font. */
        FT_Face ft_face;
  
@@@ -730,7 -737,7 +737,7 @@@ ftfont_spec_pattern (Lisp_Object spec, 
  
    if ((n = FONT_SLANT_NUMERIC (spec)) >= 0
        && n < 100)
-     /* Fontconfig doesn't support reverse-italic/obligue.  */
+     /* Fontconfig doesn't support reverse-italic/oblique.  */
      return NULL;
  
    if (INTEGERP (AREF (spec, FONT_DPI_INDEX)))
@@@ -1026,13 -1033,13 +1033,13 @@@ ftfont_list (Lisp_Object frame, Lisp_Ob
  #endif        /* HAVE_LIBOTF */
        if (VECTORP (chars))
        {
 -        int j;
 +        ptrdiff_t j;
  
          if (FcPatternGetCharSet (fontset->fonts[i], FC_CHARSET, 0, &charset)
              != FcResultMatch)
            continue;
          for (j = 0; j < ASIZE (chars); j++)
 -          if (NATNUMP (AREF (chars, j))
 +          if (TYPE_RANGED_INTEGERP (FcChar32, AREF (chars, j))
                && FcCharSetHasChar (charset, XFASTINT (AREF (chars, j))))
              break;
          if (j == ASIZE (chars))
@@@ -1462,7 -1469,7 +1469,7 @@@ ftfont_get_bitmap (struct font *font, u
         : ft_face->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_LCD_V ? 8
         : -1);
    if (bitmap->bits_per_pixel < 0)
-     /* We don't suport that kind of pixel mode.  */
+     /* We don't support that kind of pixel mode.  */
      return -1;
    bitmap->rows = ft_face->glyph->bitmap.rows;
    bitmap->width = ft_face->glyph->bitmap.width;
@@@ -2387,8 -2394,8 +2394,8 @@@ static Lisp_Objec
  ftfont_shape_by_flt (Lisp_Object lgstring, struct font *font,
                     FT_Face ft_face, OTF *otf, FT_Matrix *matrix)
  {
 -  EMACS_INT len = LGSTRING_GLYPH_LEN (lgstring);
 -  EMACS_INT i;
 +  ptrdiff_t len = LGSTRING_GLYPH_LEN (lgstring);
 +  ptrdiff_t i;
    struct MFLTFontFT flt_font_ft;
    MFLT *flt = NULL;
    int with_variation_selector = 0;
      }
  
    len = i;
 -  lint_assume (len <= TYPE_MAXIMUM (EMACS_INT) - 2);
 +  lint_assume (len <= STRING_BYTES_BOUND);
  
    if (with_variation_selector)
      {
diff --combined src/gtkutil.c
index 31cbd32f441c3c13c831e4892f32d5c43a838e0c,bc71685819efff899b2526d193876025ddd53030..43cdb38c640ebad6287c1c88f4a24dc81de61b8c
@@@ -127,7 -127,7 +127,7 @@@ xg_set_screen (GtkWidget *w, FRAME_PTR 
  
     Returns non-zero if display could be opened, zero if display could not
     be opened, and less than zero if the GTK version doesn't support
-    multipe displays.  */
+    multiple displays.  */
  
  void
  xg_display_open (char *display_name, Display **dpy)
@@@ -1100,6 -1100,14 +1100,14 @@@ xg_create_frame_widgets (FRAME_PTR f
    else
      wtop = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  
+   /* gtk_window_set_has_resize_grip is a Gtk+ 3.0 function but Ubuntu
+      has backported it to Gtk+ 2.0 and they add the resize grip for
+      Gtk+ 2.0 applications also.  But it has a bug that makes Emacs loop
+      forever, so disable the grip.  */
+ #if GTK_MAJOR_VERSION < 3 && defined (HAVE_GTK_WINDOW_SET_HAS_RESIZE_GRIP)
+   gtk_window_set_has_resize_grip (GTK_WINDOW (wtop), FALSE);
+ #endif
    xg_set_screen (wtop, f);
  
    wvbox = gtk_vbox_new (FALSE, 0);
@@@ -1621,7 -1629,7 +1629,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);
@@@ -2363,7 -2371,7 +2371,7 @@@ xg_create_one_menuitem (widget_value *i
     HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
     POP_UP_P is non-zero if we shall create a popup menu.
     MENU_BAR_P is non-zero if we shall create a menu bar.
-    ADD_TEAROFF_P is non-zero if we shall add a teroff menu item.  Ignored
+    ADD_TEAROFF_P is non-zero if we shall add a tearoff menu item.  Ignored
     if MENU_BAR_P is non-zero.
     TOPMENU is the topmost GtkWidget that others shall be placed under.
     It may be NULL, in that case we create the appropriate widget
@@@ -4262,7 -4270,7 +4270,7 @@@ xg_make_tool_item (FRAME_PTR f
  #endif
        gtk_tool_item_set_homogeneous (ti, FALSE);
  
-       /* Callback to save modifyer mask (Shift/Control, etc).  GTK makes
+       /* Callback to save modifier mask (Shift/Control, etc).  GTK makes
           no distinction based on modifiers in the activate callback,
           so we have to do it ourselves.  */
        g_signal_connect (wb, "button-release-event",
           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),
@@@ -4400,17 -4409,20 +4408,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/image.c
index fd842f3e347eeaa8d881e7c0622ce0883c79881b,81907d8e580ea4938975bca29bb4752c72d24226..736c1b3472f0dbf74f0505a43789ab5004c1a380
@@@ -771,9 -771,10 +771,9 @@@ parse_image_spec (Lisp_Object spec, str
        /* Record that we recognized the keyword.  If a keywords
         was found more than once, it's an error.  */
        keywords[i].value = value;
 -      ++keywords[i].count;
 -
        if (keywords[i].count > 1)
        return 0;
 +      ++keywords[i].count;
  
        /* Check type of value against allowed type.  */
        switch (keywords[i].type)
@@@ -1753,7 -1754,6 +1753,7 @@@ lookup_image (struct frame *f, Lisp_Obj
             `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
             `:background COLOR'.  */
          Lisp_Object ascent, margin, relief, bg;
 +        int relief_bound;
  
          ascent = image_spec_value (spec, QCascent, NULL);
          if (INTEGERP (ascent))
            }
  
          relief = image_spec_value (spec, QCrelief, NULL);
 -        if (INTEGERP (relief))
 +        relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
 +        if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
            {
              img->relief = XINT (relief);
              img->hmargin += eabs (img->relief);
@@@ -7619,7 -7618,7 +7619,7 @@@ imagemagick_load_image (struct frame *f
    image = image_spec_value (img->spec, QCindex, NULL);
    ino = INTEGERP (image) ? XFASTINT (image) : 0;
    ping_wand = NewMagickWand ();
-   MagickSetResolution (ping_wand, 2, 2);
    if (filename != NULL)
      {
        status = MagickPingImage (ping_wand, filename);
        status = MagickPingImageBlob (ping_wand, contents, size);
      }
  
+   MagickSetResolution (ping_wand, 2, 2);
    if (! (0 <= ino && ino < MagickGetNumberImages (ping_wand)))
      {
        image_error ("Invalid image number `%s' in image `%s'",
      }
  
    /* Finally we are done manipulating the image.  Figure out the
-      resulting width/height and transfer ownerwship to Emacs.  */
+      resulting width/height and transfer ownership to Emacs.  */
    height = MagickGetImageHeight (image_wand);
    width = MagickGetImageWidth (image_wand);
  
            goto imagemagick_error;
          }
  
-       /* Copy imagegmagick image to x with primitive yet robust pixel
+       /* Copy imagemagick image to x with primitive yet robust pixel
           pusher loop.  This has been tested a lot with many different
           images.  */
  
diff --combined src/intervals.c
index 6f8dda4294eb26bef8e72da3493bb4b6522463a2,05b7175ac3f1ed9226423c49ecda65bd0023edc0..ecb37495a04dc832a14228130c97f32f1707cfc1
@@@ -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 ();
@@@ -1225,7 -1225,7 +1225,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 -1258,7 +1258,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 -1602,7 +1602,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 -1862,7 +1862,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));
  }
     current buffer, and the invisible property has a `stickiness' such that
     inserting a character at position POS would inherit the property it,
     return POS + ADJ, otherwise return POS.  If TEST_INTANG is non-zero,
-    then intangibility is required as well as invisibleness.
+    then intangibility is required as well as invisibility.
  
     TEST_OFFS should be either 0 or -1, and ADJ should be either 1 or -1.
  
     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 -2389,8 +2389,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
index 3b82c4976505d7040361e0b1ff826c7989cd07f4,2df1ba742bae268787ea7ab4edd8534a6fe3f756..aa8a9908f3bbf2a70b1103210ee535b246aa4323
@@@ -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;
@@@ -376,7 -376,7 +376,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;
  
@@@ -447,9 -447,9 +447,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);
@@@ -464,7 -464,8 +464,8 @@@ static void input_available_signal (in
  static Lisp_Object (Fcommand_execute) (Lisp_Object, Lisp_Object, Lisp_Object,
                                       Lisp_Object);
  static void handle_interrupt (void);
- static void quit_throw_to_read_char (void) NO_RETURN;
+ static void quit_throw_to_read_char (int) NO_RETURN;
+ static void process_special_events (void);
  static void timer_start_idle (void);
  static void timer_stop_idle (void);
  static void timer_resume_idle (void);
@@@ -613,7 -614,7 +614,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++)
    echo_kboard = current_kboard;
  
    if (waiting_for_input && !NILP (Vquit_flag))
-     quit_throw_to_read_char ();
+     quit_throw_to_read_char (0);
  }
  
  /* Turn off echoing, for the start of a new command.  */
@@@ -671,7 -672,7 +672,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)
@@@ -713,7 -714,9 +714,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)
@@@ -791,7 -794,7 +792,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.
@@@ -1252,7 -1255,7 +1253,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);
@@@ -1303,7 -1306,7 +1304,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.  */
@@@ -1327,7 -1330,7 +1328,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 (Vtransient_mark_mode)))
                  && !EQ (Vthis_command, Qhandle_switch_frame))
                {
 -                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.  */
@@@ -1930,7 -1933,7 +1931,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);
@@@ -2268,7 -2271,7 +2269,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
  
        && ' ' <= 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 inner_gcpro1;
+       struct gcpro gcpro1;
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
  
        /* Save the echo status.  */
        int saved_immediate_echo = current_kboard->immediate_echo;
        keys = Fcopy_sequence (this_command_keys);
        else
        keys = Qnil;
-       GCPRO1_VAR (keys, inner_gcpro);
+       GCPRO1 (keys);
  
        /* Clear out this_command_keys.  */
        this_command_key_count = 0;
        if (saved_immediate_echo)
        echo_now ();
  
-       UNGCPRO_VAR (inner_gcpro);
+       UNGCPRO;
  
        /* The input method can return no events.  */
        if (! CONSP (tem))
    /* 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),
@@@ -3296,7 -3297,7 +3297,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;
@@@ -3665,7 -3666,7 +3666,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;
  
@@@ -3817,7 -3818,7 +3818,7 @@@ kbd_buffer_get_event (KBOARD **kbp
        /* If the quit flag is set, then read_char will return
         quit_char, so that counts as "available input."  */
        if (!NILP (Vquit_flag))
-       quit_throw_to_read_char ();
+       quit_throw_to_read_char (0);
  
        /* One way or another, wait until input is available; then, if
         interrupt handlers have not read it, read it now.  */
    return (obj);
  }
  \f
- /* Process any events that are not user-visible,
-    then return, without reading any user-visible events.  */
+ /* Process any non-user-visible events (currently X selection events),
+    without reading any user-visible events.  */
  
- void
swallow_events (int do_display)
static void
process_special_events (void)
  {
-   int old_timers_run;
    while (kbd_fetch_ptr != kbd_store_ptr)
      {
        struct input_event *event;
        else
        break;
      }
+ }
+ /* Process any events that are not user-visible, run timer events that
+    are ripe, and return, without reading any user-visible events.  */
+ void
+ swallow_events (int do_display)
+ {
+   int old_timers_run;
+   process_special_events ();
  
    old_timers_run = timers_run;
    get_input_pending (&input_pending, READABLE_EVENTS_DO_TIMERS_NOW);
@@@ -4415,7 -4425,7 +4425,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
@@@ -4813,7 -4823,7 +4823,7 @@@ const char *const lispy_function_keys[
      "ico-00",        /* VK_ICO_00         0xE4 */
      0,               /* VK_PROCESSKEY     0xE5 - used by IME */
      "ico-clear",     /* VK_ICO_CLEAR      0xE6 */
-     0,               /* VK_PACKET         0xE7  - used to pass unicode chars */
+     0,               /* VK_PACKET         0xE7  - used to pass Unicode chars */
      0,               /*                   0xE8 */
      "reset",         /* VK_OEM_RESET      0xE9 */
      "jump",          /* VK_OEM_JUMP       0xEA */
@@@ -5126,7 -5136,7 +5136,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;
@@@ -5401,7 -5411,7 +5411,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);
@@@ -6046,10 -6052,10 +6056,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.
@@@ -6256,7 -6262,7 +6266,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;
@@@ -6422,9 -6428,9 +6432,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);
        }
  
@@@ -7526,7 -7532,7 +7536,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;
@@@ -7597,7 -7603,7 +7607,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++]
@@@ -7641,7 -7647,7 +7651,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,
@@@ -8366,14 -8372,13 +8376,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.  */
@@@ -8958,15 -8963,15 +8968,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.  */
    int junk;
  #endif
  
-   struct gcpro outer_gcpro1;
+   struct gcpro gcpro1;
  
-   GCPRO1_VAR (fake_prefixed_keys, outer_gcpro);
+   GCPRO1 (fake_prefixed_keys);
    raw_keybuf_count = 0;
  
    last_nonmenu_event = Qnil;
         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;
  
          if (EQ (key, Qt))
            {
              unbind_to (count, Qnil);
-             UNGCPRO_VAR (outer_gcpro);
+             UNGCPRO;
              return -1;
            }
  
        add_command_key (keybuf[t]);
      }
  
-   UNGCPRO_VAR (outer_gcpro);
+   UNGCPRO;
    return t;
  }
  
@@@ -10110,7 -10115,7 +10120,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);
                         ! NILP (can_return_switch_frame), 0);
  
  #if 0  /* The following is fine for code reading a key sequence and
-         then proceeding with a lenghty computation, but it's not good
+         then proceeding with a lengthy computation, but it's not good
          for code reading keys in a loop, like an input method.  */
  #ifdef HAVE_WINDOW_SYSTEM
    if (display_hourglass_p)
@@@ -10167,7 -10172,7 +10177,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);
@@@ -10313,7 -10318,7 +10323,7 @@@ give to the command you invoke, if it a
    (Lisp_Object prefixarg)
  {
    Lisp_Object function;
 -  EMACS_INT saved_last_point_position;
 +  ptrdiff_t saved_last_point_position;
    Lisp_Object saved_keys, saved_last_point_position_buffer;
    Lisp_Object bindings, value;
    struct gcpro gcpro1, gcpro2, gcpro3;
          Lisp_Object binding;
          char *newmessage;
          int message_p = push_message ();
 -        int count = SPECPDL_INDEX ();
 +        ptrdiff_t count = SPECPDL_INDEX ();
          ptrdiff_t newmessage_len, newmessage_alloc;
          USE_SAFE_ALLOCA;
  
@@@ -10527,6 -10532,9 +10537,9 @@@ if there is a doubt, the value is t.  *
        || !NILP (Vunread_input_method_events))
      return (Qt);
  
+   /* Process non-user-visible events (Bug#10195).  */
+   process_special_events ();
    get_input_pending (&input_pending,
                     READABLE_EVENTS_DO_TIMERS_NOW
                     | READABLE_EVENTS_FILTER_EVENTS);
@@@ -10732,7 -10740,7 +10745,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;
@@@ -10788,7 -10796,7 +10801,7 @@@ stuff_buffered_input (Lisp_Object stuff
  
    if (STRINGP (stuffstring))
      {
 -      register EMACS_INT count;
 +      register ptrdiff_t count;
  
        p = SDATA (stuffstring);
        count = SBYTES (stuffstring);
@@@ -10829,7 -10837,7 +10842,7 @@@ set_waiting_for_input (struct timeval *
    /* If handle_interrupt was called before and buffered a C-g,
       make it run again now, to avoid timing error.  */
    if (!NILP (Vquit_flag))
-     quit_throw_to_read_char ();
+     quit_throw_to_read_char (0);
  }
  
  void
@@@ -10844,7 -10852,7 +10857,7 @@@ clear_waiting_for_input (void
  
     If we have a frame on the controlling tty, we assume that the
     SIGINT was generated by C-g, so we call handle_interrupt.
-    Otherwise, the handler kills Emacs.  */
+    Otherwise, tell QUIT to kill Emacs.  */
  
  static void
  interrupt_signal (int signalnum)      /* If we don't have an argument, some */
    if (!terminal)
      {
        /* If there are no frames there, let's pretend that we are a
-          well-behaving UN*X program and quit.  We cannot do that while
-          GC is in progress, though.  */
-       if (!gc_in_progress)
-       Fkill_emacs (Qnil);
-       else
-       Vquit_flag = Qt;
+          well-behaving UN*X program and quit.  We must not call Lisp
+          in a signal handler, so tell QUIT to exit when it is
+          safe.  */
+       Vquit_flag = Qkill_emacs;
      }
    else
      {
@@@ -11015,15 -11021,20 +11026,20 @@@ handle_interrupt (void
           separate event loop thread like W32.  */
  #ifndef HAVE_NS
    if (waiting_for_input && !echoing)
-       quit_throw_to_read_char ();
+       quit_throw_to_read_char (1);
  #endif
  }
  
  /* Handle a C-g by making read_char return C-g.  */
  
  static void
- quit_throw_to_read_char (void)
+ quit_throw_to_read_char (int from_signal)
  {
+   /* When not called from a signal handler it is safe to call
+      Lisp.  */
+   if (!from_signal && EQ (Vquit_flag, Qkill_emacs))
+     Fkill_emacs (Qnil);
    sigfree ();
    /* Prevent another signal from doing this before we finish.  */
    clear_waiting_for_input ();
@@@ -12105,7 -12116,7 +12121,7 @@@ This variable is keyboard-local.  */)
  Function key definitions that apply to all terminal devices should go
  here.  If a mapping is defined in both the current
  `local-function-key-map' binding and this variable, then the local
- definition will take precendence.  */);
+ definition will take precedence.  */);
    Vfunction_key_map = Fmake_sparse_keymap (Qnil);
  
    DEFVAR_LISP ("key-translation-map", Vkey_translation_map,
@@@ -12250,7 -12261,7 +12266,7 @@@ text in the region before modifying th
    DEFVAR_LISP ("debug-on-event",
                 Vdebug_on_event,
                 doc: /* Enter debugger on this event.  When Emacs
- receives the special event specifed by this variable, it will try to
+ receives the special event specified by this variable, it will try to
  break into the debugger as soon as possible instead of processing the
  event normally through `special-event-map'.
  
diff --combined src/lisp.h
index 648eb6430bd33f5ab5fa115ede273e49079a6e67,a80d39765e0452cc3ab05f760784d84bd7047133..ecc2fd1626787d8d89ea3908bde74580e780c4eb
@@@ -163,14 -163,23 +163,23 @@@ extern int suppress_checking EXTERNALLY
  /* First, try and define DECL_ALIGN(type,var) which declares a static
     variable VAR of type TYPE with the added requirement that it be
     TYPEBITS-aligned.  */
+ #ifndef GCTYPEBITS
+ #define GCTYPEBITS 3
+ #endif
  #ifndef NO_DECL_ALIGN
  # ifndef DECL_ALIGN
  #  if HAVE_ATTRIBUTE_ALIGNED
  #   define DECL_ALIGN(type, var) \
       type __attribute__ ((__aligned__ (1 << GCTYPEBITS))) var
  #  elif defined(_MSC_VER)
+ #   define ALIGN_GCTYPEBITS 8
+ #   if (1 << GCTYPEBITS) != ALIGN_GCTYPEBITS
+ #    error ALIGN_GCTYPEBITS is wrong!
+ #   endif
  #   define DECL_ALIGN(type, var) \
-      type __declspec(align(1 << GCTYPEBITS)) var
+      type __declspec(align(ALIGN_GCTYPEBITS)) var
  #  else
       /* What directives do other compilers use?  */
  #  endif
@@@ -300,10 -309,6 +309,6 @@@ enum Lisp_Fwd_Typ
      Lisp_Fwd_Kboard_Obj,      /* Fwd to a Lisp_Object field of kboards.  */
    };
  
- #ifndef GCTYPEBITS
- #define GCTYPEBITS 3
- #endif
  /* These values are overridden by the m- file on some machines.  */
  #ifndef VALBITS
  #define VALBITS (BITS_PER_EMACS_INT - GCTYPEBITS)
@@@ -324,7 -329,7 +329,7 @@@ union Lisp_Objec
  
      struct
        {
-       /* Use explict signed, the signedness of a bit-field of type
+       /* Use explicit signed, the signedness of a bit-field of type
           int is implementation defined.  */
        signed EMACS_INT val  : VALBITS;
        ENUM_BF (Lisp_Type) type : GCTYPEBITS;
@@@ -349,7 -354,7 +354,7 @@@ union Lisp_Objec
      struct
        {
        ENUM_BF (Lisp_Type) type : GCTYPEBITS;
-       /* Use explict signed, the signedness of a bit-field of type
+       /* Use explicit signed, the signedness of a bit-field of type
           int is implementation defined.  */
        signed EMACS_INT val  : VALBITS;
        } s;
@@@ -384,13 -389,14 +389,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
@@@ -593,12 -599,6 +598,12 @@@ extern Lisp_Object make_number (EMACS_I
  #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))
@@@ -805,7 -805,7 +810,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
@@@ -948,7 -948,7 +953,7 @@@ struct Lisp_Vecto
  
  /* Compute A OP B, using the unsigned comparison operator OP.  A and B
     should be integer expressions.  This is not the same as
-    mathemeatical comparison; for example, UNSIGNED_CMP (0, <, -1)
+    mathematical comparison; for example, UNSIGNED_CMP (0, <, -1)
     returns 1.  For efficiency, prefer plain unsigned comparison if A
     and B's sizes both fit (after integer promotion).  */
  #define UNSIGNED_CMP(a, op, b)                                                \
@@@ -1062,7 -1062,7 +1067,7 @@@ struct Lisp_Bool_Vecto
  
  struct Lisp_Subr
    {
 -    EMACS_INT size;
 +    ptrdiff_t size;
      union {
        Lisp_Object (*a0) (void);
        Lisp_Object (*a1) (Lisp_Object);
@@@ -1249,7 -1249,7 +1254,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.
@@@ -1366,12 -1366,12 +1371,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.
@@@ -1637,24 -1637,18 +1642,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                                                                  \
      {                                                                 \
@@@ -1714,9 -1708,7 +1719,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)
  #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)
  
      CHECK_NATNUM (tmp);                       \
      XSETCDR ((x), tmp);                       \
    } while (0)
- /* Cast pointers to this type to compare them.  */
- #define PNTR_COMPARISON_TYPE uintptr_t
  \f
  /* Define a built-in function for calling from Lisp.
   `lname' should be the name to give the function in Lisp,
@@@ -2079,9 -2049,9 +2081,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
@@@ -2134,8 -2104,8 +2136,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;
@@@ -2158,7 -2128,10 +2160,10 @@@ extern char *stack_bottom
     Exception: if you set immediate_quit to nonzero,
     then the handler that responds to the C-g does the quit itself.
     This is a good thing to do around a loop that has no side effects
-    and (in particular) cannot call arbitrary Lisp code.  */
+    and (in particular) cannot call arbitrary Lisp code.
+    If quit-flag is set to `kill-emacs' the SIGINT handler has received
+    a request to exit Emacs when it is safe to do.  */
  
  #ifdef SYNC_INPUT
  extern void process_pending_signals (void);
@@@ -2170,16 -2143,11 +2175,11 @@@ extern int pending_signals
  #define ELSE_PENDING_SIGNALS
  #endif        /* not SYNC_INPUT */
  
+ extern void process_quit_flag (void);
  #define QUIT                                          \
    do {                                                        \
      if (!NILP (Vquit_flag) && NILP (Vinhibit_quit))   \
-       {                                                       \
-         Lisp_Object flag = Vquit_flag;                        \
-       Vquit_flag = Qnil;                              \
-       if (EQ (Vthrow_on_input, flag))                 \
-         Fthrow (Vthrow_on_input, Qt);                 \
-       Fsignal (Qquit, Qnil);                          \
-       }                                                       \
+       process_quit_flag ();                           \
      ELSE_PENDING_SIGNALS                              \
    } while (0)
  
@@@ -2253,143 -2221,127 +2253,127 @@@ struct gcpr
                          || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
  
  
- #define GCPRO1(var) \
-   GCPRO1_VAR (var, gcpro)
- #define GCPRO2(var1, var2) \
-   GCPRO2_VAR (var1, var2, gcpro)
- #define GCPRO3(var1, var2, var3) \
-   GCPRO3_VAR (var1, var2, var3, gcpro)
- #define GCPRO4(var1, var2, var3, var4) \
-   GCPRO4_VAR (var1, var2, var3, var4, gcpro)
- #define GCPRO5(var1, var2, var3, var4, var5) \
-   GCPRO5_VAR (var1, var2, var3, var4, var5, gcpro)
- #define GCPRO6(var1, var2, var3, var4, var5, var6) \
-   GCPRO6_VAR (var1, var2, var3, var4, var5, var6, gcpro)
- #define UNGCPRO UNGCPRO_VAR (gcpro)
  #if GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS
  
  /* Do something silly with gcproN vars just so gcc shuts up.  */
  /* You get warnings from MIPSPro...  */
  
- #define GCPRO1_VAR(var, gcpro) ((void) gcpro##1)
- #define GCPRO2_VAR(var1, var2, gcpro) \
-   ((void) gcpro##2, (void) gcpro##1)
- #define GCPRO3_VAR(var1, var2, var3, gcpro) \
-   ((void) gcpro##3, (void) gcpro##2, (void) gcpro##1)
- #define GCPRO4_VAR(var1, var2, var3, var4, gcpro) \
-   ((void) gcpro##4, (void) gcpro##3, (void) gcpro##2, (void) gcpro##1)
- #define GCPRO5_VAR(var1, var2, var3, var4, var5, gcpro) \
-   ((void) gcpro##5, (void) gcpro##4, (void) gcpro##3, (void) gcpro##2, \
-    (void) gcpro##1)
- #define GCPRO6_VAR(var1, var2, var3, var4, var5, var6, gcpro) \
-   ((void) gcpro##6, (void) gcpro##5, (void) gcpro##4, (void) gcpro##3, \
-    (void) gcpro##2, (void) gcpro##1)
- #define UNGCPRO_VAR(gcpro) ((void) 0)
+ #define GCPRO1(varname) ((void) gcpro1)
+ #define GCPRO2(varname1, varname2) ((void) gcpro2, (void) gcpro1)
+ #define GCPRO3(varname1, varname2, varname3) \
+   ((void) gcpro3, (void) gcpro2, (void) gcpro1)
+ #define GCPRO4(varname1, varname2, varname3, varname4) \
+   ((void) gcpro4, (void) gcpro3, (void) gcpro2, (void) gcpro1)
+ #define GCPRO5(varname1, varname2, varname3, varname4, varname5) \
+   ((void) gcpro5, (void) gcpro4, (void) gcpro3, (void) gcpro2, (void) gcpro1)
+ #define GCPRO6(varname1, varname2, varname3, varname4, varname5, varname6) \
+   ((void) gcpro6, (void) gcpro5, (void) gcpro4, (void) gcpro3, (void) gcpro2, \
+    (void) gcpro1)
+ #define UNGCPRO ((void) 0)
  
  #else /* GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS */
  
  #ifndef DEBUG_GCPRO
  
- #define GCPRO1_VAR(var1, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcprolist = &gcpro##1; }
- #define GCPRO2_VAR(var1, var2, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcprolist = &gcpro##2; }
- #define GCPRO3_VAR(var1, var2, var3, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcprolist = &gcpro##3; }
- #define GCPRO4_VAR(var1, var2, var3, var4, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##4 .next = &gcpro##3; gcpro##4 .var = &var4; gcpro##4 .nvars = 1; \
-   gcprolist = &gcpro##4; }
- #define GCPRO5_VAR(var1, var2, var3, var4, var5, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##4 .next = &gcpro##3; gcpro##4 .var = &var4; gcpro##4 .nvars = 1; \
-   gcpro##5 .next = &gcpro##4; gcpro##5 .var = &var5; gcpro##5 .nvars = 1; \
-   gcprolist = &gcpro##5; }
- #define GCPRO6_VAR(var1, var2, var3, var4, var5, var6, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##4 .next = &gcpro##3; gcpro##4 .var = &var4; gcpro##4 .nvars = 1; \
-   gcpro##5 .next = &gcpro##4; gcpro##5 .var = &var5; gcpro##5 .nvars = 1; \
-   gcpro##6 .next = &gcpro##5; gcpro##6 .var = &var6; gcpro##6 .nvars = 1; \
-   gcprolist = &gcpro##6; }
- #define UNGCPRO_VAR(gcpro) (gcprolist = gcpro##1 .next)
+ #define GCPRO1(varname) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname; gcpro1.nvars = 1; \
+   gcprolist = &gcpro1; }
+ #define GCPRO2(varname1, varname2) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcprolist = &gcpro2; }
+ #define GCPRO3(varname1, varname2, varname3) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcprolist = &gcpro3; }
+ #define GCPRO4(varname1, varname2, varname3, varname4) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro4.next = &gcpro3; gcpro4.var = &varname4; gcpro4.nvars = 1; \
+   gcprolist = &gcpro4; }
+ #define GCPRO5(varname1, varname2, varname3, varname4, varname5) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro4.next = &gcpro3; gcpro4.var = &varname4; gcpro4.nvars = 1; \
+   gcpro5.next = &gcpro4; gcpro5.var = &varname5; gcpro5.nvars = 1; \
+   gcprolist = &gcpro5; }
+ #define GCPRO6(varname1, varname2, varname3, varname4, varname5, varname6) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro4.next = &gcpro3; gcpro4.var = &varname4; gcpro4.nvars = 1; \
+   gcpro5.next = &gcpro4; gcpro5.var = &varname5; gcpro5.nvars = 1; \
+   gcpro6.next = &gcpro5; gcpro6.var = &varname6; gcpro6.nvars = 1; \
+   gcprolist = &gcpro6; }
+ #define UNGCPRO (gcprolist = gcpro1.next)
  
  #else
  
  extern int gcpro_level;
  
- #define GCPRO1_VAR(var1, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##1 .level = gcpro_level++; \
-   gcprolist = &gcpro##1; }
- #define GCPRO2_VAR(var1, var2, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##1 .level = gcpro_level; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##2 .level = gcpro_level++; \
-   gcprolist = &gcpro##2; }
- #define GCPRO3_VAR(var1, var2, var3, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##1 .level = gcpro_level; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##3 .level = gcpro_level++; \
-   gcprolist = &gcpro##3; }
- #define GCPRO4_VAR(var1, var2, var3, var4, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##1 .level = gcpro_level; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##4 .next = &gcpro##3; gcpro##4 .var = &var4; gcpro##4 .nvars = 1; \
-   gcpro##4 .level = gcpro_level++; \
-   gcprolist = &gcpro##4; }
- #define GCPRO5_VAR(var1, var2, var3, var4, var5, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##1 .level = gcpro_level; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##4 .next = &gcpro##3; gcpro##4 .var = &var4; gcpro##4 .nvars = 1; \
-   gcpro##5 .next = &gcpro##4; gcpro##5 .var = &var5; gcpro##5 .nvars = 1; \
-   gcpro##5 .level = gcpro_level++; \
-   gcprolist = &gcpro##5; }
- #define GCPRO6_VAR(var1, var2, var3, var4, var5, var6, gcpro) \
-  {gcpro##1 .next = gcprolist; gcpro##1 .var = &var1; gcpro##1 .nvars = 1; \
-   gcpro##1 .level = gcpro_level; \
-   gcpro##2 .next = &gcpro##1; gcpro##2 .var = &var2; gcpro##2 .nvars = 1; \
-   gcpro##3 .next = &gcpro##2; gcpro##3 .var = &var3; gcpro##3 .nvars = 1; \
-   gcpro##4 .next = &gcpro##3; gcpro##4 .var = &var4; gcpro##4 .nvars = 1; \
-   gcpro##5 .next = &gcpro##4; gcpro##5 .var = &var5; gcpro##5 .nvars = 1; \
-   gcpro##6 .next = &gcpro##5; gcpro##6 .var = &var6; gcpro##6 .nvars = 1; \
-   gcpro##6 .level = gcpro_level++; \
-   gcprolist = &gcpro##6; }
- #define UNGCPRO_VAR(gcpro) \
-  ((--gcpro_level != gcpro##1 .level) \
-   ? (abort (), 0) \
-   : ((gcprolist = gcpro##1 .next), 0))
+ #define GCPRO1(varname) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname; gcpro1.nvars = 1; \
+   gcpro1.level = gcpro_level++; \
+   gcprolist = &gcpro1; }
+ #define GCPRO2(varname1, varname2) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro1.level = gcpro_level; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro2.level = gcpro_level++; \
+   gcprolist = &gcpro2; }
+ #define GCPRO3(varname1, varname2, varname3) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro1.level = gcpro_level; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro3.level = gcpro_level++; \
+   gcprolist = &gcpro3; }
+ #define GCPRO4(varname1, varname2, varname3, varname4) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro1.level = gcpro_level; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro4.next = &gcpro3; gcpro4.var = &varname4; gcpro4.nvars = 1; \
+   gcpro4.level = gcpro_level++; \
+   gcprolist = &gcpro4; }
+ #define GCPRO5(varname1, varname2, varname3, varname4, varname5) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro1.level = gcpro_level; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro4.next = &gcpro3; gcpro4.var = &varname4; gcpro4.nvars = 1; \
+   gcpro5.next = &gcpro4; gcpro5.var = &varname5; gcpro5.nvars = 1; \
+   gcpro5.level = gcpro_level++; \
+   gcprolist = &gcpro5; }
+ #define GCPRO6(varname1, varname2, varname3, varname4, varname5, varname6) \
+  {gcpro1.next = gcprolist; gcpro1.var = &varname1; gcpro1.nvars = 1; \
+   gcpro1.level = gcpro_level; \
+   gcpro2.next = &gcpro1; gcpro2.var = &varname2; gcpro2.nvars = 1; \
+   gcpro3.next = &gcpro2; gcpro3.var = &varname3; gcpro3.nvars = 1; \
+   gcpro4.next = &gcpro3; gcpro4.var = &varname4; gcpro4.nvars = 1; \
+   gcpro5.next = &gcpro4; gcpro5.var = &varname5; gcpro5.nvars = 1; \
+   gcpro6.next = &gcpro5; gcpro6.var = &varname6; gcpro6.nvars = 1; \
+   gcpro6.level = gcpro_level++; \
+   gcprolist = &gcpro6; }
+ #define UNGCPRO                                       \
+  ((--gcpro_level != gcpro1.level)             \
+   ? (abort (), 0)                             \
+   : ((gcprolist = gcpro1.next), 0))
  
  #endif /* DEBUG_GCPRO */
  #endif /* GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS */
@@@ -2559,8 -2511,8 +2543,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);
@@@ -2596,7 -2548,7 +2580,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;
@@@ -2628,8 -2580,8 +2612,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);
@@@ -2657,8 -2609,8 +2641,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);
@@@ -2696,48 -2648,48 +2680,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 */
@@@ -2745,7 -2697,6 +2729,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);
@@@ -2767,7 -2718,7 +2751,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];
@@@ -2783,15 -2734,15 +2767,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);
@@@ -2800,7 -2751,7 +2784,7 @@@ 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 */
@@@ -2816,7 -2767,7 +2800,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
@@@ -2841,26 -2792,26 +2825,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                                              \
@@@ -2874,7 -2825,7 +2858,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 *);
@@@ -2958,7 -2909,7 +2942,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); \
@@@ -3034,7 -2985,7 +3018,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);
@@@ -3086,9 -3037,10 +3070,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);
@@@ -3102,12 -3054,12 +3086,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);
@@@ -3141,17 -3093,17 +3125,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 */
@@@ -3200,18 -3152,18 +3184,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);
  
@@@ -3297,9 -3249,9 +3281,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 */
@@@ -3337,6 -3289,7 +3321,7 @@@ extern Lisp_Object Qfile_name_handler_a
  #ifdef FLOAT_CATCH_SIGILL
  extern void fatal_error_signal (int);
  #endif
+ extern Lisp_Object Qkill_emacs;
  EXFUN (Fkill_emacs, 1) NO_RETURN;
  #if HAVE_SETLOCALE
  void fixup_locale (void);
@@@ -3430,12 -3383,12 +3415,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);
@@@ -3481,8 -3434,8 +3466,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);
@@@ -3491,8 -3444,8 +3476,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]);
  
@@@ -3718,7 -3671,7 +3703,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
index d7c5db3a02c1a74e9909797fbe10c85f9a5fd92e,582d8f46638219f6f320fed928813c732c85a37e..90bc8c11b963cebba29743dc13320b9b1283aff3
@@@ -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);
@@@ -1026,7 -1023,7 +1026,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);
  
@@@ -1701,7 -1696,7 +1701,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");
@@@ -1878,7 -1873,7 +1878,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,8 -1917,8 +1922,8 @@@ which is the input stream for reading c
  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 danse!  */
+   /* FIXME: Do the eval-sexp-add-defvars dance!  */
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object tem, cbuf;
  
    cbuf = Fcurrent_buffer ();
@@@ -2001,7 -1996,7 +2001,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);
@@@ -2504,17 -2499,16 +2504,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)
@@@ -3895,7 -3889,7 +3895,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;
@@@ -3990,7 -3984,7 +3990,7 @@@ init_obarray (void
    Qnil = intern_c_string ("nil");
  
    /* Fmake_symbol inits fields of new symbols with Qunbound and Qnil,
-      so those two need to be fixed manally.  */
+      so those two need to be fixed manually.  */
    SET_SYMBOL_VAL (XSYMBOL (Qunbound), Qunbound);
    XSYMBOL (Qunbound)->function = Qunbound;
    XSYMBOL (Qunbound)->plist = Qnil;
@@@ -4186,13 -4180,16 +4186,16 @@@ init_lread (void
                }
  
              /* Add site-lisp under the installation dir, if it exists.  */
-             tem = Fexpand_file_name (build_string ("site-lisp"),
-                                      Vinstallation_directory);
-             tem1 = Ffile_exists_p (tem);
-             if (!NILP (tem1))
+             if (!no_site_lisp)
                {
-                 if (NILP (Fmember (tem, Vload_path)))
-                   Vload_path = Fcons (tem, Vload_path);
+                 tem = Fexpand_file_name (build_string ("site-lisp"),
+                                          Vinstallation_directory);
+                 tem1 = Ffile_exists_p (tem);
+                 if (!NILP (tem1))
+                   {
+                     if (NILP (Fmember (tem, Vload_path)))
+                       Vload_path = Fcons (tem, Vload_path);
+                   }
                }
  
              /* If Emacs was not built in the source directory,
                      if (NILP (Fmember (tem, Vload_path)))
                        Vload_path = Fcons (tem, Vload_path);
  
-                     tem = Fexpand_file_name (build_string ("site-lisp"),
-                                              Vsource_directory);
+                     if (!no_site_lisp)
+                       {
+                         tem = Fexpand_file_name (build_string ("site-lisp"),
+                                                  Vsource_directory);
  
-                     if (NILP (Fmember (tem, Vload_path)))
-                       Vload_path = Fcons (tem, Vload_path);
+                         if (NILP (Fmember (tem, Vload_path)))
+                           Vload_path = Fcons (tem, Vload_path);
+                       }
                    }
                }
              if (!NILP (sitelisp) && !no_site_lisp)
diff --combined src/minibuf.c
index 7dd189c325b70555e40d06eae7194b36023d70d3,ad5625e9ee9e9995e44b1f560fd92254142ad604..9a4df33378832513f023b631065040500c1e529d
@@@ -89,7 -89,7 +89,7 @@@ static Lisp_Object minibuf_prompt
  /* Width of current mini-buffer prompt.  Only set after display_line
     of the line that contains the prompt.  */
  
 -static EMACS_INT minibuf_prompt_width;
 +static ptrdiff_t minibuf_prompt_width;
  
  \f
  /* Put minibuf on currently selected frame's minibuffer.
@@@ -172,7 -172,7 +172,7 @@@ without invoking the usual minibuffer c
  static Lisp_Object read_minibuf_unwind (Lisp_Object);
  static Lisp_Object run_exit_minibuf_hook (Lisp_Object);
  static Lisp_Object read_minibuf (Lisp_Object, Lisp_Object,
 -                                 Lisp_Object, Lisp_Object,
 +                                 Lisp_Object,
                                   int, Lisp_Object,
                                   Lisp_Object, Lisp_Object,
                                   int, int);
@@@ -192,7 -192,7 +192,7 @@@ string_to_object (Lisp_Object val, Lisp
  {
    struct gcpro gcpro1, gcpro2;
    Lisp_Object expr_and_pos;
 -  EMACS_INT pos;
 +  ptrdiff_t pos;
  
    GCPRO2 (val, defalt);
  
      {
        /* Ignore trailing whitespace; any other trailing junk
         is an error.  */
 -      EMACS_INT i;
 +      ptrdiff_t i;
        pos = string_char_to_byte (val, pos);
        for (i = pos; i < SBYTES (val); i++)
        {
@@@ -335,7 -335,7 +335,7 @@@ DEFUN ("minibuffer-contents", Fminibuff
  If the current buffer is not a minibuffer, return its entire contents.  */)
    (void)
  {
 -  EMACS_INT prompt_end = XINT (Fminibuffer_prompt_end ());
 +  ptrdiff_t prompt_end = XINT (Fminibuffer_prompt_end ());
    return make_buffer_string (prompt_end, ZV, 1);
  }
  
@@@ -345,7 -345,7 +345,7 @@@ DEFUN ("minibuffer-contents-no-properti
  If the current buffer is not a minibuffer, return its entire contents.  */)
    (void)
  {
 -  EMACS_INT prompt_end = XINT (Fminibuffer_prompt_end ());
 +  ptrdiff_t prompt_end = XINT (Fminibuffer_prompt_end ());
    return make_buffer_string (prompt_end, ZV, 0);
  }
  
@@@ -356,7 -356,7 +356,7 @@@ That is what completion commands operat
  If the current buffer is not a minibuffer, return its entire contents.  */)
    (void)
  {
 -  EMACS_INT prompt_end = XINT (Fminibuffer_prompt_end ());
 +  ptrdiff_t prompt_end = XINT (Fminibuffer_prompt_end ());
    if (PT < prompt_end)
      error ("Cannot do completion in the prompt");
    return make_buffer_string (prompt_end, PT, 1);
  
  static Lisp_Object
  read_minibuf (Lisp_Object map, Lisp_Object initial, Lisp_Object prompt,
 -            Lisp_Object backup_n, int expflag,
 +            int expflag,
              Lisp_Object histvar, Lisp_Object histpos, Lisp_Object defalt,
              int allow_props, int inherit_input_method)
  {
    Lisp_Object val;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object mini_frame, ambient_dir, minibuffer, input_method;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
    Lisp_Object enable_multibyte;
 -  int pos = INTEGERP (backup_n) ? XINT (backup_n) : 0;
 +  EMACS_INT pos = 0;
    /* String to add to the history.  */
    Lisp_Object histstring;
  
      {
        if (CONSP (initial))
        {
 -        backup_n = Fcdr (initial);
 +        Lisp_Object backup_n = Fcdr (initial);
          initial = Fcar (initial);
          CHECK_STRING (initial);
          if (!NILP (backup_n))
  
    /* Erase the buffer.  */
    {
 -    int count1 = SPECPDL_INDEX ();
 +    ptrdiff_t count1 = SPECPDL_INDEX ();
      specbind (Qinhibit_read_only, Qt);
      specbind (Qinhibit_modification_hooks, Qt);
      Ferase_buffer ();
@@@ -802,7 -802,7 +802,7 @@@ get_minibuffer (EMACS_INT depth
      }
    else
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        /* `reset_buffer' blindly sets the list of overlays to NULL, so we
         have to empty the list, otherwise we end up with overlays that
         think they belong to this buffer while the buffer doesn't know about
@@@ -870,7 -870,7 +870,7 @@@ read_minibuf_unwind (Lisp_Object data
  
    /* Erase the minibuffer we were using at this level.  */
    {
 -    int count = SPECPDL_INDEX ();
 +    ptrdiff_t count = SPECPDL_INDEX ();
      /* Prevent error in erase-buffer.  */
      specbind (Qinhibit_read_only, Qt);
      specbind (Qinhibit_modification_hooks, Qt);
@@@ -905,26 -905,36 +905,36 @@@ DEFUN ("read-from-minibuffer", Fread_fr
  The optional second arg INITIAL-CONTENTS is an obsolete alternative to
    DEFAULT-VALUE.  It normally should be nil in new code, except when
    HIST is a cons.  It is discussed in more detail below.
  Third arg KEYMAP is a keymap to use whilst reading;
    if omitted or nil, the default is `minibuffer-local-map'.
- If fourth arg READ is non-nil, then interpret the result as a Lisp object
+ If fourth arg READ is non-nil, interpret the result as a Lisp object
    and return that object:
    in other words, do `(car (read-from-string INPUT-STRING))'
  Fifth arg HIST, if non-nil, specifies a history list and optionally
    the initial position in the list.  It can be a symbol, which is the
-   history list variable to use, or it can be a cons cell
-   (HISTVAR . HISTPOS).  In that case, HISTVAR is the history list variable
-   to use, and HISTPOS is the initial position for use by the minibuffer
-   history commands.  For consistency, you should also specify that
-   element of the history as the value of INITIAL-CONTENTS.  Positions
-   are counted starting from 1 at the beginning of the list.
- Sixth arg DEFAULT-VALUE is a default value or list of default values.
-   If non-nil, it is available via history commands.  If READ is
-   non-nil, it is also the default to `read' if the user enters empty
-   input.  If READ is non-nil, `read-from-minibuffer' does NOT return
-   DEFAULT-VALUE for empty input!  It returns the empty string.
+   history list variable to use, or a cons cell (HISTVAR . HISTPOS).
+   In that case, HISTVAR is the history list variable to use, and
+   HISTPOS is the initial position for use by the minibuffer history
+   commands.  For consistency, you should also specify that element of
+   the history as the value of INITIAL-CONTENTS.  Positions are counted
+   starting from 1 at the beginning of the list.
+ Sixth arg DEFAULT-VALUE, if non-nil, should be a string, which is used
+   as the default to `read' if READ is non-nil and the user enters
+   empty input.  But if READ is nil, this function does _not_ return
+   DEFAULT-VALUE for empty input!  Instead, it returns the empty string.
+   Whatever the value of READ, DEFAULT-VALUE is made available via the
+   minibuffer history commands.  DEFAULT-VALUE can also be a list of
+   strings, in which case all the strings are available in the history,
+   and the first string is the default to `read' if READ is non-nil.
  Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
   the current input method and the setting of `enable-multibyte-characters'.
  If the variable `minibuffer-allow-text-properties' is non-nil,
   then the string which is returned includes whatever text properties
   were present in the minibuffer.  Otherwise the value has no text properties.
@@@ -968,7 -978,7 +978,7 @@@ and some related functions, which use z
  
    GCPRO1 (default_value);
    val = read_minibuf (keymap, initial_contents, prompt,
 -                    Qnil, !NILP (read),
 +                    !NILP (read),
                      histvar, histpos, default_value,
                      minibuffer_allow_text_properties,
                      !NILP (inherit_input_method));
@@@ -986,7 -996,7 +996,7 @@@ Such arguments are used as in `read-fro
  {
    CHECK_STRING (prompt);
    return read_minibuf (Vminibuffer_local_map, initial_contents,
 -                     prompt, Qnil, 1, Qminibuffer_history,
 +                     prompt, 1, Qminibuffer_history,
                       make_number (0), Qnil, 0, 0);
  }
  
@@@ -999,7 -1009,7 +1009,7 @@@ Such arguments are used as in `read-fro
    (Lisp_Object prompt, Lisp_Object initial_contents)
  {
    return Feval (read_minibuf (Vread_expression_map, initial_contents,
 -                            prompt, Qnil, 1, Qread_expression_history,
 +                            prompt, 1, Qread_expression_history,
                              make_number (0), Qnil, 0, 0),
                Qnil);
  }
@@@ -1045,7 -1055,7 +1055,7 @@@ the current input method and the settin
    (Lisp_Object prompt, Lisp_Object initial, Lisp_Object inherit_input_method)
  {
    CHECK_STRING (prompt);
 -  return read_minibuf (Vminibuffer_local_ns_map, initial, prompt, Qnil,
 +  return read_minibuf (Vminibuffer_local_ns_map, initial, prompt,
                       0, Qminibuffer_history, make_number (0), Qnil, 0,
                       !NILP (inherit_input_method));
  }
@@@ -1125,7 -1135,7 +1135,7 @@@ function, instead of the usual behavior
    Lisp_Object args[4], result;
    char *s;
    ptrdiff_t len;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    if (BUFFERP (def))
      def = BVAR (XBUFFER (def), name);
@@@ -1224,9 -1234,9 +1234,9 @@@ is used to further constrain the set o
  {
    Lisp_Object bestmatch, tail, elt, eltstring;
    /* Size in bytes of BESTMATCH.  */
 -  int bestmatchsize = 0;
 +  ptrdiff_t bestmatchsize = 0;
    /* These are in bytes, too.  */
 -  int compare, matchsize;
 +  ptrdiff_t compare, matchsize;
    enum { function_table, list_table, obarray_table, hash_table}
      type = (HASH_TABLE_P (collection) ? hash_table
            : VECTORP (collection) ? obarray_table
                    && (!SYMBOLP (XCAR (collection))
                        || NILP (XCAR (collection)))))
               ? list_table : function_table));
 -  EMACS_INT idx = 0, obsize = 0;
 +  ptrdiff_t idx = 0, obsize = 0;
    int matchcount = 0;
 -  int bindcount = -1;
 +  ptrdiff_t bindcount = -1;
    Lisp_Object bucket, zero, end, tem;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
  
@@@ -1500,8 -1510,8 +1510,8 @@@ with a space are ignored unless STRING 
      : NILP (collection) || (CONSP (collection)
                            && (!SYMBOLP (XCAR (collection))
                                || NILP (XCAR (collection))));
 -  EMACS_INT idx = 0, obsize = 0;
 -  int bindcount = -1;
 +  ptrdiff_t idx = 0, obsize = 0;
 +  ptrdiff_t bindcount = -1;
    Lisp_Object bucket, tem, zero;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
  
@@@ -1810,7 -1820,7 +1820,7 @@@ the values STRING, PREDICATE and `lambd
    /* Reject this element if it fails to match all the regexps.  */
    if (CONSP (Vcompletion_regexp_list))
      {
 -      int count = SPECPDL_INDEX ();
 +      ptrdiff_t count = SPECPDL_INDEX ();
        specbind (Qcase_fold_search, completion_ignore_case ? Qt : Qnil);
        for (regexps = Vcompletion_regexp_list; CONSP (regexps);
           regexps = XCDR (regexps))
diff --combined src/nsfns.m
index f320a909497073d8a06971b5b9d54e8ab78a442c,9dade071e8578a7756a1888f95ea436d5102365d..ccefec1e34fc008260d856eb8031ff4a456331fc
@@@ -169,7 -169,7 +169,7 @@@ check_ns_display_info (Lisp_Object fram
        struct terminal *t = get_terminal (frame, 1);
  
        if (t->type != output_ns)
 -        error ("Terminal %ld is not a Nextstep display", (long) XINT (frame));
 +        error ("Terminal %"pI"d is not a Nextstep display", XINT (frame));
  
        return t->display_info.ns;
      }
@@@ -710,7 -710,7 +710,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;
@@@ -742,7 -742,7 +742,7 @@@ x_set_tool_bar_lines (struct frame *f, 
    if (FRAME_MINIBUF_ONLY_P (f))
      return;
  
 -  if (INTEGERP (value) && XINT (value) >= 0)
 +  if (RANGED_INTEGERP (0, value, INT_MAX))
      nlines = XFASTINT (value);
    else
      nlines = 0;
@@@ -1076,7 -1076,41 +1076,41 @@@ unwind_create_frame (Lisp_Object frame
    return Qnil;
  }
  
+ /*
+  * Read geometry related parameters from preferences if not in PARMS.
+  * Returns the union of parms and any preferences read.
+  */
+ static Lisp_Object
+ get_geometry_from_preferences (struct ns_display_info *dpyinfo,
+                                Lisp_Object parms)
+ {
+   struct {
+     const char *val;
+     const char *cls;
+     Lisp_Object tem;
+   } r[] = {
+     { "width",  "Width", Qwidth },
+     { "height", "Height", Qheight },
+     { "left", "Left", Qleft },
+     { "top", "Top", Qtop },
+   };
+   int i;
+   for (i = 0; i < sizeof (r)/sizeof (r[0]); ++i)
+     {
+       if (NILP (Fassq (r[i].tem, parms)))
+         {
+           Lisp_Object value
+             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
+                          RES_TYPE_NUMBER);
+           if (! EQ (value, Qunbound))
+             parms = Fcons (Fcons (r[i].tem, value), parms);
+         }
+     }
  
+   return parms;
+ }
  
  /* ==========================================================================
  
@@@ -1103,7 -1137,7 +1137,7 @@@ This function is an internal primitive-
    int minibuffer_only = 0;
    int window_prompting = 0;
    int width, height;
 -  int count = specpdl_ptr - specpdl;
 +  ptrdiff_t count = specpdl_ptr - specpdl;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
    Lisp_Object display;
    struct ns_display_info *dpyinfo = NULL;
    record_unwind_protect (unwind_create_frame, frame);
  
    f->output_data.ns->window_desc = desc_ctr++;
 -  if (!NILP (parent))
 +  if (TYPE_RANGED_INTEGERP (Window, parent))
      {
 -      f->output_data.ns->parent_desc = (Window) XFASTINT (parent);
 +      f->output_data.ns->parent_desc = XFASTINT (parent);
        f->output_data.ns->explicit_parent = 1;
      }
    else
    x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
                         RES_TYPE_STRING);
  
+   parms = get_geometry_from_preferences (dpyinfo, parms);
    window_prompting = x_figure_window_size (f, parms, 1);
  
    tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
@@@ -1511,6 -1546,17 +1546,17 @@@ Optional arg INIT, if non-nil, provide
    return ret ? fname : Qnil;
  }
  
+ const char *
+ ns_get_defaults_value (const char *key)
+ {
+   NSObject *obj = [[NSUserDefaults standardUserDefaults]
+                     objectForKey: [NSString stringWithUTF8String: key]];
+   if (!obj) return NULL;
+   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
+ }
  
  DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
         doc: /* Return the value of the property NAME of OWNER from the defaults database.
@@@ -1525,9 -1571,7 +1571,7 @@@ If OWNER is nil, Emacs is assumed.  */
    CHECK_STRING (name);
  /*fprintf (stderr, "ns-get-resource checking resource '%s'\n", SDATA (name)); */
  
-   value =[[[NSUserDefaults standardUserDefaults]
-             objectForKey: [NSString stringWithUTF8String: SDATA (name)]]
-            UTF8String];
+   value = ns_get_defaults_value (SDATA (name));
  
    if (value)
      return build_string (value);
@@@ -2182,8 -2226,7 +2226,7 @@@ x_get_string_resource (XrmDatabase rdb
      /* --quick was passed, so this is a no-op.  */
      return NULL;
  
-   res = [[[NSUserDefaults standardUserDefaults] objectForKey:
-             [NSString stringWithUTF8String: toCheck]] UTF8String];
+   res = ns_get_defaults_value (toCheck);
    return !res ? NULL :
        (!strncasecmp (res, "YES", 3) ? "true" :
            (!strncasecmp (res, "NO", 2) ? "false" : res));
@@@ -2506,7 -2549,7 +2549,7 @@@ Text larger than the specified size is 
  {
    int root_x, root_y;
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    struct frame *f;
    char *str;
    NSSize size;
diff --combined src/nsfont.m
index ca94b07a6bd20bb1b971b52006d441450ce1f2d6,7d691ced6e1fa402a7a11d0a8f3d2faef5f31dca..7dfb995dd27f9a684e4e3d467e82feec852220b8
@@@ -256,7 -256,7 +256,7 @@@ ns_char_width (NSFont *sfont, int c
  
  
  /* Return whether set1 covers set2 to a reasonable extent given by pct.
-    We check, out of each 16 unicode char range containing chars in set2,
+    We check, out of each 16 Unicode char range containing chars in set2,
     whether at least one character is present in set1.
     This must be true for pct of the pairs to consider it covering. */
  static BOOL
@@@ -297,7 -297,7 +297,7 @@@ static NSStrin
  
  
  /* Convert OTF 4-letter script code to emacs script name.  (Why can't
-    everyone just use some standard unicode names for these?) */
+    everyone just use some standard Unicode names for these?) */
  static NSString
  *ns_otf_to_script (Lisp_Object otf)
  {
@@@ -329,7 -329,7 +329,7 @@@ static NSStrin
  
  /* Searches the :script, :lang, and :otf extra-bundle properties of the spec,
     plus registry regular property, for something that can be mapped to a
-    unicode script.  Empty string returned if no script spec found. */
+    Unicode script.  Empty string returned if no script spec found. */
  static NSString
  *ns_get_req_script (Lisp_Object font_spec)
  {
@@@ -385,7 -385,7 +385,7 @@@ accumulate_script_ranges (Lisp_Object a
  }
  
  
- /* Use the unicode range information in Vchar_script_table to convert a script
+ /* Use the Unicode range information in Vchar_script_table to convert a script
     name into an NSCharacterSet. */
  static NSCharacterSet
  *ns_script_to_charset (NSString *scriptName)
     If none are found, we reduce the percentage and try again, until 5%.
     This provides a font with at least some characters if such can be found.
     We don't use isSupersetOfSet: because (a) it doesn't work on Tiger, and
-    (b) need approximate match as fonts covering full unicode ranges are rare. */
+    (b) need approximate match as fonts covering full Unicode ranges are rare. */
  static NSSet
  *ns_get_covering_families (NSString *script, float pct)
  {
@@@ -549,8 -549,8 +549,8 @@@ ns_findfonts (Lisp_Object font_spec, BO
        return ns_fallback_entity ();
  
      if (NSFONT_TRACE)
 -      fprintf (stderr, "    Returning %ld entities.\n",
 -                 (long) XINT (Flength (list)));
 +      fprintf (stderr, "    Returning %"pI"d entities.\n",
 +                 XINT (Flength (list)));
  
      return list;
  }
@@@ -656,8 -656,8 +656,8 @@@ nsfont_list_family (Lisp_Object frame
    /* FIXME: escape the name? */
  
    if (NSFONT_TRACE)
 -    fprintf (stderr, "nsfont: list families returning %ld entries\n",
 -            (long) XINT (Flength (list)));
 +    fprintf (stderr, "nsfont: list families returning %"pI"d entries\n",
 +           XINT (Flength (list)));
  
    return list;
  }
@@@ -1292,7 -1292,7 +1292,7 @@@ ns_uni_to_glyphs (struct nsfont_info *f
    if (!unichars || !(font_info->glyphs[block]))
      abort ();
  
-   /* create a string containing all unicode characters in this block */
+   /* create a string containing all Unicode characters in this block */
    for (idx = block<<8, i =0; i<0x100; idx++, i++)
      if (idx < 0xD800 || idx > 0xDFFF)
        unichars[i] = idx;
@@@ -1487,5 -1487,5 +1487,5 @@@ syms_of_nsfont (void
    DEFSYM (Qroman, "roman");
    DEFSYM (Qmedium, "medium");
    DEFVAR_LISP ("ns-reg-to-script", Vns_reg_to_script,
-                doc: /* Internal use: maps font registry to unicode script. */);
+                doc: /* Internal use: maps font registry to Unicode script. */);
  }
diff --combined src/print.c
index f3302daaea344b5b91f9cf08e4b99c3352fded1c,fc36d29da7ce9cee4c7a1eb154ed6c135d3d525b..b8b7ab371f6e499fb39d8f61ef753c91bc7ecf5a
@@@ -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;
@@@ -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).  */
@@@ -864,13 -875,10 +864,13 @@@ print_error_message (Lisp_Object data, 
    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);
@@@ -1084,7 -1092,7 +1084,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 -1126,7 +1118,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 -1269,8 +1261,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));
@@@ -1384,10 -1392,10 +1384,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);
                /* Detect circular list.  */
                if (NILP (Vprint_circle))
                  {
-                   /* Simple but imcomplete way.  */
+                   /* Simple but incomplete way.  */
                    if (i != 0 && EQ (obj, halftail))
                      {
                        sprintf (buf, " . #%"pMd, i / 2);
          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/process.c
index 71da2e17670e71a469ad9386e242155f8487256e,4b0f90b58afa436245791273c23b6a396d347755..206af7059fbafb5e6058038f82c64ab59dbd2309
@@@ -764,7 -764,9 +764,7 @@@ nil, indicating the current buffer's pr
      {
  #ifdef SIGCHLD
        Lisp_Object symbol;
 -      /* Assignment to EMACS_INT stops GCC whining about limited range
 -       of data type.  */
 -      EMACS_INT pid = p->pid;
 +      pid_t pid = p->pid;
  
        /* No problem storing the pid here, as it is still in Vprocess_alist.  */
        deleted_pid_list = Fcons (make_fixnum_or_float (pid),
@@@ -861,7 -863,9 +861,7 @@@ This is the pid of the external proces
  For a network connection, this value is nil.  */)
    (register Lisp_Object process)
  {
 -  /* Assignment to EMACS_INT stops GCC whining about limited range of
 -     data type.  */
 -  EMACS_INT pid;
 +  pid_t pid;
  
    CHECK_PROCESS (process);
    pid = XPROCESS (process)->pid;
@@@ -1036,8 -1040,8 +1036,8 @@@ DEFUN ("set-process-window-size", Fset_
    (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
  {
    CHECK_PROCESS (process);
 -  CHECK_NATNUM (height);
 -  CHECK_NATNUM (width);
 +  CHECK_RANGED_INTEGER (0, height, INT_MAX);
 +  CHECK_RANGED_INTEGER (0, width, INT_MAX);
  
    if (XPROCESS (process)->infd < 0
        || set_window_size (XPROCESS (process)->infd,
@@@ -1197,7 -1201,7 +1197,7 @@@ Returns nil if format of ADDRESS is inv
    if (VECTORP (address))  /* AF_INET or AF_INET6 */
      {
        register struct Lisp_Vector *p = XVECTOR (address);
 -      EMACS_INT size = p->header.size;
 +      ptrdiff_t size = p->header.size;
        Lisp_Object args[10];
        int nargs, i;
  
  
        for (i = 0; i < nargs; i++)
        {
 -        EMACS_INT element = XINT (p->contents[i]);
 -
 -        if (element < 0 || element > 65535)
 +        if (! RANGED_INTEGERP (0, p->contents[i], 65535))
            return Qnil;
  
          if (nargs <= 5         /* IPv4 */
              && i < 4           /* host, not port */
 -            && element > 255)
 +            && XINT (p->contents[i]) > 255)
            return Qnil;
  
          args[i+1] = p->contents[i];
@@@ -1286,7 -1292,7 +1286,7 @@@ usage: (start-process NAME BUFFER PROGR
    Lisp_Object buffer, name, program, proc, current_dir, tem;
    register unsigned char **new_argv;
    ptrdiff_t i;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    buffer = args[1];
    if (!NILP (buffer))
          val = XCDR (Vdefault_process_coding_system);
        }
      XPROCESS (proc)->encode_coding_system = val;
-     /* Note: At this momemnt, the above coding system may leave
+     /* Note: At this moment, the above coding system may leave
         text-conversion or eol-conversion unspecified.  They will be
         decided after we read output from the process and decode it by
         some coding system, or just before we actually send a text to
@@@ -1515,8 -1521,9 +1515,9 @@@ start_process_unwind (Lisp_Object proc
    if (!PROCESSP (proc))
      abort ();
  
-   /* Was PROC started successfully?  */
-   if (XPROCESS (proc)->pid == -1)
+   /* Was PROC started successfully?
+      -2 is used for a pty with no process, eg for gdb.  */
+   if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
      remove_process (proc);
  
    return Qnil;
@@@ -2095,8 -2102,7 +2096,8 @@@ get_lisp_to_sockaddr_size (Lisp_Object 
        return sizeof (struct sockaddr_un);
      }
  #endif
 -  else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
 +  else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
 +         && VECTORP (XCDR (address)))
      {
        struct sockaddr *sa;
        *familyp = XINT (XCAR (address));
@@@ -2119,7 -2125,6 +2120,7 @@@ conv_lisp_to_sockaddr (int family, Lisp
    register struct Lisp_Vector *p;
    register unsigned char *cp = NULL;
    register int i;
 +  EMACS_INT hostport;
  
    memset (sa, 0, len);
  
        {
          struct sockaddr_in *sin = (struct sockaddr_in *) sa;
          len = sizeof (sin->sin_addr) + 1;
 -        i = XINT (p->contents[--len]);
 -        sin->sin_port = htons (i);
 +        hostport = XINT (p->contents[--len]);
 +        sin->sin_port = htons (hostport);
          cp = (unsigned char *)&sin->sin_addr;
          sa->sa_family = family;
        }
          struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
          uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
          len = sizeof (sin6->sin6_addr) + 1;
 -        i = XINT (p->contents[--len]);
 -        sin6->sin6_port = htons (i);
 +        hostport = XINT (p->contents[--len]);
 +        sin6->sin6_port = htons (hostport);
          for (i = 0; i < len; i++)
            if (INTEGERP (p->contents[i]))
              {
@@@ -2297,7 -2302,7 +2298,7 @@@ set_socket_option (int s, Lisp_Object o
      case SOPT_INT:
        {
        int optval;
 -      if (INTEGERP (val))
 +      if (TYPE_RANGED_INTEGERP (int, val))
          optval = XINT (val);
        else
          error ("Bad option value for %s", name);
  
        linger.l_onoff = 1;
        linger.l_linger = 0;
 -      if (INTEGERP (val))
 +      if (TYPE_RANGED_INTEGERP (int, val))
          linger.l_linger = XINT (val);
        else
          linger.l_onoff = NILP (val) ? 0 : 1;
@@@ -2576,7 -2581,7 +2577,7 @@@ usage:  (make-serial-process &rest ARGS
    struct gcpro gcpro1;
    Lisp_Object name, buffer;
    Lisp_Object tem, val;
 -  int specpdl_count = -1;
 +  ptrdiff_t specpdl_count = -1;
  
    if (nargs == 0)
      return Qnil;
@@@ -2876,8 -2881,8 +2877,8 @@@ usage: (make-network-process &rest ARGS
    int xerrno = 0;
    int s = -1, outch, inch;
    struct gcpro gcpro1;
 -  int count = SPECPDL_INDEX ();
 -  int count1;
 +  ptrdiff_t count = SPECPDL_INDEX ();
 +  ptrdiff_t count1;
    Lisp_Object QCaddress;  /* one of QClocal or QCremote */
    Lisp_Object tem;
    Lisp_Object name, buffer, host, service, address;
        error ("Network servers not supported");
  #else
        is_server = 1;
 -      if (INTEGERP (tem))
 +      if (TYPE_RANGED_INTEGERP (int, tem))
        backlog = XINT (tem);
  #endif
      }
  #endif
    else if (EQ (tem, Qipv4))
      family = AF_INET;
 -  else if (INTEGERP (tem))
 +  else if (TYPE_RANGED_INTEGERP (int, tem))
      family = XINT (tem);
    else
      error ("Unknown address family");
  
    {
      /* Setup coding systems for communicating with the network stream.  */
-     struct gcpro inner_gcpro1;
+     struct gcpro gcpro1;
      /* Qt denotes we have not yet called Ffind_operation_coding_system.  */
      Lisp_Object coding_systems = Qt;
      Lisp_Object fargs[5], val;
          {
            fargs[0] = Qopen_network_stream, fargs[1] = name,
              fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
-           GCPRO1_VAR (proc, inner_gcpro);
+           GCPRO1 (proc);
            coding_systems = Ffind_operation_coding_system (5, fargs);
-           UNGCPRO_VAR (inner_gcpro);
+           UNGCPRO;
          }
        if (CONSP (coding_systems))
          val = XCAR (coding_systems);
              {
                fargs[0] = Qopen_network_stream, fargs[1] = name,
                  fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
-               GCPRO1_VAR (proc, inner_gcpro);
+               GCPRO1 (proc);
                coding_systems = Ffind_operation_coding_system (5, fargs);
-               UNGCPRO_VAR (inner_gcpro);
+               UNGCPRO;
              }
          }
        if (CONSP (coding_systems))
@@@ -3713,7 -3718,7 +3714,7 @@@ DEFUN ("network-interface-info", Fnetwo
         doc: /* Return information about network interface named IFNAME.
  The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
  where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
- NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
+ NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
  FLAGS is the current flags of the interface.  */)
    (Lisp_Object ifname)
  {
@@@ -3947,7 -3952,7 +3948,7 @@@ If JUST-THIS-ONE is an integer, don't r
  Return non-nil if we received any output before the timeout expired.  */)
    (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
  {
 -  int secs, usecs = 0;
 +  int secs = -1, usecs = 0;
  
    if (! NILP (process))
      CHECK_PROCESS (process);
  
    if (!NILP (seconds))
      {
 -      if (INTEGERP (seconds))
 -      secs = XINT (seconds);
 -      else if (FLOATP (seconds))
 -      {
 -        double timeout = XFLOAT_DATA (seconds);
 -        secs = (int) timeout;
 -        usecs = (int) ((timeout - (double) secs) * 1000000);
 -      }
 -      else
 -      wrong_type_argument (Qnumberp, seconds);
 -
 -      if (secs < 0 || (secs == 0 && usecs == 0))
 -      secs = -1, usecs = 0;
 +      double duration = extract_float (seconds);
 +      if (0 < duration)
 +      duration_to_sec_usec (duration, &secs, &usecs);
      }
 -  else
 -    secs = NILP (process) ? -1 : 0;
 +  else if (!NILP (process))
 +    secs = 0;
  
    return
      (wait_reading_process_output (secs, usecs, 0, 0,
@@@ -4286,7 -4301,7 +4287,7 @@@ wait_reading_process_output (int time_l
    EMACS_TIME timeout, end_time;
    int wait_channel = -1;
    int got_some_input = 0;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    FD_ZERO (&Available);
    FD_ZERO (&Writeok);
               some data in the TCP buffers so that select works, but
               with custom pull/push functions we need to check if some
               data is available in the buffers manually.  */
-           if (nfds == 0 &&
-               wait_proc && wait_proc->gnutls_p /* Check for valid process.  */
-               /* Do we have pending data?  */
-               && emacs_gnutls_record_check_pending (wait_proc->gnutls_state) > 0)
-           {
-               nfds = 1;
-               /* Set to Available.  */
-               FD_SET (wait_proc->infd, &Available);
-           }
+           if (nfds == 0)
+           {
+             if (! wait_proc)
+               {
+                 /* We're not waiting on a specific process, so loop
+                    through all the channels and check for data.
+                    This is a workaround needed for some versions of
+                    the gnutls library -- 2.12.14 has been confirmed
+                    to need it.  See
+                    http://comments.gmane.org/gmane.emacs.devel/145074 */
+                 for (channel = 0; channel < MAXDESC; ++channel)
+                   if (! NILP (chan_process[channel]))
+                     {
+                       struct Lisp_Process *p =
+                         XPROCESS (chan_process[channel]);
+                       if (p && p->gnutls_p && p->infd
+                           && ((emacs_gnutls_record_check_pending
+                                (p->gnutls_state))
+                               > 0))
+                         {
+                           nfds++;
+                           FD_SET (p->infd, &Available);
+                         }
+                     }
+               }
+             else
+               {
+                 /* Check this specific channel. */
+                 if (wait_proc->gnutls_p /* Check for valid process.  */
+                     /* Do we have pending data?  */
+                     && ((emacs_gnutls_record_check_pending
+                          (wait_proc->gnutls_state))
+                         > 0))
+                   {
+                     nfds = 1;
+                     /* Set to Available.  */
+                     FD_SET (wait_proc->infd, &Available);
+                   }
+               }
+           }
  #endif
        }
  
@@@ -4984,11 -5030,11 +5016,11 @@@ read_process_output (Lisp_Object proc, 
    char *chars;
    register Lisp_Object outstream;
    register struct Lisp_Process *p = XPROCESS (proc);
 -  register EMACS_INT opoint;
 +  register ptrdiff_t opoint;
    struct coding_system *coding = proc_decode_coding_system[channel];
    int carryover = p->decoding_carryover;
    int readmax = 4096;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    Lisp_Object odeactivate;
  
    chars = (char *) alloca (carryover + readmax);
    else if (!NILP (p->buffer) && !NILP (BVAR (XBUFFER (p->buffer), name)))
      {
        Lisp_Object old_read_only;
 -      EMACS_INT old_begv, old_zv;
 -      EMACS_INT old_begv_byte, old_zv_byte;
 -      EMACS_INT before, before_byte;
 -      EMACS_INT opoint_byte;
 +      ptrdiff_t old_begv, old_zv;
 +      ptrdiff_t old_begv_byte, old_zv_byte;
 +      ptrdiff_t before, before_byte;
 +      ptrdiff_t opoint_byte;
        Lisp_Object text;
        struct buffer *b;
  
@@@ -5328,7 -5374,7 +5360,7 @@@ send_process_trap (int ignore
  
  static void
  send_process (volatile Lisp_Object proc, const char *volatile buf,
 -            volatile EMACS_INT len, volatile Lisp_Object object)
 +            volatile ptrdiff_t len, volatile Lisp_Object object)
  {
    /* Use volatile to protect variables from being clobbered by longjmp.  */
    struct Lisp_Process *p = XPROCESS (proc);
        coding->dst_object = Qt;
        if (BUFFERP (object))
        {
 -        EMACS_INT from_byte, from, to;
 -        EMACS_INT save_pt, save_pt_byte;
 +        ptrdiff_t from_byte, from, to;
 +        ptrdiff_t save_pt, save_pt_byte;
          struct buffer *cur = current_buffer;
  
          set_buffer_internal (XBUFFER (object));
        process_sent_to = proc;
        while (len > 0)
        {
 -        EMACS_INT this = len;
 +        ptrdiff_t this = len;
  
          /* Send this batch, using one or more write calls.  */
          while (this > 0)
            {
 -            EMACS_INT written = 0;
 +            ptrdiff_t written = 0;
              int outfd = p->outfd;
              old_sigpipe = (void (*) (int)) signal (SIGPIPE, send_process_trap);
  #ifdef DATAGRAM_SOCKETS
                       that may allow the program
                       to finish doing output and read more.  */
                    {
 -                    EMACS_INT offset = 0;
 +                    ptrdiff_t offset = 0;
  
  #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
                      /* A gross hack to work around a bug in FreeBSD.
@@@ -5598,7 -5644,7 +5630,7 @@@ Output from processes can arrive in bet
    (Lisp_Object process, Lisp_Object start, Lisp_Object end)
  {
    Lisp_Object proc;
 -  EMACS_INT start1, end1;
 +  ptrdiff_t start1, end1;
  
    proc = get_process (process);
    validate_region (&start, &end);
@@@ -5634,10 -5680,10 +5666,10 @@@ Output from processes can arrive in bet
  \f
  /* Return the foreground process group for the tty/pty that
     the process P uses.  */
 -static int
 +static pid_t
  emacs_get_tty_pgrp (struct Lisp_Process *p)
  {
 -  int gid = -1;
 +  pid_t gid = -1;
  
  #ifdef TIOCGPGRP
    if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
@@@ -5667,7 -5713,7 +5699,7 @@@ return t unconditionally.  */
  {
    /* Initialize in case ioctl doesn't exist or gives an error,
       in a way that will cause returning t.  */
 -  int gid;
 +  pid_t gid;
    Lisp_Object proc;
    struct Lisp_Process *p;
  
@@@ -5708,7 -5754,7 +5740,7 @@@ process_send_signal (Lisp_Object proces
  {
    Lisp_Object proc;
    register struct Lisp_Process *p;
 -  int gid;
 +  pid_t gid;
    int no_pgrp = 0;
  
    proc = get_process (process);
@@@ -5962,40 -6008,48 +5994,40 @@@ SIGCODE may be an integer, or a symbol 
  {
    pid_t pid;
  
 -  if (INTEGERP (process))
 -    {
 -      pid = XINT (process);
 -      goto got_it;
 -    }
 -
 -  if (FLOATP (process))
 -    {
 -      pid = (pid_t) XFLOAT_DATA (process);
 -      goto got_it;
 -    }
 -
    if (STRINGP (process))
      {
 -      Lisp_Object tem;
 -      if (tem = Fget_process (process), NILP (tem))
 +      Lisp_Object tem = Fget_process (process);
 +      if (NILP (tem))
        {
 -        pid = XINT (Fstring_to_number (process, make_number (10)));
 -        if (pid > 0)
 -          goto got_it;
 +        Lisp_Object process_number =
 +          string_to_number (SSDATA (process), 10, 1);
 +        if (INTEGERP (process_number) || FLOATP (process_number))
 +          tem = process_number;
        }
        process = tem;
      }
 -  else
 +  else if (!NUMBERP (process))
      process = get_process (process);
  
    if (NILP (process))
      return process;
  
 -  CHECK_PROCESS (process);
 -  pid = XPROCESS (process)->pid;
 -  if (pid <= 0)
 -    error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
 -
 - got_it:
 +  if (NUMBERP (process))
 +    CONS_TO_INTEGER (process, pid_t, pid);
 +  else
 +    {
 +      CHECK_PROCESS (process);
 +      pid = XPROCESS (process)->pid;
 +      if (pid <= 0)
 +      error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
 +    }
  
  #define parse_signal(NAME, VALUE)             \
    else if (!xstrcasecmp (name, NAME))         \
      XSETINT (sigcode, VALUE)
  
    if (INTEGERP (sigcode))
 -    ;
 +    CHECK_TYPE_RANGED_INTEGER (int, sigcode);
    else
      {
        char *name;
@@@ -6258,8 -6312,8 +6290,8 @@@ sigchld_handler (int signo
        for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
        {
          Lisp_Object xpid = XCAR (tail);
 -        if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
 -            || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
 +        if ((INTEGERP (xpid) && pid == XINT (xpid))
 +            || (FLOATP (xpid) && pid == XFLOAT_DATA (xpid)))
            {
              XSETCAR (tail, Qnil);
              goto sigchld_end_of_loop;
@@@ -6375,7 -6429,7 +6407,7 @@@ exec_sentinel (Lisp_Object proc, Lisp_O
  {
    Lisp_Object sentinel, odeactivate;
    register struct Lisp_Process *p = XPROCESS (proc);
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
    int outer_running_asynch_code = running_asynch_code;
    int waiting = waiting_for_user_input_p;
  
@@@ -6534,8 -6588,8 +6566,8 @@@ status_notify (struct Lisp_Process *del
            {
              Lisp_Object tem;
              struct buffer *old = current_buffer;
 -            EMACS_INT opoint, opoint_byte;
 -            EMACS_INT before, before_byte;
 +            ptrdiff_t opoint, opoint_byte;
 +            ptrdiff_t before, before_byte;
  
              /* Avoid error if buffer is deleted
                 (probably that's why the process is dead, too) */
diff --combined src/puresize.h
index a1b7007805b18b19652c749c6fdb9fdf40cf425c,4290c30c68d7c53cbd9d3bc7960b5cde7abc2b52..889d836af78931cee65de7d1afea649034ce8bdf
@@@ -46,12 -46,8 +46,12 @@@ 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 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
@@@ -79,21 -75,7 +79,7 @@@ extern void pure_write_error (void) NO_
  \f
  /* Define PURE_P.  */
  
- #ifdef VIRT_ADDR_VARIES
- /* For machines where text and data can go anywhere
-    in virtual memory.  */
  extern EMACS_INT pure[];
  
  #define PURE_P(obj) \
-  ((PNTR_COMPARISON_TYPE) XPNTR (obj) < (PNTR_COMPARISON_TYPE) ((char *) pure + PURESIZE) \
-   && (PNTR_COMPARISON_TYPE) XPNTR (obj) >= (PNTR_COMPARISON_TYPE) pure)
- #else /* not VIRT_ADDR_VARIES */
- extern char my_edata[];
- #define PURE_P(obj) \
-   ((PNTR_COMPARISON_TYPE) XPNTR (obj) < (PNTR_COMPARISON_TYPE) my_edata)
- #endif /* VIRT_ADDRESS_VARIES */
+   ((uintptr_t) XPNTR (obj) - (uintptr_t) pure <= PURESIZE)
diff --combined src/search.c
index df53dbf8d89f398bed7a2de2ecc09aefa8114e9e,811ac74e1943c5162398cdbdb78b4b63d4e4b335..160d08e3c8ca26b5ccc6a7ad7e710d73a77dca47
@@@ -83,23 -83,22 +83,22 @@@ static struct re_registers search_regs
     Qnil if no searching has been done yet.  */
  static Lisp_Object last_thing_searched;
  
- /* error condition signaled when regexp compile_pattern fails */
+ /* Error condition signaled when regexp compile_pattern fails.  */
  static Lisp_Object Qinvalid_regexp;
  
- /* Error condition used for failing searches */
+ /* 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 -271,8 +271,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 -367,10 +367,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 -467,10 +467,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 -640,9 +640,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 -958,7 +958,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 -1098,13 +1099,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
                               || CHAR_HEAD_P (cursor[1]))
                              && (CHAR_HEAD_P (cursor[0])
                                  /* Check if this is the last byte of
-                                    a translable character.  */
+                                    a translatable character.  */
                                  || (translate_prev_byte1 == cursor[-1]
                                      && (CHAR_HEAD_P (translate_prev_byte1)
                                          || (translate_prev_byte2 == cursor[-2]
              cursor += dirlen - i - direction; /* fix cursor */
              if (i + direction == 0)
                {
 -                EMACS_INT position, start, end;
 +                ptrdiff_t position, start, end;
  
                  cursor -= direction;
  
                           || CHAR_HEAD_P (ptr[1]))
                          && (CHAR_HEAD_P (ptr[0])
                              /* Check if this is the last byte of a
-                                translable character.  */
+                                translatable character.  */
                              || (translate_prev_byte1 == ptr[-1]
                                  && (CHAR_HEAD_P (translate_prev_byte1)
                                      || (translate_prev_byte2 == ptr[-2]
              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
- /* 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 nonzero, the end of the string
-    need not match a word boundary unless it ends in whitespace.  */
- static Lisp_Object
- wordify (Lisp_Object string, int lax)
+ 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 EMACS_INT i, i_byte, len, punct_count = 0, word_count = 0;
 +  register ptrdiff_t i, i_byte, len, punct_count = 0, word_count = 0;
    Lisp_Object val;
    int prev_c = 0;
    EMACS_INT adjust;
        return empty_unibyte_string;
      }
  
 -  adjust = - punct_count + 5 * (word_count - 1)
 +  adjust = word_count - 1;
 +  if (TYPE_MAXIMUM (EMACS_INT) / 5 < adjust)
 +    memory_full (SIZE_MAX);
 +  adjust = - punct_count + 5 * adjust
-     + ((lax && !whitespace_at_end) ? 2 : 4);
+     + ((!NILP (lax) && !whitespace_at_end) ? 2 : 4);
    if (STRING_MULTIBYTE (string))
 -    val = make_uninit_multibyte_string (len + adjust,
 -                                      SBYTES (string)
 -                                      + adjust);
 +    {
 +      if (INT_ADD_OVERFLOW (SBYTES (string), adjust))
 +      memory_full (SIZE_MAX);
 +      val = make_uninit_multibyte_string (len + adjust,
 +                                        SBYTES (string) + adjust);
 +    }
    else
 -    val = make_uninit_string (len + adjust);
 +    {
 +      if (INT_ADD_OVERFLOW (len, adjust))
 +      memory_full (SIZE_MAX);
 +      val = make_uninit_string (len + adjust);
 +    }
  
    o = SDATA (val);
    *o++ = '\\';
    for (i = 0, i_byte = 0; i < len; )
      {
        int c;
 -      EMACS_INT i_byte_orig = i_byte;
 +      ptrdiff_t i_byte_orig = i_byte;
  
        FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
  
        prev_c = c;
      }
  
-   if (!lax || whitespace_at_end)
+   if (NILP (lax) || whitespace_at_end)
      {
        *o++ = '\\';
        *o++ = 'b';
@@@ -2228,10 -2219,14 +2230,14 @@@ An optional second argument bounds the 
  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.  */)
+ 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 (wordify (string, 0), bound, noerror, count, -1, 1, 0);
+   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,
@@@ -2242,10 -2237,14 +2248,14 @@@ An optional second argument bounds the 
  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.  */)
+ 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 (wordify (string, 0), bound, noerror, count, 1, 1, 0);
+   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,
@@@ -2260,10 -2259,14 +2270,14 @@@ An optional second argument bounds the 
  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.  */)
+ 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 (wordify (string, 1), bound, noerror, count, -1, 1, 0);
+   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,
@@@ -2278,10 -2281,14 +2292,14 @@@ An optional second argument bounds the 
  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.  */)
+ 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 (wordify (string, 1), bound, noerror, count, 1, 1, 0);
+   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,
@@@ -2409,14 -2416,14 +2427,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++)
        {
@@@ -2887,7 -2894,7 +2905,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)
@@@ -2999,13 -3006,11 +3017,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))
              {
@@@ -3157,7 -3150,7 +3175,7 @@@ record_unwind_save_match_data (void
                         Fmatch_data (Qnil, Qnil, Qnil));
  }
  
- /* Quote a string to inactivate reg-expr chars */
+ /* Quote a string to deactivate reg-expr chars */
  
  DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
         doc: /* Return a regexp string which matches exactly STRING and nothing else.  */)
@@@ -3254,6 -3247,7 +3272,7 @@@ 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);
diff --combined src/sound.c
index 9e15caae3ead360bc93786639f2952de6d397192,4e9758d27df2568ff0a673bc3fc6c2071d33909a..af9dc98c3d3df2a85acd898dc6bad2abf81e26c3
@@@ -235,11 -235,11 +235,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;
@@@ -267,7 -267,7 +267,7 @@@ struct soun
       read from the start of a sound file.  */
    char *header;
  
-   /* Number of bytes raed from sound file.  This is always <=
+   /* Number of bytes read from sound file.  This is always <=
       MAX_SOUND_HEADER_BYTES.  */
    int header_size;
  
@@@ -291,7 -291,7 +291,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 -600,9 +600,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 -690,9 +690,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 -895,7 +895,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");
@@@ -952,7 -952,7 +952,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 -1155,13 +1155,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 -1348,7 +1348,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
index 9b4bd088046cd5bffb7e1362b852657b253827a9,b111fa1324ca01eb8af76bcc3af36c0cc8eb6cce..bd8a10204417dbad582a854ed316aa9c5ef2d63b
@@@ -296,7 -296,7 +296,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);
  }
@@@ -433,7 -433,7 +433,7 @@@ child_setup_tty (int out
  #endif /* AIX */
  
    /* We originally enabled ICANON (and set VEOF to 04), and then had
-      proces.c send additional EOF chars to flush the output when faced
+      process.c send additional EOF chars to flush the output when faced
       with long lines, but this leads to weird effects when the
       subprocess has disabled ICANON and ends up seeing those spurious
       extra EOFs.  So we don't send EOFs any more in
@@@ -1663,7 -1663,7 +1663,7 @@@ init_signals (void
        sys_siglist[SIGQUIT] = "Quit";
  # endif
  # ifdef SIGRETRACT
-       sys_siglist[SIGRETRACT] = "Need to relinguish monitor mode";
+       sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
  # endif
  # ifdef SIGSAK
        sys_siglist[SIGSAK] = "Secure attention";
@@@ -1902,8 -1902,8 +1902,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;
  
@@@ -2158,8 -2158,7 +2158,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)
@@@ -2689,10 -2688,7 +2689,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;
@@@ -2962,16 -2962,15 +2962,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;
diff --combined src/term.c
index fb3166a6e50dda11d59cf0e2594d5964c0c7ffbf,ae505f020f2a42f77c7ac08416c617ac6a27ce7c..036f5797e48e19a1226f9424cd2deddee3b26c22
@@@ -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)
      {
@@@ -3234,7 -3236,7 +3234,7 @@@ use the Bourne shell command `TERM=... 
    MultiLeft (tty) = tgetstr ("LE", address);
    MultiRight (tty) = tgetstr ("RI", address);
  
-   /* SVr4/ANSI color suppert.  If "op" isn't available, don't support
+   /* SVr4/ANSI color support.  If "op" isn't available, don't support
       color because we can't switch back to the default foreground and
       background.  */
    tty->TS_orig_pair = tgetstr ("op", address);
diff --combined src/textprop.c
index a877e2a67ae3968dbe06c45f816ae5d13fa22678,a1c7593f5685b49adc684ef088fd7560c834c0e2..1a635444b005850310f2c73cde5c27623ad45a8b
@@@ -124,7 -124,7 +124,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 -514,10 +514,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 -775,7 +775,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 -858,7 +858,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 -1140,7 +1140,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 -1345,7 +1345,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 -1438,7 +1438,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 -1524,7 +1524,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;
  \f
  DEFUN ("text-property-any", Ftext_property_any,
         Stext_property_any, 4, 5, 0,
-        doc: /* Check text from START to END for property PROPERTY equalling VALUE.
+        doc: /* Check text from START to END for property PROPERTY equaling VALUE.
  If so, return the position of the first character whose property PROPERTY
  is `eq' to VALUE.  Otherwise return nil.
  If the optional fifth argument OBJECT is a buffer (or nil, which means
@@@ -1634,7 -1634,7 +1634,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);
  
  DEFUN ("text-property-not-all", Ftext_property_not_all,
         Stext_property_not_all, 4, 5, 0,
-        doc: /* Check text from START to END for property PROPERTY not equalling VALUE.
+        doc: /* Check text from START to END for property PROPERTY not equaling VALUE.
  If so, return the position of the first character whose property PROPERTY
  is not `eq' to VALUE.  Otherwise, return nil.
  If the optional fifth argument OBJECT is a buffer (or nil, which means
@@@ -1670,7 -1670,7 +1670,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 -1780,7 +1780,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 -1877,12 +1880,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 -1960,7 +1963,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 -2014,7 +2017,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/w32fns.c
index aa4650dd7b2bf8e4b6b94abca4b40595515cf45e,822e3530bb671553a006eba5c1816410f6275783..20284108185a55e62644781c94ed76c1856bf659
@@@ -2262,7 -2262,7 +2262,7 @@@ w32_msg_pump (deferred_msg * msg_buf
                   some third party shell extensions can cause it to be used in
                   system dialogs, which causes a crash if it is not initialized.
                   This is a known bug in Windows, which was fixed long ago, but
-                  the patch for XP is not publically available until XP SP3,
+                  the patch for XP is not publicly available until XP SP3,
                   and older versions will never be patched.  */
                CoInitialize (NULL);
              w32_createwindow ((struct frame *) msg.wParam);
@@@ -2417,7 -2417,7 +2417,7 @@@ complete_deferred_msg (HWND hwnd, UINT 
    deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
  
    if (msg_buf == NULL)
-     /* Message may have been cancelled, so don't abort.  */
+     /* Message may have been canceled, so don't abort.  */
      return;
  
    msg_buf->result = result;
@@@ -2538,7 -2538,7 +2538,7 @@@ post_character_message (HWND hwnd, UIN
             the lisp thread to respond.
  
           Note that we don't want to block the input thread waiting for
-          a reponse from the lisp thread (although that would at least
+          a response from the lisp thread (although that would at least
           solve the deadlock problem above), because we want to be able
           to receive C-g to interrupt the lisp thread.  */
        cancel_all_deferred_msgs ();
@@@ -2880,7 -2880,7 +2880,7 @@@ w32_wnd_proc (HWND hwnd, UINT msg, WPAR
                      key.dwControlKeyState = modifiers;
  
                      add = w32_kbd_patch_key (&key);
-                     /* 0 means an unrecognised keycode, negative means
+                     /* 0 means an unrecognized keycode, negative means
                         dead key.  Ignore both.  */
                      while (--add >= 0)
                        {
        break;
  
      case WM_IME_CHAR:
-       /* If we can't get the IME result as unicode, use default processing,
+       /* If we can't get the IME result as Unicode, use default processing,
           which will at least allow characters decodable in the system locale
           get through.  */
        if (!get_composition_string_fn)
        if (w32_system_caret_hwnd == NULL)
        {
          /* Use the default caret width, and avoid changing it
-            unneccesarily, as it confuses screen reader software.  */
+            unnecessarily, as it confuses screen reader software.  */
          w32_system_caret_hwnd = hwnd;
          CreateCaret (hwnd, NULL, 0,
                       w32_system_caret_height);
          flags |= TPM_RIGHTBUTTON;
  
        /* Remember we did a SetCapture on the initial mouse down event,
-          so for safety, we make sure the capture is cancelled now.  */
+          so for safety, we make sure the capture is canceled now.  */
        ReleaseCapture ();
        button_state = 0;
  
@@@ -4065,7 -4065,7 +4065,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;
@@@ -4951,7 -4951,7 +4951,7 @@@ If TYPE is nil or omitted, get the prop
  Otherwise TYPE is the name of the atom that denotes the type expected.
  If SOURCE is non-nil, get the property on that window instead of from
  FRAME.  The number 0 denotes the root window.
- If DELETE_P is non-nil, delete the property after retreiving it.
+ If DELETE_P is non-nil, delete the property after retrieving it.
  If VECTOR_RET_P is non-nil, don't return a string but a vector of values.
  
  Value is nil if FRAME hasn't a property with name PROP or if PROP has
@@@ -5011,7 -5011,8 +5011,8 @@@ 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 houglass timer has been started or hourglass is shown.  */
+ /* 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. */
  
@@@ -5177,7 -5178,7 +5178,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;
@@@ -5526,7 -5527,7 +5527,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);
  
@@@ -5805,7 -5806,7 +5806,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;
  
@@@ -5927,7 -5928,7 +5928,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];
  
        file = DECODE_FILE (build_string (filename));
        }
-     /* User cancelled the dialog without making a selection.  */
+     /* User canceled the dialog without making a selection.  */
      else if (!CommDlgExtendedError ())
        file = Qnil;
      /* An error occurred, fallback on reading from the mini-buffer.  */
diff --combined src/w32menu.c
index 93194b68018b7208fefec523a0e2be7708599679,9b2d014cd58abfa75cb692933930b44be274bcd5..369b75877e87232f90ff3306545a61ebc10f4118
@@@ -381,7 -381,7 +381,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
@@@ -1219,7 -1219,7 +1219,7 @@@ simple_dialog_show (FRAME_PTR f, Lisp_O
       is_simple_dialog, we don't need to worry about checking contents
       to see what type of dialog to use.  */
  
-   /* Use unicode if possible, so any language can be displayed.  */
+   /* Use Unicode if possible, so any language can be displayed.  */
    if (unicode_message_box)
      {
        WCHAR *text, *title;
@@@ -1476,7 -1476,7 +1476,7 @@@ add_menu_item (HMENU menu, widget_valu
                                          utf16_string);
        if (!return_value)
        {
-         /* On W9x/ME, unicode menus are not supported, though AppendMenuW
+         /* On W9x/ME, Unicode menus are not supported, though AppendMenuW
             apparently does exist at least in some cases and appears to be
             stubbed out to do nothing.  out_string is UTF-8, but since
             our standard menus are in English and this is only going to
            AppendMenu (menu, fuFlags,
                        item != NULL ? (UINT) item: (UINT) wv->call_data,
                        out_string);
-         /* Don't use unicode menus in future.  */
+         /* Don't use Unicode menus in future.  */
          unicode_append_menu = NULL;
        }
  
diff --combined src/window.c
index 60d17c74de37275def91434beea6489f7e766d41,b908749ea4a92ff0dfc41a8fbc43a09b71fb3a28..3b9705444f9ba477a5aa61624b0570403005024d
@@@ -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)
@@@ -465,10 -465,8 +465,8 @@@ Return nil if WINDOW has no previous si
    return decode_any_window (window)->prev;
  }
  
- DEFUN ("window-combination-limit", Fwindow_combination_limit, Swindow_combination_limit, 0, 1, 0,
+ DEFUN ("window-combination-limit", Fwindow_combination_limit, Swindow_combination_limit, 1, 1, 0,
         doc: /* Return combination limit of window WINDOW.
- If WINDOW is omitted or nil, it defaults to the selected window.
  If the return value is nil, child windows of WINDOW can be recombined with
  WINDOW's siblings.  A return value of t means that child windows of
  WINDOW are never \(re-)combined with WINDOW's siblings.  */)
  }
  
  DEFUN ("set-window-combination-limit", Fset_window_combination_limit, Sset_window_combination_limit, 2, 2, 0,
-        doc: /* Set combination limit of window WINDOW to STATUS; return STATUS.
- If WINDOW is omitted or nil, it defaults to the selected window.
- If STATUS is nil, child windows of WINDOW can be recombined with
- WINDOW's siblings.  STATUS t means that child windows of WINDOW are
+        doc: /* Set combination limit of window WINDOW to LIMIT; return LIMIT.
+ If LIMIT is nil, child windows of WINDOW can be recombined with
+ WINDOW's siblings.  LIMIT t means that child windows of WINDOW are
  never \(re-)combined with WINDOW's siblings.  Other values are reserved
  for future use.  */)
-   (Lisp_Object window, Lisp_Object status)
+   (Lisp_Object window, Lisp_Object limit)
  {
    register struct window *w = decode_any_window (window);
  
-   w->combination_limit = status;
+   w->combination_limit = limit;
  
    return w->combination_limit;
  }
@@@ -684,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)
@@@ -1056,6 -1052,7 +1052,7 @@@ window_relative_x_coord (struct window 
  DEFUN ("coordinates-in-window-p", Fcoordinates_in_window_p,
         Scoordinates_in_window_p, 2, 2, 0,
         doc: /* Return non-nil if COORDINATES are in WINDOW.
+ WINDOW must be a live window.
  COORDINATES is a cons of the form (X . Y), X and Y being distances
  measured in characters from the upper-left corner of the frame.
  \(0 . 0) denotes the character in the upper left corner of the
@@@ -1077,7 -1074,7 +1074,7 @@@ If they are in the windows's left or ri
    int x, y;
    Lisp_Object lx, ly;
  
-   CHECK_WINDOW (window);
+   CHECK_LIVE_WINDOW (window);
    w = XWINDOW (window);
    f = XFRAME (w->frame);
    CHECK_CONS (coordinates);
@@@ -1498,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);
  
@@@ -2186,7 -2182,7 +2183,7 @@@ next_window (Lisp_Object window, Lisp_O
  
  
  DEFUN ("next-window", Fnext_window, Snext_window, 0, 3, 0,
-        doc: /* Return window following WINDOW in cyclic ordering of windows.
+        doc: /* Return live window after WINDOW in the cyclic ordering of windows.
  WINDOW must be a live window and defaults to the selected one.  The
  optional arguments MINIBUF and ALL-FRAMES specify the set of windows to
  consider.
@@@ -2225,7 -2221,7 +2222,7 @@@ windows, eventually ending up back at t
  
  
  DEFUN ("previous-window", Fprevious_window, Sprevious_window, 0, 3, 0,
-        doc: /* Return window preceding WINDOW in cyclic ordering of windows.
+        doc: /* Return live window before WINDOW in the cyclic ordering of windows.
  WINDOW must be a live window and defaults to the selected one.  The
  optional arguments MINIBUF and ALL-FRAMES specify the set of windows to
  consider.
@@@ -2567,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;
  
    w = decode_any_window (window);
@@@ -2893,7 -2889,7 +2890,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,
@@@ -2959,7 -2955,7 +2956,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;
@@@ -3092,7 -3088,7 +3089,7 @@@ This function runs `window-scroll-funct
            error ("Window is dedicated to `%s'", SDATA (BVAR (XBUFFER (tem), name)));
          else
            /* WINDOW is weakly dedicated to its buffer, reset
-              dedicatedness.  */
+              dedication.  */
            w->dedicated = Qnil;
  
          call1 (Qrecord_window_buffer, window);
@@@ -3190,7 -3186,7 +3187,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);
@@@ -4170,10 -4166,9 +4167,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.  */
@@@ -4269,7 -4264,7 +4266,7 @@@ window_scroll_pixel_based (Lisp_Object 
              /* 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
@@@ -4559,12 -4554,12 +4556,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);
  
@@@ -4828,7 -4823,7 +4825,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);
@@@ -4870,7 -4865,7 +4867,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))
@@@ -4899,7 -4894,7 +4896,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))
@@@ -5010,7 -5005,7 +5007,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 ();
@@@ -5359,7 -5354,7 +5356,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);
  
@@@ -5772,20 -5767,37 +5769,37 @@@ get_leaf_windows (struct window *w, str
  
  
  /* Return a pointer to the glyph W's physical cursor is on.  Value is
-    null if W's current matrix is invalid, so that no meaningfull glyph
+    null if W's current matrix is invalid, so that no meaningful glyph
     can be returned.  */
  struct glyph *
  get_phys_cursor_glyph (struct window *w)
  {
    struct glyph_row *row;
    struct glyph *glyph;
+   int hpos = w->phys_cursor.hpos;
+   if (!(w->phys_cursor.vpos >= 0
+       && w->phys_cursor.vpos < w->current_matrix->nrows))
+     return NULL;
+   row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
+   if (!row->enabled_p)
+     return NULL;
+   if (XINT (w->hscroll))
+     {
+       /* When the window is hscrolled, cursor hpos can legitimately be
+        out of bounds, but we draw the cursor at the corresponding
+        window margin in that case.  */
+       if (!row->reversed_p && hpos < 0)
+       hpos = 0;
+       if (row->reversed_p && hpos >= row->used[TEXT_AREA])
+       hpos = row->used[TEXT_AREA] - 1;
+     }
  
-   if (w->phys_cursor.vpos >= 0
-       && w->phys_cursor.vpos < w->current_matrix->nrows
-       && (row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos),
-         row->enabled_p)
-       && row->used[TEXT_AREA] > w->phys_cursor.hpos)
-     glyph = row->glyphs[TEXT_AREA] + w->phys_cursor.hpos;
+   if (row->used[TEXT_AREA] > hpos
+       && 0 <= hpos)
+     glyph = row->glyphs[TEXT_AREA] + hpos;
    else
      glyph = NULL;
  
@@@ -6074,7 -6086,7 +6088,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;
@@@ -6287,7 -6299,7 +6301,7 @@@ freeze_window_starts (struct frame *f, 
     ignore_positions non-zero means ignore non-matching scroll positions
     and the like.
  
-    This ignores a couple of things like the dedicatedness status of
+    This ignores a couple of things like the dedication status of
     window, combination_limit and the like.  This might have to be
     fixed.  */
  
@@@ -6521,10 -6533,10 +6535,10 @@@ sibling
  
  Other values are reserved for future use.
  
- The value of this variable is also assigned to the combination-limit
- status of the new parent window.  The combination-limit status of a
- window can be retrieved via the function `window-combination-limit' and
altered by the function `set-window-combination-limit'.  */);
+ The value of this variable is also assigned to the combination limit of
+ the new parent window.  The combination limit of a window can be
+ retrieved via the function `window-combination-limit' and altered by the
+ function `set-window-combination-limit'.  */);
    Vwindow_combination_limit = Qnil;
  
    defsubr (&Sselected_window);
diff --combined src/xdisp.c
index 3883a753940e0ea66ee802c0d6d06193ab811e38,41d393a65a75f4222935a309a48314d41e03bce7..4eef9e05231b814da7cf5ab77a0d2c30687fb772
@@@ -748,7 -748,7 +748,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 -795,33 +795,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,10 -834,10 +834,10 @@@ 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 pop_it (struct it *);
  static void sync_frame_with_window_matrix_rows (struct window *);
@@@ -850,7 -850,7 +850,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 -862,14 +862,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 -884,14 +884,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 -901,20 +901,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 -1246,7 +1246,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;
                     position is CHARPOS.  For the contingency that we
                     didn't, and stopped at the first newline from the
                     display string, move back over the glyphs
-                    prfoduced from the string, until we find the
+                    produced from the string, until we find the
                     rightmost glyph not from the string.  */
                  if (IT_CHARPOS (it3) != charpos && EQ (it3.object, string))
                    {
@@@ -1550,7 -1550,7 +1550,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;
  
@@@ -1915,7 -1915,7 +1915,7 @@@ get_glyph_string_clip_rects (struct gly
         environments with anti-aliased text: if the same text is
         drawn onto the same place multiple times, it gets thicker.
         If the overlap we are processing is for the erased cursor, we
-        take the intersection with the rectagle of the cursor.  */
+        take the intersection with the rectangle of the cursor.  */
        if (s->for_overlaps & OVERLAPS_ERASED_CURSOR)
        {
          XRectangle rc, r_save = r;
@@@ -2346,7 -2346,7 +2346,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 -2496,7 +2496,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);
  
@@@ -2849,8 -2846,14 +2849,14 @@@ start_display (struct it *it, struct wi
                  || (new_x == it->last_visible_x
                      && FRAME_WINDOW_P (it->f))))
            {
-             if (it->current.dpvec_index >= 0
-                 || it->current.overlay_string_index >= 0)
+             if ((it->current.dpvec_index >= 0
+                  || it->current.overlay_string_index >= 0)
+                 /* If we are on a newline from a display vector or
+                    overlay string, then we are already at the end of
+                    a screen line; no need to go to the next line in
+                    that case, as this line is not really continued.
+                    (If we do go to the next line, C-e will not DTRT.)  */
+                 && it->c != '\n')
                {
                  set_iterator_to_next (it, 1);
                  move_it_in_display_line_to (it, -1, -1, 0);
@@@ -2888,7 -2891,7 +2894,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--)
            {
@@@ -3167,15 -3170,13 +3173,13 @@@ 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 nowhere else, stop at the end.  */
-   it->stop_charpos = it->end_charpos;
    if (STRINGP (it->string))
      {
        /* Strings are usually short, so don't limit the search for
         properties.  */
+       it->stop_charpos = it->end_charpos;
        object = it->string;
        limit = Qnil;
        charpos = IT_STRING_CHARPOS (*it);
      }
    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->end_charpos > ZV)
+       it->end_charpos = ZV;
+       it->stop_charpos = it->end_charpos;
        /* If next overlay change is in front of the current stop pos
         (which is IT->end_charpos), stop there.  Note: value of
         next_overlay_change is point-max if no overlay change
  
    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)))
@@@ -3474,7 -3481,7 +3484,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;
@@@ -3571,7 -3578,7 +3581,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
@@@ -3730,7 -3737,7 +3740,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
@@@ -3951,7 -3958,7 +3961,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 && newpos < ZV)
            {
 -            EMACS_INT bpos = CHAR_TO_BYTE (newpos);
 +            ptrdiff_t bpos = CHAR_TO_BYTE (newpos);
-             if (FETCH_BYTE (bpos) == '\n'
-                 || (newpos > BEGV && FETCH_BYTE (bpos - 1) == '\n'))
+             int on_newline = FETCH_BYTE (bpos) == '\n';
+             int after_newline =
+               newpos <= BEGV || FETCH_BYTE (bpos - 1) == '\n';
+             /* If the invisible text ends on a newline or on a
+                character after a newline, we can avoid the costly,
+                character by character, bidi iteration to NEWPOS, and
+                instead simply reseat the iterator there.  That's
+                because all bidi reordering information is tossed at
+                the newline.  This is a big win for modes that hide
+                complete lines, like Outline, Org, etc.  */
+             if (on_newline || after_newline)
                {
-                 /* If the invisible text ends on a newline or the
-                    character after a newline, we can avoid the
-                    costly, character by character, bidi iteration to
-                    newpos, and instead simply reseat the iterator
-                    there.  That's because all bidi reordering
-                    information is tossed at the newline.  This is a
-                    big win for modes that hide complete lines, like
-                    Outline, Org, etc.  (Implementation note: the
-                    call to reseat_1 is necessary, because it signals
-                    to the bidi iterator that it needs to reinit its
-                    internal information when the next element for
-                    display is requested.  */
                  struct text_pos tpos;
+                 bidi_dir_t pdir = it->bidi_it.paragraph_dir;
  
                  SET_TEXT_POS (tpos, newpos, bpos);
                  reseat_1 (it, tpos, 0);
+                 /* If we reseat on a newline, we need to prep the
+                    bidi iterator for advancing to the next character
+                    after the newline, keeping the current paragraph
+                    direction (so that PRODUCE_GLYPHS does TRT wrt
+                    prepending/appending glyphs to a glyph row).  */
+                 if (on_newline)
+                   {
+                     it->bidi_it.first_elt = 0;
+                     it->bidi_it.paragraph_dir = pdir;
+                     it->bidi_it.ch = '\n';
+                     it->bidi_it.nchars = 1;
+                     it->bidi_it.ch_len = 1;
+                   }
                }
              else      /* Must use the slow method.  */
                {
                     non-base embedding level.  Therefore, we need to
                     skip invisible text using the bidi iterator,
                     starting at IT's current position, until we find
-                    ourselves outside the invisible text.  Skipping
-                    invisible text _after_ bidi iteration avoids
-                    affecting the visual order of the displayed text
-                    when invisible properties are added or
-                    removed.  */
+                    ourselves outside of the invisible text.
+                    Skipping invisible text _after_ bidi iteration
+                    avoids affecting the visual order of the
+                    displayed text when invisible properties are
+                    added or removed.  */
                  if (it->bidi_it.first_elt && it->bidi_it.charpos < ZV)
                    {
                      /* If we were `reseat'ed to a new paragraph,
@@@ -4249,7 -4267,7 +4270,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,
@@@ -4421,7 -4439,7 +4442,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);
  
  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;
@@@ -4927,7 -4945,7 +4948,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);
  
@@@ -5023,7 -5041,7 +5044,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))
      {
@@@ -5089,7 -5107,7 +5110,7 @@@ struct overlay_entr
  {
    Lisp_Object overlay;
    Lisp_Object string;
 -  int priority;
 +  EMACS_INT priority;
    int after_string_p;
  };
  
@@@ -5215,17 -5233,12 +5236,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;
@@@ -5562,8 -5575,8 +5583,8 @@@ static voi
  iterate_out_of_display_property (struct it *it)
  {
    int buffer_p = BUFFERP (it->object);
 -  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);
  
@@@ -5724,7 -5737,7 +5745,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));
@@@ -5865,8 -5878,8 +5886,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);
@@@ -6019,7 -6032,7 +6040,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);
  
@@@ -6127,7 -6140,7 +6148,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,
@@@ -6353,11 -6366,11 +6374,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
@@@ -6489,7 -6502,7 +6510,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);
@@@ -6803,7 -6818,7 +6824,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),
                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;
@@@ -7111,7 -7126,7 +7132,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);
@@@ -7146,8 -7161,8 +7167,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))
        {
@@@ -7518,10 -7533,10 +7539,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);
@@@ -7710,7 -7725,7 +7731,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.  */
@@@ -7899,7 -7914,7 +7920,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;
@@@ -8713,7 -8728,7 +8734,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);
@@@ -8905,7 -8920,7 +8926,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,
@@@ -9028,7 -9043,7 +9049,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;
  
@@@ -9077,7 -9092,7 +9098,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;
@@@ -9693,12 -9708,12 +9714,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 ();
@@@ -9874,7 -9889,7 +9895,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;
@@@ -10027,7 -10042,7 +10048,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));
@@@ -10077,8 -10092,7 +10098,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;
@@@ -10207,7 -10221,7 +10228,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;
  }
  
  
- /* Push the current message on Vmessage_stack for later restauration
+ /* Push the current message on Vmessage_stack for later restoration
     by restore_message.  Value is non-zero if the current message isn't
     empty.  This is a relatively infrequent operation, so it's not
     worth optimizing.  */
@@@ -10286,7 -10300,7 +10307,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];
  
@@@ -10556,7 -10570,7 +10577,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 ();
@@@ -10733,7 -10747,7 +10754,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);
@@@ -10778,7 -10792,7 +10799,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))
        {
@@@ -10881,7 -10895,7 +10902,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;
@@@ -10998,7 -11012,7 +11019,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);
  
@@@ -11196,7 -11210,7 +11217,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;
@@@ -11334,20 -11348,20 +11355,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));
        }
  
@@@ -11693,7 -11707,7 +11714,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);
@@@ -11881,7 -11895,7 +11902,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);
@@@ -12060,7 -12074,7 +12081,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.  */
@@@ -12241,12 -12255,12 +12262,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
@@@ -12296,7 -12310,7 +12317,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;
  
@@@ -12519,10 -12533,10 +12540,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;
  
@@@ -12573,7 -12587,7 +12594,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;
@@@ -12642,7 -12656,7 +12663,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;
                {
                  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
@@@ -13608,18 -13622,18 +13629,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 smalles 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);
        {
        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 (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,
              || (STRINGP (g1->object)
                  && (!NILP (Fget_char_property (make_number (g1->charpos),
                                                Qcursor, g1->object))
-                     /* pevious candidate is from the same display
+                     /* previous candidate is from the same display
                         string as this one, and the display string
                         came from a text property */
                      || (EQ (g1->object, glyph->object)
  
  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);
      {
        int scroll_margin_y;
  
-       /* Compute the pixel ypos of the scroll margin, then move it to
+       /* Compute the pixel ypos of the scroll margin, then move IT to
         either that ypos or PT, whichever comes first.  */
        start_display (&it, w, startp);
        scroll_margin_y = it.last_visible_y - this_scroll_margin
          if (dy > scroll_max)
            return SCROLLING_FAILED;
  
-         scroll_down_p = 1;
+         if (dy > 0)
+           scroll_down_p = 1;
        }
      }
  
@@@ -14921,7 -14936,7 +14943,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)
@@@ -14981,7 -14996,7 +15003,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
@@@ -15038,14 -15053,14 +15060,14 @@@ redisplay_window (Lisp_Object window, i
    int current_matrix_up_to_date_p = 0;
    int used_current_matrix_p = 0;
    /* This is less strict than current_matrix_up_to_date_p.
-      It indictes that the buffer contents and narrowing are unchanged.  */
+      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);
-       int scrolling_up;
        Lisp_Object aggressive;
+       int scrolling_up;
  
        /* If there is a scroll margin at the top of the window, find
         its character position.  */
              pt_offset = float_amount * WINDOW_BOX_TEXT_HEIGHT (w);
              if (pt_offset == 0 && float_amount > 0)
                pt_offset = 1;
-             if (pt_offset)
+             if (pt_offset && margin > 0)
                margin -= 1;
            }
          /* Compute how much to move the window start backward from
          goto recenter;
        }
  
+       /* Users who set scroll-conservatively to a large number want
+        point just above/below the scroll margin.  If we ended up
+        with point's row partially visible, move the window start to
+        make that row fully visible and out of the margin.  */
+       if (scroll_conservatively > SCROLL_LIMIT)
+       {
+         int margin =
+           scroll_margin > 0
+           ? min (scroll_margin, WINDOW_TOTAL_LINES (w) / 4)
+           : 0;
+         int move_down = w->cursor.vpos >= WINDOW_TOTAL_LINES (w) / 2;
+         move_it_by_lines (&it, move_down ? margin + 1 : -(margin + 1));
+         clear_glyph_matrix (w->desired_matrix);
+         if (1 == try_window (window, it.current.pos,
+                              TRY_WINDOW_CHECK_MARGINS))
+           goto done;
+       }
        /* If centering point failed to make the whole line visible,
         put point at the top instead.  That has to make the whole line
         visible, if it can be done.  */
@@@ -16434,7 -16468,7 +16475,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 *);
@@@ -16482,7 -16516,7 +16523,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);
  
@@@ -16649,12 -16683,12 +16690,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.  */
@@@ -16768,14 -16802,14 +16809,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
    last_unchanged_at_beg_row = find_last_unchanged_at_beg_row (w);
    if (last_unchanged_at_beg_row)
      {
-       /* Avoid starting to display in the moddle of a character, a TAB
+       /* Avoid starting to display in the middle of a character, a TAB
         for instance.  This is easier than to set up the iterator
         exactly, and it's not a frequent case, so the additional
         effort wouldn't really pay off.  */
@@@ -17646,7 -17680,7 +17687,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",
@@@ -17720,7 -17754,7 +17761,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;
  }
  
@@@ -17743,7 -17777,7 +17784,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;
  }
  
@@@ -17765,13 -17799,13 +17806,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;
  }
  
@@@ -17957,9 -17991,6 +17998,6 @@@ insert_left_trunc_glyphs (struct it *it
  }
  
  /* Compute the hash code for ROW.  */
- #if !XASSERTS
- static
- #endif
  unsigned
  row_hash (struct glyph_row *row)
  {
@@@ -18294,9 -18325,9 +18332,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
@@@ -18613,8 -18644,8 +18651,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.  */
@@@ -18781,11 -18812,11 +18819,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);
  #define RECORD_MAX_MIN_POS(IT)                                        \
    do                                                          \
      {                                                         \
-       int composition_p = (IT)->what == IT_COMPOSITION;               \
+       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)                              \
@@@ -19503,8 -19535,8 +19542,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 ();
  
@@@ -19792,7 -19824,7 +19831,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.
@@@ -19928,7 -19960,7 +19967,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;
  
@@@ -20375,7 -20407,7 +20414,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)
@@@ -20476,7 -20508,7 +20515,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;
  
@@@ -20606,11 -20638,11 +20645,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;
@@@ -20890,7 -20922,7 +20929,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
@@@ -22858,7 -22890,7 +22897,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;
@@@ -24322,7 -24354,7 +24361,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')
  void
  x_write_glyphs (struct glyph *start, int len)
  {
-   int x, hpos;
+   int x, hpos, chpos = updated_window->phys_cursor.hpos;
  
    xassert (updated_window && updated_row);
+   /* When the window is hscrolled, cursor hpos can legitimately be out
+      of bounds, but we draw the cursor at the corresponding window
+      margin in that case.  */
+   if (!updated_row->reversed_p && chpos < 0)
+     chpos = 0;
+   if (updated_row->reversed_p && chpos >= updated_row->used[TEXT_AREA])
+     chpos = updated_row->used[TEXT_AREA] - 1;
    BLOCK_INPUT;
  
    /* Write glyphs.  */
    if (updated_area == TEXT_AREA
        && updated_window->phys_cursor_on_p
        && updated_window->phys_cursor.vpos == output_cursor.vpos
-       && updated_window->phys_cursor.hpos >= hpos
-       && updated_window->phys_cursor.hpos < hpos + len)
+       && chpos >= hpos
+       && chpos < hpos + len)
      updated_window->phys_cursor_on_p = 0;
  
    UNBLOCK_INPUT;
@@@ -24722,7 -24762,7 +24769,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;
@@@ -24869,7 -24909,8 +24916,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;
@@@ -25207,8 -25249,17 +25254,17 @@@ draw_phys_cursor_glyph (struct window *
      {
        int on_p = w->phys_cursor_on_p;
        int x1;
-       x1 = draw_glyphs (w, w->phys_cursor.x, row, TEXT_AREA,
-                       w->phys_cursor.hpos, w->phys_cursor.hpos + 1,
+       int hpos = w->phys_cursor.hpos;
+       /* When the window is hscrolled, cursor hpos can legitimately be
+        out of bounds, but we draw the cursor at the corresponding
+        window margin in that case.  */
+       if (!row->reversed_p && hpos < 0)
+       hpos = 0;
+       if (row->reversed_p && hpos >= row->used[TEXT_AREA])
+       hpos = row->used[TEXT_AREA] - 1;
+       x1 = draw_glyphs (w, w->phys_cursor.x, row, TEXT_AREA, hpos, hpos + 1,
                        hl, 0);
        w->phys_cursor_on_p = on_p;
  
@@@ -25296,6 -25347,14 +25352,14 @@@ erase_phys_cursor (struct window *w
         : (w->phys_cursor.hpos >= cursor_row->used[TEXT_AREA])))
      goto mark_cursor_off;
  
+   /* When the window is hscrolled, cursor hpos can legitimately be out
+      of bounds, but we draw the cursor at the corresponding window
+      margin in that case.  */
+   if (!cursor_row->reversed_p && hpos < 0)
+     hpos = 0;
+   if (cursor_row->reversed_p && hpos >= cursor_row->used[TEXT_AREA])
+     hpos = cursor_row->used[TEXT_AREA] - 1;
    /* If the cursor is in the mouse face area, redisplay that when
       we clear the cursor.  */
    if (! NILP (hlinfo->mouse_face_window)
@@@ -25439,8 -25498,26 +25503,26 @@@ update_window_cursor (struct window *w
       of being deleted.  */
    if (w->current_matrix)
      {
+       int hpos = w->phys_cursor.hpos;
+       int vpos = w->phys_cursor.vpos;
+       struct glyph_row *row;
+       if (vpos >= w->current_matrix->nrows
+         || hpos >= w->current_matrix->matrix_w)
+       return;
+       row = MATRIX_ROW (w->current_matrix, vpos);
+       /* When the window is hscrolled, cursor hpos can legitimately be
+        out of bounds, but we draw the cursor at the corresponding
+        window margin in that case.  */
+       if (!row->reversed_p && hpos < 0)
+       hpos = 0;
+       if (row->reversed_p && hpos >= row->used[TEXT_AREA])
+       hpos = row->used[TEXT_AREA] - 1;
        BLOCK_INPUT;
-       display_and_set_cursor (w, on, w->phys_cursor.hpos, w->phys_cursor.vpos,
+       display_and_set_cursor (w, on, hpos, vpos,
                              w->phys_cursor.x, w->phys_cursor.y);
        UNBLOCK_INPUT;
      }
@@@ -25610,9 -25687,18 +25692,18 @@@ show_mouse_face (Mouse_HLInfo *hlinfo, 
        if (FRAME_WINDOW_P (f)
          && phys_cursor_on_p && !w->phys_cursor_on_p)
        {
+         int hpos = w->phys_cursor.hpos;
+         /* When the window is hscrolled, cursor hpos can legitimately be
+            out of bounds, but we draw the cursor at the corresponding
+            window margin in that case.  */
+         if (!row->reversed_p && hpos < 0)
+           hpos = 0;
+         if (row->reversed_p && hpos >= row->used[TEXT_AREA])
+           hpos = row->used[TEXT_AREA] - 1;
          BLOCK_INPUT;
-         display_and_set_cursor (w, 1,
-                                 w->phys_cursor.hpos, w->phys_cursor.vpos,
+         display_and_set_cursor (w, 1, hpos, w->phys_cursor.vpos,
                                  w->phys_cursor.x, w->phys_cursor.y);
          UNBLOCK_INPUT;
        }
@@@ -25711,7 -25797,19 +25802,19 @@@ coords_in_mouse_face_p (struct window *
  int
  cursor_in_mouse_face_p (struct window *w)
  {
-   return coords_in_mouse_face_p (w, w->phys_cursor.hpos, w->phys_cursor.vpos);
+   int hpos = w->phys_cursor.hpos;
+   int vpos = w->phys_cursor.vpos;
+   struct glyph_row *row = MATRIX_ROW (w->current_matrix, vpos);
+   /* When the window is hscrolled, cursor hpos can legitimately be out
+      of bounds, but we draw the cursor at the corresponding window
+      margin in that case.  */
+   if (!row->reversed_p && hpos < 0)
+     hpos = 0;
+   if (row->reversed_p && hpos >= row->used[TEXT_AREA])
+     hpos = row->used[TEXT_AREA] - 1;
+   return coords_in_mouse_face_p (w, hpos, vpos);
  }
  
  
     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,
                     struct glyph_row **start, struct glyph_row **end)
  {
    struct glyph_row *first = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
  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;
@@@ -26422,8 -26520,8 +26525,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;
@@@ -26501,9 -26599,7 +26604,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));
  }
  
  
@@@ -26562,7 -26658,7 +26665,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;
  
@@@ -26932,14 -27028,14 +27035,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);
@@@ -28579,7 -28675,8 +28682,8 @@@ init_xdisp (void
  
  /* Platform-independent portion of hourglass implementation. */
  
- /* Return non-zero if houglass timer has been started or hourglass is shown.  */
+ /* Return non-zero if hourglass timer has been started or hourglass is
+    shown.  */
  int
  hourglass_started (void)
  {
@@@ -28592,16 -28689,23 +28696,16 @@@ 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/xfaces.c
index 2dc46b2fa026a83de3d2e8bffe48603104554600,7e3ce4103d9729549c4b4d5d557cff5242080fbf..5a7b39fcca526bc6ac22b454a2f717c5f9cb4eb1
@@@ -66,7 -66,7 +66,7 @@@ along with GNU Emacs.  If not, see <htt
     attributes (1st thru 5th) are updated from the spec.
  
     On the other hand, if one of the other font-related attributes are
-    specified, the correspoinding specs in this attribute is set to nil.
+    specified, the corresponding specs in this attribute is set to nil.
  
     15. A face name or list of face names from which to inherit attributes.
  
@@@ -922,7 -922,7 +922,7 @@@ the pixmap.  Bits are stored row by row
    else if (CONSP (object))
      {
        /* Otherwise OBJECT must be (WIDTH HEIGHT DATA), WIDTH and
 -       HEIGHT must be integers > 0, and DATA must be string large
 +       HEIGHT must be ints > 0, and DATA must be string large
         enough to hold a bitmap of the specified size.  */
        Lisp_Object width, height, data;
  
        }
  
        if (STRINGP (data)
 -        && INTEGERP (width) && 0 < XINT (width)
 -        && INTEGERP (height) && 0 < XINT (height))
 +        && RANGED_INTEGERP (1, width, INT_MAX)
 +        && RANGED_INTEGERP (1, height, INT_MAX))
        {
 -        EMACS_INT bytes_per_row = ((XINT (width) + BITS_PER_CHAR - 1)
 -                                   / BITS_PER_CHAR);
 +        int bytes_per_row = ((XINT (width) + BITS_PER_CHAR - 1)
 +                             / BITS_PER_CHAR);
          if (XINT (height) <= SBYTES (data) / bytes_per_row)
            pixmap_p = 1;
        }
@@@ -1223,7 -1223,7 +1223,7 @@@ face_color_gray_p (struct frame *f, con
    int gray_p;
  
    if (defined_color (f, color_name, &color, 0))
-     gray_p = (/* Any color sufficiently close to black counts as grey.  */
+     gray_p = (/* Any color sufficiently close to black counts as gray.  */
              (color.red < 5000 && color.green < 5000 && color.blue < 5000)
              ||
              ((eabs (color.red - color.green)
@@@ -1604,9 -1604,7 +1604,9 @@@ compare_fonts_by_sort_order (const voi
        else
        {
          if (INTEGERP (val1))
 -          result = INTEGERP (val2) ? XINT (val1) - XINT (val2) : -1;
 +          result = (INTEGERP (val2) && XINT (val1) >= XINT (val2)
 +                    ? XINT (val1) > XINT (val2)
 +                    : -1);
          else
            result = INTEGERP (val2) ? 1 : 0;
        }
@@@ -1635,10 -1633,8 +1635,10 @@@ the face font sort order.  */
    (Lisp_Object family, Lisp_Object frame)
  {
    Lisp_Object font_spec, list, *drivers, vec;
 -  int i, nfonts, ndrivers;
 +  ptrdiff_t i, nfonts;
 +  EMACS_INT ndrivers;
    Lisp_Object result;
 +  USE_SAFE_ALLOCA;
  
    if (NILP (frame))
      frame = selected_frame;
    font_props_for_sorting[i++] = FONT_REGISTRY_INDEX;
  
    ndrivers = XINT (Flength (list));
 -  drivers  = alloca (sizeof (Lisp_Object) * ndrivers);
 +  SAFE_ALLOCA_LISP (drivers, ndrivers);
    for (i = 0; i < ndrivers; i++, list = XCDR (list))
      drivers[i] = XCAR (list);
    vec = Fvconcat (ndrivers, drivers);
        result = Fcons (v, result);
      }
  
 +  SAFE_FREE ();
    return result;
  }
  
@@@ -2268,7 -2263,7 +2268,7 @@@ merge_face_heights (Lisp_Object from, L
      {
        if (INTEGERP (to))
        /* relative X absolute => absolute */
 -      result = make_number ((EMACS_INT)(XFLOAT_DATA (from) * XINT (to)));
 +      result = make_number (XFLOAT_DATA (from) * XINT (to));
        else if (FLOATP (to))
        /* relative X relative => relative */
        result = make_float (XFLOAT_DATA (from) * XFLOAT_DATA (to));
@@@ -2688,7 -2683,8 +2688,7 @@@ Value is a vector of face attributes.  
         property `face' of the Lisp face name.  */
        if (next_lface_id == lface_id_to_name_size)
        lface_id_to_name =
 -        xpalloc (lface_id_to_name, &lface_id_to_name_size, 1,
 -                 min (INT_MAX, MOST_POSITIVE_FIXNUM),
 +        xpalloc (lface_id_to_name, &lface_id_to_name_size, 1, MAX_FACE_ID,
                   sizeof *lface_id_to_name);
  
        lface_id_to_name[next_lface_id] = face;
@@@ -5281,7 -5277,7 +5281,7 @@@ static in
  realize_basic_faces (struct frame *f)
  {
    int success_p = 0;
 -  int count = SPECPDL_INDEX ();
 +  ptrdiff_t count = SPECPDL_INDEX ();
  
    /* Block input here so that we won't be surprised by an X expose
       event, for instance, without having the faces set up.  */
@@@ -5964,9 -5960,9 +5964,9 @@@ compute_char_face (struct frame *f, in
     The face returned is suitable for displaying ASCII characters.  */
  
  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,
 +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)
  {
    struct frame *f = XFRAME (w->frame);
    ptrdiff_t i, noverlays;
    Lisp_Object *overlay_vec;
    Lisp_Object frame;
 -  EMACS_INT endpos;
 +  ptrdiff_t endpos;
    Lisp_Object propname = mouse ? Qmouse_face : Qface;
    Lisp_Object limit1, end;
    struct face *default_face;
  
    /* Look at properties from overlays.  */
    {
 -    EMACS_INT next_overlay;
 +    ptrdiff_t next_overlay;
  
      GET_OVERLAYS_AT (pos, overlay_vec, noverlays, &next_overlay, 0);
      if (next_overlay < endpos)
     simply disregards the `face' properties of all overlays.  */
  
  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,
 +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)
  {
    struct frame *f = XFRAME (w->frame);
  
  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 base_face_id,
 +                       ptrdiff_t pos, ptrdiff_t bufpos,
 +                       ptrdiff_t region_beg, ptrdiff_t region_end,
 +                       ptrdiff_t *endptr, enum face_id base_face_id,
                         int mouse_p)
  {
    Lisp_Object prop, position, end, limit;
  */
  
  int
 -merge_faces (struct frame *f, Lisp_Object face_name, EMACS_INT face_id,
 +merge_faces (struct frame *f, Lisp_Object face_name, int face_id,
             int base_face_id)
  {
    Lisp_Object attrs[LFACE_VECTOR_SIZE];
diff --combined src/xfns.c
index 88c70a9b41000fb104a76c9d89a4d11236bb8671,95154395e9ccde303a610f9cf793c2d16791268b..9bbaea3758350d4d730bc440da2d34fa236e3496
@@@ -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;
@@@ -2787,8 -2787,8 +2787,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");
@@@ -2962,7 -2962,7 +2962,7 @@@ x_default_font_parameter (struct frame 
  
    if (NILP (font_param))
      {
-       /* System font should take precedendce over X resources.  We suggest this
+       /* System font should take precedence over X resources.  We suggest this
           regardless of font-use-system-font because .emacs may not have been
           read yet.  */
        const char *system_font = xsettings_get_system_font ();
@@@ -3073,7 -3073,7 +3073,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;
       to get the color reference counts right, so initialize them!  */
    {
      Lisp_Object black;
-     struct gcpro inner_gcpro1;
+     struct gcpro gcpro1;
  
      /* Function x_decode_color can signal an error.  Make
         sure to initialize color slots so that we won't try
      f->output_data.x->mouse_pixel = -1;
  
      black = build_string ("black");
-     GCPRO1_VAR (black, inner_gcpro);
+     GCPRO1 (black);
      FRAME_FOREGROUND_PIXEL (f)
        = x_decode_color (f, black, BLACK_PIX_DEFAULT (f));
      FRAME_BACKGROUND_PIXEL (f)
        = x_decode_color (f, black, BLACK_PIX_DEFAULT (f));
      f->output_data.x->mouse_pixel
        = x_decode_color (f, black, BLACK_PIX_DEFAULT (f));
-     UNGCPRO_VAR (inner_gcpro);
+     UNGCPRO;
    }
  
    /* Specify the parent under which to make this X window.  */
@@@ -4193,11 -4193,11 +4193,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))
@@@ -4286,7 -4286,7 +4286,7 @@@ If TYPE is nil or omitted, get the prop
  Otherwise TYPE is the name of the atom that denotes the type expected.
  If SOURCE is non-nil, get the property on that window instead of from
  FRAME.  The number 0 denotes the root window.
- If DELETE_P is non-nil, delete the property after retreiving it.
+ If DELETE_P is non-nil, delete the property after retrieving it.
  If VECTOR_RET_P is non-nil, don't return a string but a vector of values.
  
  Value is nil if FRAME hasn't a property with name PROP or if PROP has
@@@ -4555,7 -4555,7 +4555,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;
       to get the color reference counts right, so initialize them!  */
    {
      Lisp_Object black;
-     struct gcpro inner_gcpro1;
+     struct gcpro gcpro1;
  
      /* Function x_decode_color can signal an error.  Make
         sure to initialize color slots so that we won't try
      f->output_data.x->mouse_pixel = -1;
  
      black = build_string ("black");
-     GCPRO1_VAR (black, inner_gcpro);
+     GCPRO1 (black);
      FRAME_FOREGROUND_PIXEL (f)
        = x_decode_color (f, black, BLACK_PIX_DEFAULT (f));
      FRAME_BACKGROUND_PIXEL (f)
        = x_decode_color (f, black, BLACK_PIX_DEFAULT (f));
      f->output_data.x->mouse_pixel
        = x_decode_color (f, black, BLACK_PIX_DEFAULT (f));
-     UNGCPRO_VAR (inner_gcpro);
+     UNGCPRO;
    }
  
    /* Set the name; the functions to which we pass f expect the name to
@@@ -4952,7 -4952,7 +4952,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);
@@@ -5209,7 -5211,7 +5209,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;
  
@@@ -5351,7 -5353,7 +5351,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 ();
@@@ -5520,7 -5522,7 +5520,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;
  
@@@ -5583,7 -5585,7 +5583,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 ();
  
@@@ -5912,7 -5914,7 +5912,7 @@@ the tool bar buttons.  */)
    x_gtk_whole_detached_tool_bar = 0;
  
    DEFVAR_BOOL ("x-gtk-use-system-tooltips", x_gtk_use_system_tooltips,
-     doc: /* *If non-nil with a Gtk+ built Emacs, the Gtk+ toolip is used.
+     doc: /* *If non-nil with a Gtk+ built Emacs, the Gtk+ tooltip is used.
  Otherwise use Emacs own tooltip implementation.
  When using Gtk+ tooltips, the tooltip face is not used.  */);
    x_gtk_use_system_tooltips = 1;
diff --combined src/xmenu.c
index d73051be6dee6bfe56f3b39eb319d93ecfe5426c,4b7bbfd73dcc429ad2d76a32687c13ec1bdf26f1..b766f142e2d8c096e5570f73c22a63f25dfbbd74
@@@ -315,7 -315,7 +315,7 @@@ for instance using the window manager, 
      Lisp_Object title;
      const char *error_name;
      Lisp_Object selection;
 -    int specpdl_count = SPECPDL_INDEX ();
 +    ptrdiff_t specpdl_count = SPECPDL_INDEX ();
  
      /* Decode the dialog items from what was specified.  */
      title = Fcar (contents);
@@@ -968,7 -968,7 +968,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
@@@ -1304,7 -1304,7 +1304,7 @@@ free_frame_menubar (FRAME_PTR f
  #ifdef USE_MOTIF
        /* Removing the menu bar magically changes the shell widget's x
         and y position of (0, 0) which, when the menu bar is turned
-        on again, leads to pull-down menuss appearing in strange
+        on again, leads to pull-down menus appearing in strange
         positions near the upper-left corner of the display.  This
         happens only with some window managers like twm and ctwm,
         but not with other like Motif's mwm or kwm, because the
@@@ -1434,7 -1434,7 +1434,7 @@@ create_and_show_popup_menu (FRAME_PTR f
    GtkWidget *menu;
    GtkMenuPositionFunc pos_func = 0;  /* Pop up at pointer.  */
    struct next_popup_x_y popup_x_y;
 -  int specpdl_count = SPECPDL_INDEX ();
 +  ptrdiff_t specpdl_count = SPECPDL_INDEX ();
  
    if (! FRAME_X_P (f))
      abort ();
@@@ -1590,7 -1590,7 +1590,7 @@@ create_and_show_popup_menu (FRAME_PTR f
  
    {
      int fact = 4 * sizeof (LWLIB_ID);
 -    int specpdl_count = SPECPDL_INDEX ();
 +    ptrdiff_t specpdl_count = SPECPDL_INDEX ();
      record_unwind_protect (pop_down_menu,
                             Fcons (make_number (menu_id >> (fact)),
                                    make_number (menu_id & ~(-1 << (fact)))));
@@@ -1629,7 -1629,7 +1629,7 @@@ xmenu_show (FRAME_PTR f, int x, int y, 
  
    int first_pane;
  
 -  int specpdl_count = SPECPDL_INDEX ();
 +  ptrdiff_t specpdl_count = SPECPDL_INDEX ();
  
    if (! FRAME_X_P (f))
      abort ();
@@@ -1926,7 -1926,7 +1926,7 @@@ create_and_show_dialog (FRAME_PTR f, wi
  
    if (menu)
      {
 -      int specpdl_count = SPECPDL_INDEX ();
 +      ptrdiff_t specpdl_count = SPECPDL_INDEX ();
        record_unwind_protect (pop_down_menu, make_save_value (menu, 0));
  
        /* Display the menu.  */
@@@ -1982,7 -1982,7 +1982,7 @@@ create_and_show_dialog (FRAME_PTR f, wi
    /* Process events that apply to the dialog box.
       Also handle timers.  */
    {
 -    int count = SPECPDL_INDEX ();
 +    ptrdiff_t count = SPECPDL_INDEX ();
      int fact = 4 * sizeof (LWLIB_ID);
  
      /* xdialog_show_unwind is responsible for popping the dialog box down.  */
@@@ -2020,7 -2020,7 +2020,7 @@@ xdialog_show (FRAME_PTR f
    /* 1 means we've seen the boundary between left-hand elts and right-hand.  */
    int boundary_seen = 0;
  
 -  int specpdl_count = SPECPDL_INDEX ();
 +  ptrdiff_t specpdl_count = SPECPDL_INDEX ();
  
    if (! FRAME_X_P (f))
      abort ();
@@@ -2285,7 -2285,7 +2285,7 @@@ xmenu_show (FRAME_PTR f, int x, int y, 
    int maxwidth;
    int dummy_int;
    unsigned int dummy_uint;
 -  int specpdl_count = SPECPDL_INDEX ();
 +  ptrdiff_t specpdl_count = SPECPDL_INDEX ();
  
    if (! FRAME_X_P (f) && ! FRAME_MSDOS_P (f))
      abort ();
diff --combined src/xselect.c
index d2ab416176c2d5d138b5c99fea22120bf4972674,f9ebdf730d43a3b7f0ca5dbed751b0f97bb7e909..099b1670e4d881529428d50f26432842172d67a0
@@@ -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);
@@@ -515,7 -516,7 +515,7 @@@ static struct selection_data *converted
  static Atom conversion_fail_tag;
  
  /* Used as an unwind-protect clause so that, if a selection-converter signals
-    an error, we tell the requester that we were unable to do what they wanted
+    an error, we tell the requestor that we were unable to do what they wanted
     before we throw to top-level or go into the debugger or whatever.  */
  
  static Lisp_Object
@@@ -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;
        bytes_remaining = cs->size;
        bytes_remaining *= format_bytes;
  
-       /* Wait for the requester to ack by deleting the property.
+       /* Wait for the requestor to ack by deleting the property.
           This can run Lisp code (process handlers) or signal.  */
        if (! had_errors)
          {
  
            if (had_errors) break;
  
-           /* Wait for the requester to ack this chunk by deleting
+           /* Wait for the requestor to ack this chunk by deleting
               the property.  This can run Lisp code or signal.  */
            TRACE1 ("Waiting for increment ACK (deletion of %s)",
                    XGetAtomName (display, cs->property));
          }
  
        /* Now write a zero-length chunk to the property to tell the
-          requester that we're done.  */
+          requestor that we're done.  */
        BLOCK_INPUT;
        if (! waiting_for_other_props_on_window (display, window))
          XSelectInput (display, window, 0L);
@@@ -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;
@@@ -1139,7 -1140,7 +1139,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 -1701,7 +1700,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;
@@@ -2600,12 -2601,13 +2600,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
index d5131c9a60cfdfa441fb2aba43be125e59a09dd5,1f995b3c1a0f01aac476ce70bf28618fb09bee46..4bc12c06b3473616fd4ba1ed9e9e5808e9147355
@@@ -2963,9 -2963,7 +2963,7 @@@ x_clear_frame (struct frame *f
       follow an explicit cursor_to.  */
    BLOCK_INPUT;
  
-   /* The following call is commented out because it does not seem to accomplish
-      anything, apart from causing flickering during window resize.  */
-   /* XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f)); */
+   XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  
    /* We have to clear the scroll bars.  If we have changed colors or
       something like that, then they should be notified.  */
@@@ -3319,7 -3317,7 +3317,7 @@@ x_scroll_run (struct window *w, struct 
      }
    else
      {
-       /* Scolling down.  Make sure we don't copy over the mode line.
+       /* Scrolling down.  Make sure we don't copy over the mode line.
         at the bottom.  */
        if (to_y + run->height > bottom_y)
        height = bottom_y - to_y;
@@@ -3690,23 -3688,24 +3688,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;
  
@@@ -4183,7 -4182,7 +4181,7 @@@ static Boolean xaw3d_arrow_scroll
  
  /* Whether the drag scrolling maintains the mouse at the top of the
     thumb.  If not, resizing the thumb needs to be done more carefully
-    to avoid jerkyness.  */
+    to avoid jerkiness.  */
  
  static Boolean xaw3d_pick_top;
  
@@@ -6115,7 -6114,8 +6113,8 @@@ handle_one_xevent (struct x_display_inf
        last_user_time = event.xproperty.time;
        f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
        if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
-         if (x_handle_net_wm_state (f, &event.xproperty) && f->iconified)
+         if (x_handle_net_wm_state (f, &event.xproperty) && f->iconified
+             && f->output_data.x->net_wm_state_hidden_seen)
            {
              /* Gnome shell does not iconify us when C-z is pressed.  It hides
                 the frame.  So if our state says we aren't hidden anymore,
              f->async_visible = 1;
              f->async_iconified = 0;
              f->output_data.x->has_been_visible = 1;
+             f->output_data.x->net_wm_state_hidden_seen = 0;
              inev.ie.kind = DEICONIFY_EVENT;
              XSETFRAME (inev.ie.frame_or_window, f);
            }
  
          /* 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
@@@ -7755,7 -7755,7 +7755,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);
@@@ -8482,7 -8482,10 +8482,10 @@@ get_current_wm_state (struct frame *f
      {
        Atom a = ((Atom*)tmp_data)[i];
        if (a == dpyinfo->Xatom_net_wm_state_hidden)
-         is_hidden = 1;
+         {
+           is_hidden = 1;
+           f->output_data.x->net_wm_state_hidden_seen = 1;
+         }
        else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
          {
            if (*size_state == FULLSCREEN_HEIGHT)
@@@ -8765,7 -8768,7 +8768,7 @@@ x_wait_for_event (struct frame *f, int 
    pending_event_wait.f = f;
    pending_event_wait.eventtype = eventtype;
  
-   /* Set timeout to 0.1 second.  Hopefully not noticable.
+   /* Set timeout to 0.1 second.  Hopefully not noticeable.
       Maybe it should be configurable.  */
    EMACS_SET_SECS_USECS (tmo, 0, 100000);
    EMACS_GET_TIME (tmo_at);
@@@ -9558,6 -9561,14 +9561,14 @@@ x_wm_set_size_hint (struct frame *f, lo
    XSizeHints size_hints;
    Window window = FRAME_OUTER_WINDOW (f);
  
+ #ifdef USE_X_TOOLKIT
+   if (f->output_data.x->widget)
+     {
+       widget_update_wm_size_hints (f->output_data.x->widget);
+       return;
+     }
+ #endif
    /* Setting PMaxSize caused various problems.  */
    size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
  
@@@ -9950,6 -9961,11 +9961,11 @@@ x_term_init (Lisp_Object display_name, 
             https://bugzilla.gnome.org/show_bug.cgi?id=563627.  */
          id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
                                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
+         /* NULL window -> events for all windows go to our function.
+            Call before gtk_init so Gtk+ event filters comes after our.  */
+         gdk_window_add_filter (NULL, event_handler_gdk, NULL);
          gtk_init (&argc, &argv2);
          g_log_remove_handler ("GLib", id);
  
  
          dpy = DEFAULT_GDK_DISPLAY ();
  
-         /* NULL window -> events for all windows go to our function */
-         gdk_window_add_filter (NULL, event_handler_gdk, NULL);
  #if GTK_MAJOR_VERSION <= 2 && GTK_MINOR_VERSION <= 90
          /* Load our own gtkrc if it exists.  */
          {
diff --combined src/xterm.h
index 92761ccee876aa8a006857678cf208ffaf59c14b,9e0e1acca92952be8e12f63e41317ea27cb12f51..1242bf64d7777df0184243d07c03d735c9c8c500
@@@ -632,6 -632,9 +632,9 @@@ struct x_outpu
       x_check_expected_move.  */
    int left_before_move;
    int top_before_move;
+   /* Non-zero if _NET_WM_STATE_HIDDEN is set for this frame.  */
+   int net_wm_state_hidden_seen;
  };
  
  #define No_Cursor (None)
@@@ -640,7 -643,7 +643,7 @@@ enu
  {
    /* Values for focus_state, used as bit mask.
       EXPLICIT means we received a FocusIn for the frame and know it has
-      the focus.  IMPLICIT means we recevied an EnterNotify and the frame
+      the focus.  IMPLICIT means we received an EnterNotify and the frame
       may have the focus if no window manager is running.
       FocusOut and LeaveNotify clears EXPLICIT/IMPLICIT. */
    FOCUS_NONE     = 0,
  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))
  
@@@ -985,7 -995,7 +988,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 *);