/* Indentation functions.
   Copyright (C) 1985, 1986, 1987, 1988, 1990 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs 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 1, or (at your option)
any later version.

GNU Emacs 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 GNU Emacs; see the file COPYING.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

/*
 * Epoch 4.0:  must now consider actual character widths, etc. according
 * to styles (which are window-dependent)
 *
 * $Revision: 1.42 $
 * $Source: /import/kaplan/stable/distrib/epoch-4.2/src/RCS/indent.c,v $
 * $Date: 92/08/05 04:15:54 $
 * $Author: marca $
 */
#ifndef LINT
static char rcsid[] = "$Author: marca $ $Date: 92/08/05 04:15:54 $ $Source: /import/kaplan/stable/distrib/epoch-4.2/src/RCS/indent.c,v $ $Revision: 1.42 $";
#endif

#include "config.h"
#include "lisp.h"
#include "buffer.h"
#include "indent.h"
#include "window.h"
#include "termchar.h"
#include "termopts.h"

#include "dispepoch.h"		/* Epoch */
#include "screen.h"		/* Epoch */
#include "button.h"		/* Epoch */
#include "screenW.h"		/* Epoch */
#define CR '\015'

extern short text_width();

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

#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))

/* These three values memoize the current column to avoid recalculation */
/* Some things in set last_known_column_point to -1
  to mark the memoized value as invalid */
/* Last value returned by current_column */
int last_known_column;
/* Value of point when current_column was called */
int last_known_column_point;
/* Value of MODIFF when current_column was called */
int last_known_column_modified;

int last_known_pixel;
int last_known_pixel_point;
int last_known_pixel_modified;

extern int minibuf_prompt_width;

DEFUN ("current-column", Fcurrent_column, Scurrent_column, 0, 0, 0,
  "Return the horizontal position of point.  Beginning of line is column 0.\n\
This is calculated by adding together the widths of all the displayed\n\
representations of the character between the start of the previous line\n\
and point.  (eg control characters will have a width of 2 or 4, tabs\n\
will have a variable width)\n\
Ignores finite width of screen, which means that this function may return\n\
values greater than (screen-width).\n\
Whether the line is visible (if `selective-display' is t) has no effect.")
  () 
{
  Lisp_Object temp;
  XFASTINT (temp) = current_column (0);
  return temp;
}

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

invalidate_current_column ()
{
  last_known_column_point = 0;
}

DEFUN ("current-pixel",Fcurrent_pixel,Scurrent_pixel,0,0,0,
       "Returns the horizontal position of point as a pixel value.  Beginning of line\n\
is pixel 0.")
       ()
{
  Lisp_Object temp;
  XFASTINT(temp) = current_pixel ();
  return temp;
}

int
current_column (arg)
     int arg;
{
  register int col;
  register unsigned char *ptr, *stop, c;
  register int tab_seen;
  register int post_tab;
  register int tab_width = XINT (current_buffer->tab_width);
  int ctl_arrow = (!NULL (current_buffer->ctl_arrow))
    + (EQ (current_buffer->ctl_arrow,Qt));
  int old_pt = point;
  int meta_printable = !NULL (current_buffer->meta_printable);
  
  if (arg) SET_PT(arg);

  if (point == last_known_column_point
      && MODIFF == last_known_column_modified)
    {
      point = old_pt;
      return last_known_column;
    }

  /* Make a pointer for decrementing through the chars before point.  */
  ptr = &FETCH_CHAR (point - 1) + 1;
  /* Make a pointer to where consecutive chars leave off,
     going backwards from point.  */
  if (point == BEGV)
    stop = ptr;
  else if (point <= GPT || BEGV > GPT)
    stop = BEGV_ADDR;
  else
    stop = GAP_END_ADDR;

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

  col = 0, tab_seen = 0, post_tab = 0;

  while (1)
    {
      if (ptr == stop)
	{
	  /* We stopped either for the beginning of the buffer
	     or for the gap.  */
	  if (ptr == BEGV_ADDR)
	    break;
	  /* It was the gap.  Jump back over it.  */
	  stop = BEGV_ADDR;
	  ptr = GPT_ADDR;
	  /* Check whether that brings us to beginning of buffer.  */
	  if (BEGV >= GPT) break;
	}

      c = *--ptr;
      if (c >= 040 && c < 0177)
	{
	  col++;
	}
      else if (c == '\n')
	break;
      else if (c == '\r' && EQ (current_buffer->selective_display, Qt))
	break;
      else if (c == '\t')
	{
	  if (tab_seen)
	    col = ((col + tab_width) / tab_width) * tab_width;

	  post_tab += col;
	  col = 0;
	  tab_seen = 1;
  } else if (is_control_char(c))
 	  col += ctl_arrow ? 2 : 4;
  else if (is_meta_char(c))
    col += meta_printable ? 1 : 4;
  else
 	col += 4;
  }
  
  if (tab_seen)
    {
      col = ((col + tab_width) / tab_width) * tab_width;
      col += post_tab;
    }

  last_known_column = col;
  last_known_column_point = point;
  last_known_column_modified = MODIFF;

  if (arg)
    SET_PT(old_pt);

  return col;
}

