view src/indent.c @ 5353:38e24b8be4ea

Improve the lexical scoping in #'block, #'return-from. lisp/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el: * bytecomp.el (byte-compile-initial-macro-environment): Shadow `block', `return-from' here, we implement them differently when byte-compiling. * bytecomp.el (byte-compile-active-blocks): New. * bytecomp.el (byte-compile-block-1): New. * bytecomp.el (byte-compile-return-from-1): New. * bytecomp.el (return-from-1): New. * bytecomp.el (block-1): New. These are two aliases that exist to have their own associated byte-compile functions, which functions implement `block' and `return-from'. * cl-extra.el (cl-macroexpand-all): Fix a bug here when macros in the environment have been compiled. * cl-macs.el (block): * cl-macs.el (return): * cl-macs.el (return-from): Be more careful about lexical scope in these macros. * cl.el: * cl.el ('cl-block-wrapper): Removed. * cl.el ('cl-block-throw): Removed. These aren't needed in code generated by this XEmacs. They shouldn't be needed in code generated by XEmacs 21.4, but if it turns out the packages do need them, we can put them back. 2011-01-30 Mike Sperber <mike@xemacs.org> * font-lock.el (font-lock-fontify-pending-extents): Don't fail if `font-lock-mode' is unset, which can happen in the middle of `revert-buffer'. 2011-01-23 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete): * cl-macs.el (delq): * cl-macs.el (remove): * cl-macs.el (remq): Don't use the compiler macro if these functions were given the wrong number of arguments, as happens in lisp-tests.el. * cl-seq.el (remove, remq): Removed. I added these to subr.el, and forgot to remove them from here. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-setq, byte-compile-set): Remove kludge allowing keywords' values to be set, all the code that does that is gone. * cl-compat.el (elt-satisfies-test-p): * faces.el (set-face-parent): * faces.el (face-doc-string): * gtk-font-menu.el: * gtk-font-menu.el (gtk-reset-device-font-menus): * msw-font-menu.el: * msw-font-menu.el (mswindows-reset-device-font-menus): * package-get.el (package-get-installedp): * select.el (select-convert-from-image-data): * sound.el: * sound.el (load-sound-file): * x-font-menu.el (x-reset-device-font-menus-core): Don't quote keywords, they're self-quoting, and the win from backward-compatibility is sufficiently small now that the style problem overrides it. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (block, return-from): Require that NAME be a symbol in these macros, as always documented in the #'block docstring and as required by Common Lisp. * descr-text.el (unidata-initialize-unihan-database): Correct the use of non-symbols in #'block and #'return-from in this function. 2011-01-15 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (concatenate): Accept more complicated TYPEs in this function, handing the sequences over to #'coerce if we don't understand them here. * cl-macs.el (inline): Don't proclaim #'concatenate as inline, its compiler macro is more useful than doing that. 2011-01-11 Aidan Kehoe <kehoea@parhasard.net> * subr.el (delete, delq, remove, remq): Move #'remove, #'remq here, they don't belong in cl-seq.el; move #'delete, #'delq here from fns.c, implement them in terms of #'delete*, allowing support for sequences generally. * update-elc.el (do-autoload-commands): Use #'delete*, not #'delq here, now the latter's no longer dumped. * cl-macs.el (delete, delq): Add compiler macros transforming #'delete and #'delq to #'delete* calls. 2011-01-10 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): Correct a misplaced parenthesis here, thank you Mats Lidell in 87zkr9gqrh.fsf@mail.contactor.se ! 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): * list-mode.el (display-completion-list): These functions used to use cl-parsing-keywords; change them to use defun* instead, fixing the build. (Not sure what led to me not including this change in d1b17a33450b!) 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (define-star-compiler-macros): Make sure the form has ITEM and LIST specified before attempting to change to calls with explicit tests; necessary for some tests in lisp-tests.el to compile correctly. (stable-union, stable-intersection): Add compiler macros for these functions, in the same way we do for most of the other functions in cl-seq.el. 2011-01-01 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (dolist, dotimes, do-symbols, macrolet) (symbol-macrolet): Define these macros with defmacro* instead of parsing the argument list by hand, for the sake of style and readability; use backquote where appropriate, instead of calling #'list and and friends, for the same reason. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * x-misc.el (device-x-display): Provide this function, documented in the Lispref for years, but not existing previously. Thank you Julian Bradfield, thank you Jeff Mincy. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl-seq.el: Move the heavy lifting from this file to C. Dump the cl-parsing-keywords macro, but don't use defun* for the functions we define that do take keywords, dynamic scope lossage makes that not practical. * subr.el (sort, fillarray): Move these aliases here. (map-plist): #'nsublis is now built-in, but at this point #'eql isn't necessarily available as a test; use #'eq. * obsolete.el (cl-delete-duplicates): Make this available for old compiler macros and old code. (memql): Document that this is equivalent to #'member*, and worse. * cl.el (adjoin, subst): Removed. These are in C. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * simple.el (assoc-ignore-case): Remove a duplicate definition of this function (it's already in subr.el). * iso8859-1.el (char-width): On non-Mule, make this function equivalent to that produced by (constantly 1), but preserve its docstring. * subr.el (subst-char-in-string): Define this in terms of #'substitute, #'nsubstitute. (string-width): Define this using #'reduce and #'char-width. (char-width): Give this a simpler definition, it makes far more sense to check for mule at load time and redefine, as we do in iso8859-1.el. (store-substring): Implement this in terms of #'replace, now #'replace is cheap. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * update-elc.el (lisp-files-needed-for-byte-compilation) (lisp-files-needing-early-byte-compilation): cl-macs belongs in the former, not the latter, it is as fundamental as bytecomp.el. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl.el: Provde the Common Lisp program-error, type-error as error symbols. This doesn't nearly go far enough for anyone using the Common Lisp errors. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete-duplicates): If the form has an incorrect number of arguments, don't attempt a compiler macroexpansion. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (cl-safe-expr-p): Forms that start with the symbol lambda are also safe. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): For these functions' compiler macros, the optimisation is safe even if the first and the last arguments have side effects, since they're only used the once. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (inline-side-effect-free-compiler-macros): Unroll a loop here at macro-expansion time, so these compiler macros are compiled. Use #'eql instead of #'eq in a couple of places for better style. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (notany, notevery): Avoid some dynamic scope stupidity with local variable names in these functions, when they weren't prefixed with cl-; go into some more detail in the doc strings. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): #'remove, #'remq are free of side-effects. (side-effect-and-error-free-fns): Drop dot, dot-marker from the list. 2010-11-17 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (coerce): In the argument list, name the first argument OBJECT, not X; the former name was always used in the doc string and is clearer. Handle vector type specifications which include the length of the target sequence, error if there's a mismatch. * cl-macs.el (cl-make-type-test): Handle type specifications starting with the symbol 'eql. 2010-11-14 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (eql): Don't remove the byte-compile property of this symbol. That was necessary to override a bug in bytecomp.el where #'eql was confused with #'eq, which bug we no longer have. If neither expression is constant, don't attempt to handle the expression in this compiler macro, leave it to byte-compile-eql, which produces better code anyway. * bytecomp.el (eq): #'eql is not the function associated with the byte-eq byte code. (byte-compile-eql): Add an explicit compile method for this function, for cases where the cl-macs compiler macro hasn't reduced it to #'eq or #'equal. 2010-10-25 Aidan Kehoe <kehoea@parhasard.net> Add compiler macros and compilation sanity-checking for various functions that take keywords. * byte-optimize.el (side-effect-free-fns): #'symbol-value is side-effect free and not error free. * bytecomp.el (byte-compile-normal-call): Check keyword argument lists for sanity; store information about the positions where keyword arguments start using the new byte-compile-keyword-start property. * cl-macs.el (cl-const-expr-val): Take a new optional argument, cl-not-constant, defaulting to nil, in this function; return it if the expression is not constant. (cl-non-fixnum-number-p): Make this into a separate function, we want to pass it to #'every. (eql): Use it. (define-star-compiler-macros): Use the same code to generate the member*, assoc* and rassoc* compiler macros; special-case some code in #'add-to-list in subr.el. (remove, remq): Add compiler macros for these two functions, in preparation for #'remove being in C. (define-foo-if-compiler-macros): Transform (remove-if-not ...) calls to (remove ... :if-not) at compile time, which will be a real win once the latter is in C. (define-substitute-if-compiler-macros) (define-subst-if-compiler-macros): Similarly for these functions. (delete-duplicates): Change this compiler macro to use #'plists-equal; if we don't have information about the type of SEQUENCE at compile time, don't bother attempting to inline the call, the function will be in C soon enough. (equalp): Remove an old commented-out compiler macro for this, if we want to see it it's in version control. (subst-char-in-string): Transform this to a call to nsubstitute or nsubstitute, if that is appropriate. * cl.el (ldiff): Don't call setf here, this makes for a load-time dependency problem in cl-macs.el 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * term/vt100.el: Refer to XEmacs, not GNU Emacs, in permissions. * term/bg-mouse.el: * term/sup-mouse.el: Put copyright notice in canonical "Copyright DATE AUTHOR" form. Refer to XEmacs, not GNU Emacs, in permissions. * site-load.el: Add permission boilerplate. * mule/canna-leim.el: * alist.el: Refer to XEmacs, not APEL/this program, in permissions. * mule/canna-leim.el: Remove my copyright, I've assigned it to the FSF. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * gtk.el: * gtk-widget-accessors.el: * gtk-package.el: * gtk-marshal.el: * gtk-compose.el: * gnome.el: Add copyright notice based on internal evidence. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * easymenu.el: Add reference to COPYING to permission notice. * gutter.el: * gutter-items.el: * menubar-items.el: Fix typo "Xmacs" in permissions notice. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * auto-save.el: * font.el: * fontconfig.el: * mule/kinsoku.el: Add "part of XEmacs" text to permission notice. 2010-10-14 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): * cl-macs.el (remf, getf): * cl-extra.el (tailp, cl-set-getf, cl-do-remf): * cl.el (ldiff, endp): Tighten up Common Lisp compatibility for #'ldiff, #'endp, #'tailp; add circularity checking for the first two. #'cl-set-getf and #'cl-do-remf were Lisp implementations of #'plist-put and #'plist-remprop; change the names to aliases, changes the macros that use them to using #'plist-put and #'plist-remprop directly. 2010-10-12 Aidan Kehoe <kehoea@parhasard.net> * abbrev.el (fundamental-mode-abbrev-table, global-abbrev-table): Create both these abbrev tables using the usual #'define-abbrev-table calls, rather than attempting to special-case them. * cl-extra.el: Force cl-macs to be loaded here, if cl-extra.el is being loaded interpreted. Previously other, later files would redundantly call (load "cl-macs") when interpreted, it's more reasonable to do it here, once. * cmdloop.el (read-quoted-char-radix): Use defcustom here, we don't have any dump-order dependencies that would prevent that. * custom.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling, rely on cl-extra.el in the former case and the appropriate entry in bytecomp-load-hook in the latter. Get rid of custom-declare-variable-list, we have no dump-time dependencies that would require it. * faces.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling. * packages.el: Remove some inaccurate comments. * post-gc.el (cleanup-simple-finalizers): Use #'delete-if-not here, now the order of preloaded-file-list has been changed to make it available. * subr.el (custom-declare-variable-list): Remove. No need for it. Also remove a stub define-abbrev-table from this file, given the current order of preloaded-file-list there's no need for it. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-constp) Forms quoted with FUNCTION are also constant. (byte-compile-initial-macro-environment): In #'the, if FORM is constant and does not match TYPE, warn at byte-compile time. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * backquote.el (bq-vector-contents, bq-list*): Remove; the former is equivalent to (append VECTOR nil), the latter to (list* ...). (bq-process-2): Use (append VECTOR nil) instead of using #'bq-vector-contents to convert to a list. (bq-process-1): Now we use list* instead of bq-list * subr.el (list*): Moved from cl.el, since it is now required to be available the first time a backquoted form is encountered. * cl.el (list*): Move to subr.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * test-harness.el (Check-Message): Add an omitted comma here, thank you the buildbot. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * hash-table.el (hash-table-key-list, hash-table-value-list) (hash-table-key-value-alist, hash-table-key-value-plist): Remove some useless #'nreverse calls in these files; our hash tables have no order, it's not helpful to pretend they do. * behavior.el (read-behavior): Do the same in this file, in some code evidently copied from hash-table.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * info.el (Info-insert-dir): * format.el (format-deannotate-region): * files.el (cd, save-buffers-kill-emacs): Use #'some, #'every and related functions for applying boolean operations to lists, instead of rolling our own ones that cons and don't short-circuit. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-initial-macro-environment): * cl-macs.el (the): Rephrase the docstring, make its implementation when compiling files a little nicer. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * descr-text.el (unidata-initialize-unicodedata-database) (unidata-initialize-unihan-database, describe-char-unicode-data) (describe-char-unicode-data): Wrap calls to the database functions with (with-fboundp ...), avoiding byte compile warnings on builds without support for the database functions. (describe-char): (reduce #'max ...), not (apply #'max ...), no need to cons needlessly. (describe-char): Remove a redundant lambda wrapping #'extent-properties. (describe-char-unicode-data): Call #'nsubst when replacing "" with nil in the result of #'split-string, instead of consing inside mapcar. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * x-faces.el (x-available-font-sizes): * specifier.el (let-specifier): * package-ui.el (pui-add-required-packages): * msw-faces.el (mswindows-available-font-sizes): * modeline.el (modeline-minor-mode-menu): * minibuf.el (minibuf-directory-files): Replace the O2N (delq nil (mapcar (lambda (W) (and X Y)) Z)) with the ON (mapcan (lambda (W) (and X (list Y))) Z) in these files. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): When these functions are handed more than two arguments, and those arguments have no side effects, transform to a series of two argument calls, avoiding funcall in the byte-compiled code. * mule/mule-cmds.el (finish-set-language-environment): Take advantage of this change in a function called 256 times at startup. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-function-form, byte-compile-quote) (byte-compile-quote-form): Warn at compile time, and error at runtime, if a (quote ...) or a (function ...) form attempts to quote more than one object. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (byte-optimize-apply): Transform (apply 'nconc (mapcar ...)) to (mapcan ...); warn about use of the first idiom. * update-elc.el (do-autoload-commands): * packages.el (packages-find-package-library-path): * frame.el (frame-list): * extents.el (extent-descendants): * etags.el (buffer-tag-table-files): * dumped-lisp.el (preloaded-file-list): * device.el (device-list): * bytecomp-runtime.el (proclaim-inline, proclaim-notinline) Use #'mapcan, not (apply #'nconc (mapcar ...) in all these files. * bytecomp-runtime.el (eval-when-compile, eval-and-compile): In passing, mention that these macros also evaluate the body when interpreted. tests/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * automated/lisp-tests.el: Test lexical scope for `block', `return-from'; add a Known-Bug-Expect-Failure for a contorted example that fails when byte-compiled.
author Aidan Kehoe <kehoea@parhasard.net>
date Mon, 07 Feb 2011 12:01:24 +0000
parents c096d8051f89
children 8d29f1c4bb98
line wrap: on
line source