int
current_pixel()
{
  register unsigned char *ptr, *stop,a;
  unsigned char c[2];
  register int pix,col;
  register int tab_seen;
  register int post_tab,tab_chars;
  register int tab_width = XINT (current_buffer->tab_width);
  int ctl_arrow = (!NULL (current_buffer->ctl_arrow))
    + (EQ (current_buffer->ctl_arrow,Qt));
  struct X_font *font;
  struct buffer *b = current_buffer;

  if (point == last_known_pixel_point &&
      MODIFF == last_known_pixel_modified)
    return last_known_pixel;

  /* Make a pointer for decrementing through the chars before point. */
  ptr = &FETCH_CHAR(point - 1) + 1;
  /* Make ptr to where consecutive chars lead off, going backwards */
  if (point == BEGV)
    stop = ptr;
  else if (point <= GPT || BEGV > GPT)
    stop = BEGV_ADDR;
  else
    stop = GAP_END_ADDR;

  font = XXFONT(STYLE_FIELD(XWINDOW(selected_window),font,stylenorm));
  c[1]=0;

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

  pix = 0, col = 0, tab_seen = 0, post_tab = 0, tab_chars = 0;

  while (1)
    {
      if (ptr == stop)
	{
	  if (ptr == BEGV_ADDR)
	    break;
	  stop = BEGV_ADDR;
	  ptr = GPT_ADDR;
	  if (BEGV >= GPT) break;
	}
      a = c[0] = *--ptr;
      if (a >= 040 && a < 0177)
	{
	  pix += text_width(font,c,1);
	  col++;
	}
      else if (a == '\n')
	break;
      else if (a == '\r' && EQ(current_buffer->selective_display,Qt))
	break;
      else if (a == '\t')
	{
	  if (tab_seen)
	    {
	      int i = col;
	      col = ((col + tab_width) / tab_width) * tab_width;
	      tab_chars += (col - i);
	    }
	  post_tab += col;
	  col = 0;
	  tab_seen = 1;
	}
      else
	{
	  c[0] = '0';
	  col += (ctl_arrow == 1 && a >= 0177) ? 1 :
	    (ctl_arrow && a < 0200) ? 2 : 4;
	  pix += ((ctl_arrow == 1 && a >= 0177) ? 1 :
		  (ctl_arrow && a < 0200) ? 2 : 4) * text_width(font,c,1);
	}
    }

  if (tab_seen)
    {
      int i = col;
      col = ((col + tab_width) / tab_width) * tab_width;
      i = col - i;
      col += post_tab;      
      c[0] = ' ';
      pix += (tab_chars + i) * text_width(font,c,1);
    }
      
  last_known_pixel = pix;
  last_known_pixel_point = point;
  last_known_pixel_modified = MODIFF;
  last_known_column_point = pix;
  last_known_column = col;
  last_known_column_modified = MODIFF;

  return pix;
}