/* Indentation functions.
   Copyright (C) 1995 Board of Trustees, University of Illinois.
   Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
   Free Software Foundation, Inc.
   Copyright (C) 2002, 2005 Ben Wing.

This file is part of XEmacs.

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

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

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* This file has been Mule-ized. */

/* Synched up with: 19.30.  Diverges significantly from FSF. */


#include <config.h>
#include "lisp.h"

#include "buffer.h"
#include "device.h"
#include "extents.h"
#include "faces.h"
#include "frame.h"
#include "glyphs.h"
#include "insdel.h"
#ifdef REGION_CACHE_NEEDS_WORK
#include "region-cache.h"
#endif
#include "window.h"

/* Indentation can insert tabs if this is non-zero;
   otherwise always uses spaces */
int indent_tabs_mode;

/* Avoid recalculation by remembering things in these variables. */

/* Last value returned by current_column.

   Some things set last_known_column_point to -1
   to mark the memoized value as invalid */
static int last_known_column;

/* Last buffer searched by current_column */
static struct buffer *last_known_column_buffer;

/* Value of point when current_column was called */
static Charbpos last_known_column_point;

/* Value of MODIFF when current_column was called */
static int last_known_column_modified;

static Charbpos
last_visible_position (Charbpos pos, struct buffer *buf)
{
  Lisp_Object buffer;
  Lisp_Object value;

  buffer = wrap_buffer (buf);
  value = Fprevious_single_char_property_change (make_int (pos), Qinvisible,
						 buffer, Qnil);
  if (NILP (value))
    return 0; /* no visible position found */
  else
    /* #### bug bug bug!!! This will return the position of the beginning
       of an invisible extent; this extent is very likely to be start-closed,
       and thus the spaces inserted in `indent-to' will go inside the
       invisible extent.

       Not sure what the correct solution is here.  Rethink indent-to? */
    return XINT (value);
}

#ifdef REGION_CACHE_NEEDS_WORK

/* Allocate or free the width run cache, as requested by the current
   state of current_buffer's cache_long_line_scans variable.  */
static void
width_run_cache_on_off (struct buffer *buf)
{
  if (NILP (buf->cache_long_line_scans))
    {
      /* It should be off.  */
      if (buf->width_run_cache)
        {
          free_region_cache (buf->width_run_cache);
          buf->width_run_cache = 0;
          buf->width_table = Qnil;
        }
    }
  else
    {
      /* It should be on.  */
      if (buf->width_run_cache == 0)
        {
          buf->width_run_cache = new_region_cache ();
          recompute_width_table (buf, buffer_display_table ());
        }
    }
}

#endif /* REGION_CACHE_NEEDS_WORK */


/* Cancel any recorded value of the horizontal position.  */

void
invalidate_current_column (void)
{
  last_known_column_point = -1;
}

int
column_at_point (struct buffer *buf, Charbpos init_pos, int cur_col)
{
  int col;
  int tab_seen;
  int tab_width = XINT (buf->tab_width);
  int post_tab;
  Charbpos pos = init_pos;
  Ichar c;

  if (tab_width <= 0 || tab_width > 1000) tab_width = 8;
  col = tab_seen = post_tab = 0;

  while (1)
    {
      if (pos <= BUF_BEGV (buf))
	break;

      pos--;
      c = BUF_FETCH_CHAR (buf, pos);
      if (c == '\t')
	{
	  if (tab_seen)
	    col = ((col + tab_width) / tab_width) * tab_width;

	  post_tab += col;
	  col = 0;
	  tab_seen = 1;
	}
      else if (c == '\n' ||
	       (EQ (buf->selective_display, Qt) && c == '\r'))
	break;
      else
	{
	  /* #### This needs updating to handle the new redisplay. */
	  /* #### FSFmacs looks at ctl_arrow, display tables.
	     We need to do similar. */
#if 0
	  displayed_glyphs = glyphs_from_charbpos (sel_frame, buf,
						 XWINDOW (selected_window),
						 pos, dp, 0, col, 0, 0, 0);
	  col += (displayed_glyphs->columns
		  - (displayed_glyphs->begin_columns
		     + displayed_glyphs->end_columns));
#else /* XEmacs */
#ifdef MULE
	  col += XCHARSET_COLUMNS (ichar_charset (c));
#else
	  col ++;
#endif /* MULE */
#endif /* XEmacs */
	}
    }

  if (tab_seen)
    {
      col = ((col + tab_width) / tab_width) * tab_width;
      col += post_tab;
    }

  if (cur_col)
    {
      last_known_column_buffer = buf;
      last_known_column = col;
      last_known_column_point = init_pos;
      last_known_column_modified = BUF_MODIFF (buf);
    }

  return col;
}