DEFUN ("text-width", Ftext_width,Stext_width,1,2,0,
       "Return the text width of STRING displayed using FONT.  Uses the\n\
default font of the selected window if FONT is nil.")
	(str,font_name) Lisp_Object str,font_name;
{
  Lisp_Object f;
  char buf[300];
  register char *ptr;
  int c;
  register int i = 0,j = 0;
  register int tab_width = XINT(current_buffer->tab_width);
  register int ctl_arrow = (!NULL (current_buffer->ctl_arrow))
    + (EQ (current_buffer->ctl_arrow,Qt));
  
  struct X_font *font;
  extern Lisp_Object get_style_font();

  if (tab_width <= 0 || tab_width >= 20) tab_width = 8;
  CHECK_STRING(str,0);
  font =
    XXFONT(XSTYLE(XROOT(XWINDOW(selected_window)->root)->stylenorm)->font);
  if (!NULL(font_name))
    {
      f = get_style_font(font_name);

      if (!NULL(f))
	font = XXFONT(f);
    }
  /* Make a string corresponding to STRING as displayed in selected window.
   */
  ptr = (char *) XSTRING(str)->data;
  i = strlen(XSTRING(str)->data);
  c = *ptr++;

  while (i)
    {
      if (c >= 040 && c < 0177)
	{
	  buf[j++] = c;

	}
      else if (c == '\t')
	{
	  int k = tab_width;

	  while (k--)
	    buf[j++] = ' ';
	}
      else if (c == '\n' || c == '\r')
	continue;
      else
	{
	  int k = (ctl_arrow == 1 && (c >= 0177)) ? 1 :
	    (ctl_arrow && (c < 0200)) ? 2 : 4;

	  while (k--)
	    buf[j++] = '0';
	}
      i--;
      c = *ptr++;
    }
  buf[j] = 0;
  return make_number(text_width(font,buf,j));

}