int
string_column_at_point (Lisp_Object s, Charbpos init_pos, int tab_width)
{
  int col;
  int tab_seen;
  int post_tab;
  Charbpos pos = init_pos;
  Ichar c;

  if (tab_width <= 0 || tab_width > 1000) tab_width = 8;
  col = tab_seen = post_tab = 0;

  while (1)
    {
      if (pos <= 0)
	break;

      pos--;
      c = string_ichar (s, pos);
      if (c == '\t')
	{
	  if (tab_seen)
	    col = ((col + tab_width) / tab_width) * tab_width;

	  post_tab += col;
	  col = 0;
	  tab_seen = 1;
	}
      else if (c == '\n')
	break;
      else
#ifdef MULE
	  col += XCHARSET_COLUMNS (ichar_charset (c));
#else
	  col ++;
#endif /* MULE */
    }

  if (tab_seen)
    {
      col = ((col + tab_width) / tab_width) * tab_width;
      col += post_tab;
    }

  return col;
}

int
current_column (struct buffer *buf)
{
  if (buf == last_known_column_buffer
      && BUF_PT (buf) == last_known_column_point
      && BUF_MODIFF (buf) == last_known_column_modified)
    return last_known_column;

  return column_at_point (buf, BUF_PT (buf), 1);
}

DEFUN ("current-column", Fcurrent_column, 0, 1, 0, /*
Return the horizontal position of point.  Beginning of line is column 0.
This is calculated by adding together the widths of all the displayed
 representations of the character between the start of the previous line
 and point. (e.g. control characters will have a width of 2 or 4, tabs
 will have a variable width.)
Ignores finite width of frame, which means that this function may return
 values greater than (frame-width).
Whether the line is visible (if `selective-display' is t) has no effect;
 however, ^M is treated as end of line when `selective-display' is t.
If BUFFER is nil, the current buffer is assumed.
*/
       (buffer))
{
  return make_int (current_column (decode_buffer (buffer, 0)));
}


DEFUN ("indent-to", Findent_to, 1, 3, "NIndent to column: ", /*
Indent from point with tabs and spaces until COLUMN is reached.
Optional second argument MINIMUM says always do at least MINIMUM spaces
 even if that goes past COLUMN; by default, MINIMUM is zero.
If BUFFER is nil, the current buffer is assumed.
*/
       (column, minimum, buffer))
{
  /* This function can GC */
  int mincol;
  int fromcol;
  struct buffer *buf = decode_buffer (buffer, 0);
  int tab_width = XINT (buf->tab_width);
  Charbpos opoint = 0;

  CHECK_INT (column);
  if (NILP (minimum))
    minimum = Qzero;
  else
    CHECK_INT (minimum);

  buffer = wrap_buffer (buf);

  fromcol = current_column (buf);
  mincol = fromcol + XINT (minimum);
  if (mincol < XINT (column)) mincol = XINT (column);

  if (fromcol == mincol)
    return make_int (mincol);

  if (tab_width <= 0 || tab_width > 1000) tab_width = 8;

  if (!NILP (Fextent_at (make_int (BUF_PT (buf)), buffer, Qinvisible,
			 Qnil, Qnil)))
    {
      Charbpos last_visible = last_visible_position (BUF_PT (buf), buf);

      opoint = BUF_PT (buf);
      if (last_visible >= BUF_BEGV (buf))
	BUF_SET_PT (buf, last_visible);
      else
        invalid_operation ("Visible portion of buffer not modifiable", Qunbound);
    }

  if (indent_tabs_mode)
    {
      int n = mincol / tab_width - fromcol / tab_width;
      if (n != 0)
	{
	  Finsert_char (make_char ('\t'), make_int (n), Qnil, buffer);

	  fromcol = (mincol / tab_width) * tab_width;
	}
    }

  Finsert_char (make_char (' '), make_int (mincol - fromcol), Qnil, buffer);

  last_known_column_buffer = buf;
  last_known_column = mincol;
  last_known_column_point = BUF_PT (buf);
  last_known_column_modified = BUF_MODIFF (buf);

  /* Not in FSF: */
  if (opoint > 0)
    BUF_SET_PT (buf, opoint);

  return make_int (mincol);
}

int
byte_spaces_at_point (struct buffer *b, Bytebpos byte_pos)
{
  Bytebpos byte_end = BYTE_BUF_ZV (b);
  int col = 0;
  Ichar c;
  int tab_width = XINT (b->tab_width);

  if (tab_width <= 0 || tab_width > 1000)
    tab_width = 8;

  while (byte_pos < byte_end &&
	 (c = BYTE_BUF_FETCH_CHAR (b, byte_pos),
	  (c == '\t'
	   ? (col += tab_width - col % tab_width)
	   : (c == ' ' ? ++col : 0))))
    INC_BYTEBPOS (b, byte_pos);

  return col;
}


DEFUN ("current-indentation", Fcurrent_indentation, 0, 1, 0, /*
Return the indentation of the current line.
This is the horizontal position of the character
following any initial whitespace.
*/
       (buffer))
{
  struct buffer *buf = decode_buffer (buffer, 0);
  Charbpos pos = find_next_newline (buf, BUF_PT (buf), -1);

  buffer = wrap_buffer (buf);

  if (!NILP (Fextent_at (make_int (pos), buffer, Qinvisible, Qnil, Qnil)))
    return Qzero;

  return make_int (byte_spaces_at_point (buf, charbpos_to_bytebpos (buf, pos)));
}


DEFUN ("move-to-column", Fmove_to_column, 1, 3, 0, /*
Move point to column COLUMN in the current line.
The column of a character is calculated by adding together the widths
as displayed of the previous characters in the line.
This function ignores line-continuation;
there is no upper limit on the column number a character can have
and horizontal scrolling has no effect.

If specified column is within a character, point goes after that character.
If it's past end of line, point goes to end of line.

A value of `coerce' for the second (optional) argument FORCE means if
COLUMN is in the middle of a tab character, change it to spaces.
Any other non-nil value means the same, plus if the line is too short to
reach column COLUMN, then add spaces/tabs to get there.

Returns the actual column that it moved to.
*/
       (column, force, buffer))
{
  /* This function can GC */
  Charbpos pos;
  struct buffer *buf = decode_buffer (buffer, 0);
  int col = current_column (buf);
  int goal;
  Charbpos end;
  int tab_width = XINT (buf->tab_width);

  int prev_col = 0;
  Ichar c = 0;

  buffer = wrap_buffer (buf);
  if (tab_width <= 0 || tab_width > 1000) tab_width = 8;

  check_integer_range (column, Qzero, make_integer (EMACS_INT_MAX));
  goal = XINT (column);

 retry:
  pos = BUF_PT (buf);
  end = BUF_ZV (buf);

  /* If we're starting past the desired column,
     back up to beginning of line and scan from there.  */
  if (col > goal)
    {
      pos = find_next_newline (buf, pos, -1);
      col = 0;
    }

  while (col < goal && pos < end)
    {
      c = BUF_FETCH_CHAR (buf, pos);
      if (c == '\n')
	break;
      if (c == '\r' && EQ (buf->selective_display, Qt))
	break;
      if (c == '\t')
	{
	  prev_col = col;
	  col += tab_width;
	  col = col / tab_width * tab_width;
	}
      else
	{
	  /* #### oh for the days of the complete new redisplay */
	  /* #### FSFmacs looks at ctl_arrow, display tables.
	     We need to do similar. */
#if 0
	  displayed_glyphs = glyphs_from_charbpos (selected_frame (),
						 buf,
						 XWINDOW (Fselected_window (Qnil)),
						 pos, dp, 0, col, 0, 0, 0);
	  col += (displayed_glyphs->columns
		  - (displayed_glyphs->begin_columns
		     + displayed_glyphs->end_columns));
#else /* XEmacs */
#ifdef MULE
	  col += XCHARSET_COLUMNS (ichar_charset (c));
#else
	  col ++;
#endif /* MULE */
#endif /* XEmacs */
	}

      pos++;
    }

  BUF_SET_PT (buf, pos);

  /* If a tab char made us overshoot, change it to spaces
     and scan through it again.  */
  if (!NILP (force) && col > goal && c == '\t' && prev_col < goal)
    {
      buffer_delete_range (buf, BUF_PT (buf) - 1, BUF_PT (buf), 0);
      Findent_to (make_int (col - 1), Qzero, buffer);
      buffer_insert_emacs_char (buf, ' ');
      goto retry;
    }

  /* If line ends prematurely, add space to the end.  */
  if (col < goal && !NILP (force) && !EQ (force, Qcoerce))
    {
      col = goal;
      Findent_to (make_int (col), Qzero, buffer);
    }

  last_known_column_buffer = buf;
  last_known_column = col;
  last_known_column_point = BUF_PT (buf);
  last_known_column_modified = BUF_MODIFF (buf);

  return make_int (col);
}