ToCol (col)
     int col;
{
  register int fromcol = current_column (0);
  register int n;
  register int tab_width = XINT (current_buffer->tab_width);

  if (fromcol > col)
    return;

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

  if (indent_tabs_mode)
    {
      n = col / tab_width - fromcol / tab_width;
      if (n)
	{
	  while (n-- > 0)
	    insert ("\t", 1);

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

  while (fromcol < col)
    {
      insert ("        ", min (8, col - fromcol));
      fromcol += min (8, col - fromcol);
    }

  last_known_column = col;
  last_known_column_point = point;
  last_known_column_modified = MODIFF;
}

DEFUN ("indent-to", Findent_to, Sindent_to, 1, 2, "NIndent to column: ",
  "Indent from point with tabs and spaces until COLUMN is reached.\n\
Always do at least MIN spaces even if that goes past COLUMN;\n\
by default, MIN is zero.")
  (col, minimum)
     Lisp_Object col, minimum;
{
  int mincol;
  register int fromcol;
  register int tab_width = XINT (current_buffer->tab_width);

  CHECK_NUMBER (col, 0);
  if (NULL (minimum))
    XFASTINT (minimum) = 0;
  CHECK_NUMBER (minimum, 1);

  fromcol = current_column (0);
  mincol = fromcol + XINT (minimum);
  if (mincol < XINT (col)) mincol = XINT (col);

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

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

  if (indent_tabs_mode)
    {
      Lisp_Object n;
      XFASTINT (n) = mincol / tab_width - fromcol / tab_width;
      if (XFASTINT (n) != 0)
	{
	  Finsert_char (make_number ('\t'), n);

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

  XFASTINT (col) = mincol - fromcol;
  Finsert_char (make_number (' '), col);

  last_known_column = mincol;
  last_known_column_point = point;
  last_known_column_modified = MODIFF;

  XSETINT (col, mincol);
  return col;
}

DEFUN ("current-indentation", Fcurrent_indentation, Scurrent_indentation,
  0, 0, 0,
  "Return the indentation of the current line.\n\
This is the horizontal position of the character\n\
following any initial whitespace.")
  ()
{
  Lisp_Object val;

  XFASTINT (val) = position_indentation (find_next_newline (point, -1));
  return val;
}

position_indentation (pos)
     register int pos;
{
  register int column = 0;
  register int tab_width = XINT (current_buffer->tab_width);
  register unsigned char *p;
  register unsigned char *stop;

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

  stop = &FETCH_CHAR (BufferSafeCeiling (pos)) + 1;
  p = &FETCH_CHAR (pos);
  while (1)
    {
      while (p == stop)
	{
	  if (pos == ZV)
	    return column;
	  pos += p - &FETCH_CHAR (pos);
	  p = &FETCH_CHAR (pos);
	  stop = &FETCH_CHAR (BufferSafeCeiling (pos)) + 1;
	}
      switch (*p++)
	{
	case ' ':
	  column++;
	  break;
	case '\t':
	  column += tab_width - column % tab_width;
	  break;
	default:
	  return column;
	}
    }
}

DEFUN ("move-to-pixel",Fmove_to_pixel, Smove_to_pixel,1,1,0,
  "Move point to character column corresponding to PIXEL in the current\n\
line.")
  (pixel) Lisp_Object pixel;
{
  Lisp_Object val;

  CHECK_NUMBER(pixel,0);
  XFASTINT(val) = move_to_pixel(XFASTINT(pixel),1);
  return val;
}

move_to_pixel(goal)
     int goal;
{
  char c[2];
  register int pos = point;
  register int pix = current_pixel();
  register int col = current_column(0);
  register int end = ZV;
  register int tab_width = XINT(current_buffer->tab_width);
  register int ctl_arrow = (!NULL (current_buffer->ctl_arrow))
    + (EQ (current_buffer->ctl_arrow, Qt));
  register int meta_printable = !NULL (current_buffer->meta_printable);
  struct X_font *font;
  struct buffer *b = current_buffer;

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

  if (pix > goal)
    {
      pos = find_next_newline (pos, -1);
      pix = 0;
      col = 0;
    }

  font = XXFONT(STYLE_FIELD(XWINDOW(selected_window),font,stylenorm));
  c[1] = 0;

  while (pix + XFWIDTH(font) <= goal && pos < end)
    {
      int a = c[0] = FETCH_CHAR(pos);
      
      if (a == '\n')
	break;
      if (a == '\r' && EQ (current_buffer->selective_display, Qt))
	break;
      pos++;
      col++;
      pix += text_width(font,c,1);
      if (a == '\t')
	{
	  int i = col;
	  c[0] = ' ';

	  col += tab_width - 1;
	  col = col / tab_width * tab_width;

	  pix += (col - i) * text_width(font,c,1);
	}
      else if (ctl_arrow == 1 && a >= 040)
	continue;
	  /*
      else if (ctl_arrow && (a < 040 || a == 0177))
	{
	  col++;
	  c[0] = '0';
	  pix += text_width(font,c,1);
	}
      else if (a < 040 || a >= 0177)
	{
	  col += 3;
	  c[0] = '0';
	  pix += text_width(font,c,1);
	}
	  */
	  else if (is_control_char(a))
	{
 	  col += ctl_arrow ? 1 : 3;
 	  c[0] = '0';
 	  pix += text_width(font,c,1);
    } else  if (is_meta_char(a)) {
	  col += meta_printable ? 0 : 3;
	  c[0] = '0';
	  pix += text_width(font,c,1);
    } else if (a < 040 || a >= 0177) {
	  col += 3;
	  c[0] = '0';
	  pix += text_width(font,c,1);
    }
    }      

  SET_PT(pos);

  last_known_pixel = pix;
  last_known_pixel_point = point;
  last_known_pixel_modified = MODIFF;
  last_known_column = col;
  last_known_column_point = point;
  last_known_column_modified = MODIFF;

  return pix;
}
   
DEFUN ("move-to-column", Fmove_to_column, Smove_to_column, 1, 1, 0,
  "Move point to column COLUMN in the current line.\n\
COLUMN is calculated by adding together the widths of all the displayed\n\
representations of the character between the start of the previous line\n\
and point.  (eg control characters will have a width of 2 or 4, tabs\n\
will have a variable width)\n\
Ignores finite width of screen, which means that this function may be\n\
passed values greater than (screen-width)")
  (column)
     Lisp_Object column;
{
  Lisp_Object val;
  
  CHECK_NUMBER (column, 0);
  XFASTINT(val) = move_to_col(XFASTINT(column));
  return val;
}

move_to_col(goal)
     int goal;
{
  register int pos = point;
  register int col = current_column (0);
  register int end = ZV;
  register int tab_width = XINT (current_buffer->tab_width);
  register int ctl_arrow = (!NULL (current_buffer->ctl_arrow))
    + (EQ (current_buffer->ctl_arrow, Qt));
  register int meta_printable = !NULL (current_buffer->meta_printable);
  
  if (tab_width <= 0 || tab_width > 20) tab_width = 8;

  if (col > goal)
    {
      pos = find_next_newline (pos, -1);
      col = 0;
    }

  while (col < goal && pos < end)
    {
      int c = FETCH_CHAR (pos);
      if (c == '\n')
	break;
      if (c == '\r' && EQ (current_buffer->selective_display, Qt))
	break;
      pos++;
      col++;      
      if (c == '\t')
	{
	  int i = pos;

	  col += tab_width - 1;
	  col = col / tab_width * tab_width;
	}
      else if (ctl_arrow == 1 && c >= 040)
	continue;
	  else if (is_control_char(c)) {
 		  col += ctl_arrow ? 1 : 3;
      } else  if (is_meta_char(c)) {
 		  col += meta_printable ? 0 : 3;
 	  } else if (c < 040 || c >= 0177) {
 		  col += 3;
 	  }
  }

  SET_PT (pos);

  last_known_column = col;
  last_known_column_point = point;
  last_known_column_modified = MODIFF;

  return col;
}

struct position val_compute_motion;

#define CHECK_NEXT(s) {\
  wid = text_width(font,s,1);\
  if (HPOS(cpos)<0) cpos++; else\
  if ((cwidth + wid) > cend)\
    {\
      if (hscroll || (truncate_partial_width_windows &&\
		      (cend + cbuf) < cur_Wscreen->pixw) ||\
		     !NULL(current_buffer->truncate_lines))\
	{\
	  while (pos < to && FETCH_CHAR(pos) != '\n') pos++;\
	  pos--;\
	}\
      else\
	{\
          cpos = ((VPOS(cpos) + 1) << SHORTBITS)+ 1 ;\
	  cwidth = wid;\
	  tab_offset += window_char_width(w) -1;\
	}\
    }\
  else\
    {\
      cwidth += wid;\
      cpos += 1;\
    }\
   }

/* Note that `cpos' is CURRENT_VPOS << SHORTBITS + CURRENT_HPOS,
 * and that CURRENT_HPOS may be negative.  Use these macros
 * to extract the hpos or the vpos from cpos or anything like it.
 */
#ifndef SHORT_CAST_BUG
#define HPOS(VAR) (short) (VAR)
#else
#define HPOS(VAR) (((VAR) & (1 << (SHORTBITS - 1)) \
		    ? ~((1 << SHORTBITS) - 1) : 0) \
		   | (VAR) & ((1 << SHORTBITS) - 1))
#endif				/* SHORT_CAST_BUG */
#define VPOS(VAR) (((VAR) >> SHORTBITS) + (HPOS (VAR) < 0))

/* START_BUTTON is a starting point in the zone list.  If Qnil, then start
   from scratch */
   
struct position *
compute_motion (from,fromvpos,fromhpos,to,tovpos,tohpos,
		hscroll,tab_offset,
		w,
		start_button)
     int from,fromvpos,fromhpos,to,tovpos,tohpos,hscroll,tab_offset;
     struct window *w;
     Lisp_Object start_button;
{
  register int cpos = fromhpos + (fromvpos << SHORTBITS);
  register int target = tohpos + (tovpos << SHORTBITS);
  register int pos;
  int c;
  int c1;
  char a[2];		    
  register int tab_width = XFASTINT (current_buffer->tab_width);
  register int ctl_arrow = (!NULL (current_buffer->ctl_arrow))
    + (EQ  (current_buffer->ctl_arrow, Qt));
  int cwidth = 0;
  int cend = XFASTINT(w->pixwidth);
  int cbuf;
  int savecpos,savecwidth,savepos;
  short wid;		    
  int button_end, button_start;
  int truncate = hscroll || (truncate_partial_width_windows &&
			     XFASTINT(w->pixwidth) < XWSCREEN(XROOT(w->root)->win)->pixw);
  int meta_printable = !NULL (current_buffer->meta_printable);
  int selective = XTYPE (current_buffer->selective_display) == Lisp_Int
    ? XINT (current_buffer->selective_display)
      : !NULL (current_buffer->selective_display) ? -1 : 0;
  int prevpos;
  struct Lisp_Style *style;
  Lisp_Object ob;
  struct X_font *font;
  struct buffer *b = XBUFFER(w->buffer);
  Lisp_Object next_b = start_button;

  if (tab_width <= 0 || tab_width > 20) tab_width = 8;
  ob = get_button(current_buffer,from,&button_start,&button_end,
		  &next_b,0);
  if (!NULL(ob))
    {
      /* Set font according to style's font (if there) */
      style = XSTYLE(ob);
      if (style && (XTYPE(style->font) == Lisp_Raw_Data))
	{
	  font = XXFONT(style->font);
	}
      else
	{
	  font = XXFONT(STYLE_FIELD(w,font,stylenorm));
	}
    }
  else
    {
      font = XXFONT(STYLE_FIELD(w,font,stylenorm));
      style = 0;
    }

  if (w == XWINDOW(minibuf_window) && minibuf_prompt_width)
    {
      cwidth = text_width(font,minibuf_prompt,strlen(minibuf_prompt)) + 1;
    }

  /* Adjust right logical border of window to consider truncate character
   */
  a[0] = truncate ? '$' : '\\';
  a[1] = 0;
  cbuf = text_width(font,a,1);
  cend -= cbuf;
  
  for (pos = from; pos < to && cpos < target; pos++)
    {
      prevpos = cpos;
      if (pos == button_start || pos == button_end || button_start == -1)
	{
	  ob = get_button(current_buffer,pos,&button_start,&button_end,
			  &next_b,0);
	  if (!NULL(ob))
	    {
	      style = XSTYLE(ob);
	      if (style && (XTYPE(style->font) == Lisp_Raw_Data))
		{
		  font = XXFONT(style->font);
		}
	      else
		{
		  font = XXFONT(STYLE_FIELD(w,font,stylenorm));
		}
	    }
	  else
	    {
	      font = XXFONT(STYLE_FIELD(w,font,stylenorm));
	      style = 0;
	    }
	}
      c = FETCH_CHAR(pos);
      if (c >= 040 && c < 0177)
	{
	  a[0] = c;
	  CHECK_NEXT(a);
	}
      else if (c == '\t')
	{
	  int i;
	  int inc = tab_width
	    - HPOS (cpos + tab_offset + hscroll - (hscroll > 0) + tab_width)
	      % tab_width;
	  a[0] = ' ';
	  for (i = 0; i < inc; i++)
	    CHECK_NEXT(a);
	}
      else if (c == '\n')
	{
	  if (selective > 0 && position_indentation (pos + 1) >= selective)
	    {
	      /* Skip invisible lines */
	      do
		{
		  while (++pos < to && FETCH_CHAR(pos) != '\n');
		}
	      while (selective > 0 && position_indentation(pos + 1) >= selective);
	      pos--;
	      /* Allow for ' ...' */
	      if (!NULL(current_buffer->selective_display_ellipses))
		{
		  int i;
		  a[0] = ' ';
		  CHECK_NEXT(a);
		  a[0] = '.';
		  for (i = 0; i < 3; i++)
		    CHECK_NEXT(a);
		}
	    }
	  else
	    {
/*	      cpos += (1 << SHORTBITS) - HPOS(cpos); */
	      cpos = ((VPOS(cpos) + 1) << SHORTBITS);
	      cwidth = 0;
	    }
	  cpos -= hscroll;
	  if (hscroll > 0)
	    {
	      a[0] = '$';
	      CHECK_NEXT(a);
	    }
	  tab_offset = 0;
	}
      else if (c == CR && selective < 0)
	{
	  while (pos < to && FETCH_CHAR(pos) != '\n') pos++;
	  pos--;
	  /* Allow for ' ...' */
	  if (!NULL(current_buffer->selective_display_ellipses))
	    {
	      int i;
	      a[0] = ' ';
	      CHECK_NEXT(a);
	      a[0] = '.';
	      for (i = 0; i < 3; i++)
		CHECK_NEXT(a);
	    }
	}
      else
	{
	  if (is_meta_char(c) && meta_printable)
	    {
	      /* Insert control character as itself */
	      a[0] = c;
	      CHECK_NEXT(a);
	    }
	  else if (is_control_char(c) && ctl_arrow)
	    {
	      /* Insert control character as 2-char sequence */
	      a[0] = '^';
	      CHECK_NEXT(a);

	      a[0] = c ^ 0100;
	      CHECK_NEXT(a);
	    }
	  else
	    {
	      /* Insert control character as 4-char sequence */
	      a[0] = '\\';
	      CHECK_NEXT(a);

	      a[0] = (c>>6) + '0';
	      CHECK_NEXT(a);

	      a[0] = (7 & (c >>3)) + '0';
	      CHECK_NEXT(a);

	      a[0] = (7 & c) + '0';
	      CHECK_NEXT(a);
	    }
	}
    }

 done:

  savecpos = cpos;
  savepos = pos;
  savecwidth = cwidth;

  /* If at end of buffer/narrowed region, don't fetch next character as
   * it isn't there.  Fake it with last character of buffer.
   */
  a[0] = c1 = ((pos < ZV) ? FETCH_CHAR(pos) : c);
  CHECK_NEXT(a);
  if (VPOS(cpos) != VPOS(savecpos) && savepos < ZV && (c1 != '\n') && !truncate)
    {
      cpos = ((VPOS(savecpos) + 1) << SHORTBITS);
      pos = savepos;
    }
  else
    {
      cpos = savecpos;
      pos = savepos;
    }
  
#if 0  /* ORIGINAL */
  if ((cwidth + wid) >= cend && pos < ZV && (c1 != '\n') && !truncate)
    {
      cpos = ((VPOS(cpos) + 1) << SHORTBITS);
    }
#endif  

  val_compute_motion.bufpos = pos;
  val_compute_motion.hpos = HPOS(cpos);
  val_compute_motion.vpos = VPOS(cpos);
  val_compute_motion.prevhpos = HPOS(prevpos);
		    
  val_compute_motion.contin
    = pos != from &&
      (val_compute_motion.vpos != VPOS(prevpos)) &&
	c != '\n';

  return &val_compute_motion;
}
#undef HPOS
#undef VPOS
#undef CHECK_NEXT

pos_tab_offset (w, pos)
     struct window *w;
     register int pos;
{
  int opoint = point;
  register int width = window_char_width(w);
  int col;

  if (pos == BEGV || FETCH_CHAR (pos - 1) == '\n')
    return 0;
  SET_PT (pos);
  col = current_column (0);
  SET_PT (opoint);
  
  return col - (col % (width - 1));
}

/* start_hpos is the hpos of the first character of the buffer:
   zero except for the minibuffer window,
   where it is the width of the prompt.  */

struct position val_vmotion;

struct position *
vmotion (from, vtarget, hscroll, window)
     register int from, vtarget;
     int hscroll;
     Lisp_Object window;
{
  struct position pos;
  /* vpos is cumulative vertical position, changed as from is changed */
  register int vpos = 0;
  register int width = window_char_width(XWINDOW(window));
  register int prevline;
  register int first;
  int lmargin = hscroll > 0 ? 1 - hscroll : 0;
  int selective
    = XTYPE (current_buffer->selective_display) == Lisp_Int
      ? XINT (current_buffer->selective_display)
	: !NULL (current_buffer->selective_display) ? -1 : 0;
  int start_hpos = (EQ (window, minibuf_window) ? minibuf_prompt_width : 0);

 retry:
  if (vtarget > vpos)
    {
      /* Moving downward is simple, but must calculate from beg of line 
	 to determine hpos of starting point */
      if (from > BEGV && FETCH_CHAR (from - 1) != '\n')
	{
	  prevline = find_next_newline (from, -1);
	  while (selective > 0
		 && prevline > BEGV
		 && position_indentation (prevline) >= selective)
	    prevline = find_next_newline (prevline - 1, -1);
	  pos = *compute_motion (prevline, 0,
				 lmargin + (prevline == 1 ? start_hpos : 0),
				 from, 10000,10000,
				 hscroll,0,XWINDOW(window),Qnil);
	}
      else
	{
	  pos.hpos = lmargin + (from == 1 ? start_hpos : 0);
	  pos.vpos = 0;
	}
      return compute_motion (from, vpos, pos.hpos,
			     ZV, vtarget, - (1 << (SHORTBITS - 1)),
			     hscroll,pos.vpos*width,XWINDOW(window),Qnil);
    }

  /* To move upward, go a line at a time until
     we have gone at least far enough */

  first = 1;

  while ((vpos > vtarget || first) && from > BEGV)
    {
      prevline = from;
      while (1)
	{
	  prevline = find_next_newline (prevline - 1, -1);
	  if (prevline == BEGV
	      || selective <= 0
	      || position_indentation (prevline) < selective)
	    break;
	}
      pos = *compute_motion (prevline, 0,
			     lmargin + (prevline == 1 ? start_hpos : 0),
			     from, 10000,10000,
			     hscroll,0,XWINDOW(window),Qnil);
      vpos -= pos.vpos;
      first = 0;
      from = prevline;
    }

  /* If we made exactly the desired vertical distance,
     or if we hit beginning of buffer,
     return point found */
  if (vpos >= vtarget)
    {
      val_vmotion.bufpos = from;
      val_vmotion.vpos = vpos;
      val_vmotion.hpos = lmargin;
      val_vmotion.contin = 0;
      val_vmotion.prevhpos = 0;
      return &val_vmotion;
    }
  
  /* Otherwise find the correct spot by moving down */
  goto retry;
}

DEFUN ("vertical-motion", Fvertical_motion, Svertical_motion, 1, 1, 0,
  "Move to start of screen line LINES lines down.\n\
If LINES is negative, this is moving up.\n\
Sets point to position found; this may be start of line\n\
 or just the start of a continuation line.\n\
Returns number of lines moved; may be closer to zero than LINES\n\
 if beginning or end of buffer was reached.")
  (lines)
     Lisp_Object lines;
{
  struct position pos;
  register struct window *w = XWINDOW (selected_window);

  CHECK_NUMBER (lines, 0);

  pos = *vmotion (point, XINT (lines),
		  XINT(w->hscroll),selected_window);

  SET_PT (pos.bufpos);
  return make_number (pos.vpos);
}

syms_of_indent ()
{
  DEFVAR_BOOL ("indent-tabs-mode", &indent_tabs_mode,
    "*Indentation can insert tabs if this is non-nil.\n\
Setting this variable automatically makes it local to the current buffer.");
  indent_tabs_mode = 1;

  defsubr (&Scurrent_indentation);
  defsubr (&Sindent_to);
  defsubr (&Scurrent_column);
  defsubr (&Scurrent_pixel);
  defsubr (&Smove_to_column);
  defsubr (&Smove_to_pixel);
  defsubr (&Stext_width);
  defsubr (&Svertical_motion);
}