#if 0 /* #### OK boys, this function needs to be present, I think.
	 It was there before the 19.12 redisplay rewrite. */

DEFUN ("compute-motion", Fcompute_motion, 7, 7, 0, /*
  "Scan through the current buffer, calculating screen position.
Scan the current buffer forward from offset FROM,
assuming it is at position FROMPOS--a cons of the form (HPOS . VPOS)--
to position TO or position TOPOS--another cons of the form (HPOS . VPOS)--
and return the ending buffer position and screen location.

There are three additional arguments:

WIDTH is the number of columns available to display text;
this affects handling of continuation lines.
This is usually the value returned by `window-width', less one (to allow
for the continuation glyph).

OFFSETS is either nil or a cons cell (HSCROLL . TAB-OFFSET).
HSCROLL is the number of columns not being displayed at the left
margin; this is usually taken from a window's hscroll member.
TAB-OFFSET is the number of columns of the first tab that aren't
being displayed, perhaps because the line was continued within it.
If OFFSETS is nil, HSCROLL and TAB-OFFSET are assumed to be zero.

WINDOW is the window to operate on.  Currently this is used only to
find the display table.  It does not matter what buffer WINDOW displays;
`compute-motion' always operates on the current buffer.

The value is a list of five elements:
  (POS HPOS VPOS PREVHPOS CONTIN)
POS is the buffer position where the scan stopped.
VPOS is the vertical position where the scan stopped.
HPOS is the horizontal position where the scan stopped.

PREVHPOS is the horizontal position one character back from POS.
CONTIN is t if a line was continued after (or within) the previous character.

For example, to find the buffer position of column COL of line LINE
of a certain window, pass the window's starting location as FROM
and the window's upper-left coordinates as FROMPOS.
Pass the buffer's (point-max) as TO, to limit the scan to the end of the
visible section of the buffer, and pass LINE and COL as TOPOS.
*/
	 (from, frompos, to, topos, width, offsets, window))
{
  Lisp_Object charbpos, hpos, vpos, prevhpos, contin;
  struct position *pos;
  int hscroll, tab_offset;
  struct window *w = decode_window (window);

  CHECK_INT_COERCE_MARKER (from);
  CHECK_CONS (frompos);
  CHECK_INT (XCAR (frompos));
  CHECK_INT (XCDR (frompos));
  CHECK_INT_COERCE_MARKER (to);
  CHECK_CONS (topos);
  CHECK_INT (XCAR (topos));
  CHECK_INT (XCDR (topos));
  CHECK_INT (width);
  if (!NILP (offsets))
    {
      CHECK_CONS (offsets);
      CHECK_INT (XCAR (offsets));
      CHECK_INT (XCDR (offsets));
      hscroll = XINT (XCAR (offsets));
      tab_offset = XINT (XCDR (offsets));
    }
  else
    hscroll = tab_offset = 0;

  pos = compute_motion (XINT (from), XINT (XCDR (frompos)),
			XINT (XCAR (frompos)),
			XINT (to), XINT (XCDR (topos)),
			XINT (XCAR (topos)),
			XINT (width), hscroll, tab_offset, w);

  charbpos = make_int (pos->charbpos);
  hpos = make_int (pos->hpos);
  vpos = make_int (pos->vpos);
  prevhpos = make_int (pos->prevhpos);

  return list5 (charbpos, hpos, vpos, prevhpos,
		pos->contin ? Qt : Qnil);
}

#endif /* 0 */

/* Helper for vmotion_1 - compute vertical pixel motion between
   START and END in the line start cache CACHE.  This just sums
   the line heights, including both the starting and ending lines.
*/
static int
vpix_motion (line_start_cache_dynarr *cache, int start, int end)
{
  int i, vpix;

  assert (start <= end);
  assert (start >= 0);
  assert (end < Dynarr_length (cache));

  vpix = 0;
  for (i = start; i <= end; i++)
    vpix += Dynarr_atp (cache, i)->height;

  return vpix;
}

/*****************************************************************************
 vmotion_1

 Given a starting position ORIG, move point VTARGET lines in WINDOW.
 Returns the new value for point.  If the arg ret_vpos is not nil, it is
 taken to be a pointer to an int and the number of lines actually moved is
 returned in it.  If the arg ret_vpix is not nil, it is taken to be a
 pointer to an int and the vertical pixel height of the motion which
 took place is returned in it.
 ****************************************************************************/
static Charbpos
vmotion_1 (struct window *w, Charbpos orig, int vtarget,
           int *ret_vpos, int *ret_vpix)
{
  struct buffer *b = XBUFFER (w->buffer);
  int elt;

  elt = point_in_line_start_cache (w, orig, (vtarget < 0
					     ? -vtarget
					     : vtarget));

  /* #### This assertion must be true before the if statements are hit
     but may possibly be wrong after the call to
     point_in_line_start_cache if orig is outside of the visible
     region of the buffer.  Handle this. */
  assert (elt >= 0);

  /* Moving downward. */
  if (vtarget > 0)
    {
      int cur_line = Dynarr_length (w->line_start_cache) - 1 - elt;
      Charbpos ret_pt;

      if (cur_line > vtarget)
	cur_line = vtarget;

      /* The traditional FSF behavior is to return the end of buffer
         position if we couldn't move far enough because we hit it.  */
      if (cur_line < vtarget)
	ret_pt = BUF_ZV (b);
      else
	ret_pt = Dynarr_atp (w->line_start_cache, cur_line + elt)->start;

      while (ret_pt > BUF_ZV (b) && cur_line > 0)
	{
	  cur_line--;
	  ret_pt = Dynarr_atp (w->line_start_cache, cur_line + elt)->start;
	}

      if (ret_vpos) *ret_vpos = cur_line;
      if (ret_vpix)
        *ret_vpix = vpix_motion (w->line_start_cache, elt, cur_line + elt);
      return ret_pt;
    }
  else if (vtarget < 0)
    {
      if (elt < -vtarget)
	{
	  if (ret_vpos) *ret_vpos = -elt;
          if (ret_vpix)
            *ret_vpix = vpix_motion (w->line_start_cache, 0, elt);
	  /* #### This should be BUF_BEGV (b), right? */
	  return Dynarr_begin (w->line_start_cache)->start;
	}
      else
	{
	  if (ret_vpos) *ret_vpos = vtarget;
          if (ret_vpix)
            *ret_vpix = vpix_motion (w->line_start_cache, elt + vtarget, elt);
	  return Dynarr_atp (w->line_start_cache, elt + vtarget)->start;
	}
    }
  else
    {
      /* No vertical motion requested so we just return the position
         of the beginning of the current line. */
      if (ret_vpos) *ret_vpos = 0;
      if (ret_vpix)
        *ret_vpix = vpix_motion (w->line_start_cache, elt, elt);

      return Dynarr_atp (w->line_start_cache, elt)->start;
    }

  RETURN_NOT_REACHED(0);	/* shut up compiler */
}

/*****************************************************************************
 vmotion

 Given a starting position ORIG, move point VTARGET lines in WINDOW.
 Returns the new value for point.  If the arg ret_vpos is not nil, it is
 taken to be a pointer to an int and the number of lines actually moved is
 returned in it.
 ****************************************************************************/
Charbpos
vmotion (struct window *w, Charbpos orig, int vtarget, int *ret_vpos)
{
  return vmotion_1 (w, orig, vtarget, ret_vpos, NULL);
}

/* Helper for Fvertical_motion.
 */
static
Lisp_Object vertical_motion_1 (Lisp_Object lines, Lisp_Object window,
                               int pixels)
{
  Charbpos charbpos;
  Charbpos orig;
  int selected;
  int *vpos, *vpix;
  int value=0;
  struct window *w;

  if (NILP (window))
    window = Fselected_window (Qnil);

  CHECK_LIVE_WINDOW (window);
  CHECK_INT (lines);

  selected = (EQ (window, Fselected_window (Qnil)));

  w = XWINDOW (window);

  orig = selected ? BUF_PT (XBUFFER (w->buffer))
                  : marker_position (w->pointm[CURRENT_DISP]);

  vpos = pixels ? NULL   : &value;
  vpix = pixels ? &value : NULL;

  charbpos = vmotion_1 (w, orig, XINT (lines), vpos, vpix);

  /* Note that the buffer's point is set, not the window's point. */
  if (selected)
    BUF_SET_PT (XBUFFER (w->buffer), charbpos);
  else
    set_marker_restricted (w->pointm[CURRENT_DISP],
			   make_int(charbpos),
			   w->buffer);

  return make_int (value);
}

DEFUN ("vertical-motion", Fvertical_motion, 1, 3, 0, /*
Move to start of frame line LINES lines down.
If LINES is negative, this is moving up.
Optional second argument is WINDOW to move in,
the default is the selected window.

Sets point to position found; this may be start of line
or just the start of a continuation line.
If optional third argument PIXELS is nil, returns number
of lines moved; may be closer to zero than LINES if beginning
or end of buffer was reached.  If PIXELS is non-nil, the
vertical pixel height of the motion which took place is
returned instead of the actual number of lines moved.  A
motion of zero lines returns the height of the current line.

NOTE NOTE NOTE: GNU Emacs/XEmacs difference.

What `vertical-motion' actually does is set WINDOW's buffer's point
if WINDOW is the selected window; else, it sets WINDOW's point.
This is unfortunately somewhat tricky to work with, and different
from GNU Emacs, which always uses the current buffer, not WINDOW's
buffer, always sets current buffer's point, and, from the
perspective of this function, temporarily makes WINDOW display
the current buffer if it wasn't already.
*/
       (lines, window, pixels))
{
  return vertical_motion_1 (lines, window, !NILP (pixels));
}

/*
 * Like vmotion() but requested and returned movement is in pixels.
 * HOW specifies the stopping condition.  Positive means move at least
 * PIXELS.  Negative means at most.  Zero means as close as possible.
 */
Charbpos
vmotion_pixels (Lisp_Object window, Charbpos start, int pixels, int how,
                int *motion)
{
  struct window *w;
  Charbpos eobuf, bobuf;
  int defheight;
  int needed;
  int line, next;
  int remain, abspix, dirn;
  int elt, nelt;
  int i;
  line_start_cache_dynarr *cache;
  int previous = -1;
  int lines;

  if (NILP (window))
    window = Fselected_window (Qnil);

  CHECK_LIVE_WINDOW (window);
  w = XWINDOW (window);

  eobuf = BUF_ZV (XBUFFER (w->buffer));
  bobuf = BUF_BEGV (XBUFFER (w->buffer));

  default_face_width_and_height (window, NULL, &defheight);

  /* guess num lines needed in line start cache + a few extra */
  abspix = abs (pixels);
  needed = (abspix + defheight-1)/defheight + 3;

  dirn = (pixels >= 0) ? 1 : -1;

  while (1)
    {
      elt = point_in_line_start_cache (w, start, needed);
      assert (elt >= 0); /* in the cache */

      cache = w->line_start_cache;
      nelt  = Dynarr_length (cache);

      *motion = 0;

      if (pixels == 0)
        /* No vertical motion requested so we just return the position
           of the beginning of the current display line. */
        return Dynarr_atp (cache, elt)->start;

      if ((dirn < 0 && elt == 0      &&
           Dynarr_atp (cache, elt)->start <= bobuf) ||
          (dirn > 0 && elt == nelt-1 &&
           Dynarr_atp (cache, elt)->end   >= eobuf))
        return Dynarr_atp (cache, elt)->start;

      remain = abspix;
      for (i = elt; (dirn > 0) ? (i < nelt) : (i > 0); i += dirn)
        {
          /* cache line we're considering moving over */
          int ii = (dirn > 0) ? i : i-1;

          if (remain < 0)
            return Dynarr_atp (cache, i)->start;

          line = Dynarr_atp (cache, ii)->height;
          next = remain - line;

          /* is stopping condition satisfied? */
          if ((how >  0  &&  remain <= 0)  ||       /* at least */
              (how <  0  &&  next < 0)     ||       /* at most */
              (how == 0  &&  remain <= abs (next))) /* closest */
            return Dynarr_atp (cache, i)->start;

          /* moving down and nowhere left to go? */
          if (dirn > 0 && Dynarr_atp (cache, ii)->end >= eobuf)
            return Dynarr_atp (cache, ii)->start;

          /* take the step */
          remain   = next;
          *motion += dirn * line;

          /* moving up and nowhere left to go? */
          if (dirn < 0 && Dynarr_atp (cache, ii)->start <= bobuf)
            return Dynarr_atp (cache, ii)->start;
        }

      /* get here => need more cache lines.  try again. */
      assert (abs (*motion) > previous); /* progress? */
      previous = abs (*motion);

      lines   = (pixels < 0) ? elt : (nelt - elt);
      needed += (remain*lines + abspix-1)/abspix + 3;
    }

  RETURN_NOT_REACHED(0);	/* shut up compiler */
}

DEFUN ("vertical-motion-pixels", Fvertical_motion_pixels, 1, 3, 0, /*
Move to start of frame line PIXELS vertical pixels down.
If PIXELS is negative, this is moving up.
The actual vertical motion in pixels is returned.

Optional second argument is WINDOW to move in,
the default is the selected window.

Optional third argument HOW specifies when to stop.  A value
less than zero indicates that the motion should be no more
than PIXELS.  A value greater than zero indicates that the
motion should be at least PIXELS.  Any other value indicates
that the motion should be as close as possible to PIXELS.
*/
       (pixels, window, how))
{
  Charbpos charbpos;
  Charbpos orig;
  int selected;
  int motion;
  int howto;
  struct window *w;

  if (NILP (window))
    window = Fselected_window (Qnil);

  CHECK_LIVE_WINDOW (window);
  CHECK_INT (pixels);

  selected = (EQ (window, Fselected_window (Qnil)));

  w = XWINDOW (window);

  orig = selected ? BUF_PT (XBUFFER (w->buffer))
                  : marker_position (w->pointm[CURRENT_DISP]);

  howto = INTP (how) ? XINT (how) : 0;

  charbpos = vmotion_pixels (window, orig, XINT (pixels), howto, &motion);

  if (selected)
    BUF_SET_PT (XBUFFER (w->buffer), charbpos);
  else
    set_marker_restricted (w->pointm[CURRENT_DISP],
			   make_int(charbpos),
			   w->buffer);

  return make_int (motion);
}


void
syms_of_indent (void)
{
  DEFSUBR (Fcurrent_indentation);
  DEFSUBR (Findent_to);
  DEFSUBR (Fcurrent_column);
  DEFSUBR (Fmove_to_column);
#if 0 /* #### */
  DEFSUBR (Fcompute_motion);
#endif
  DEFSUBR (Fvertical_motion);
  DEFSUBR (Fvertical_motion_pixels);
}

void
vars_of_indent (void)
{
  DEFVAR_BOOL ("indent-tabs-mode", &indent_tabs_mode /*
*Indentation can insert tabs if this is non-nil.
Setting this variable automatically makes it local to the current buffer.
*/ );
  indent_tabs_mode = 1;
}