/*******************************************************************************
*									       
* TextDisp.cxx - Display text from a text buffer				       
*									       
* The code in this file is based on code that makes part of the NEdit Version
* 5.0.2 from Fermi National Accelator Laboratory, written by Mark Edel. See
* LICENSE.FERMI for details.
*
* Maarten de Boer 1999
*
*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include "TextBuffer.H"
#include "TextDisp.H"

#define TOP_MARGIN 1
#define BOTTOM_MARGIN 1
#define LEFT_MARGIN 3
#define RIGHT_MARGIN 3

/* Masks for text drawing methods.  These are or'd together to form an
   integer which describes what drawing calls to use to draw a string */
#define FILL_MASK 0x100
#define SECONDARY_MASK 0x200
#define PRIMARY_MASK 0x400
#define HIGHLIGHT_MASK 0x800
#define STYLE_LOOKUP_MASK 0xff

/* Maximum displayable line length (how many characters will fit across the
   widest window).  This amount of memory is temporarily allocated from the
   stack in the redisplayLine routine for drawing strings */
#define MAX_DISP_LINE_LEN 1000

#define FL_DAMAGE_RANGE 0x10
#define FL_DAMAGE_CURSORPROTRUSIONS 0x20
#define FL_DAMAGE_CURSOR 0x40

enum positionTypes {CURSOR_POS, CHARACTER_POS};

static int max( int i1, int i2 );
static int min( int i1, int i2 );
static int countLines( char *string );
static int rangeTouchesRectSel( Selection *sel, int rangeStart, int rangeEnd );

//static void TextDisp::allocateFixedFontGCs( XFontStruct *fontStruct,
//	Pixel bgPixel, Pixel fgPixel, Pixel selectFGPixel, Pixel selectBGPixel,
//	Pixel highlightFGPixel, Pixel highlightBGPixel);
//static GC allocateGC(Widget w, unsigned long valueMask,
//	unsigned long foreground, unsigned long background, Font font,
//	unsigned long dynamicMask, unsigned long dontCareMask);
//static void releaseGC(Widget w, GC gc);
/*textDisp *Create(Widget widget, Widget hScrollBar, Widget vScrollBar,
	Position left, Position top, Position width, Position height,
	TextBuffer *buffer, XFontStruct *fontStruct, Pixel bgPixel,
	Pixel fgPixel, Pixel selectFGPixel, Pixel selectBGPixel,
	Pixel highlightFGPixel, Pixel highlightBGPixel, Pixel cursorFGPixel,
	int continuousWrap, int wrapMargin)
*/

#define TMPFONTWIDTH 6 //!!!

TextDisp::TextDisp( Position left, Position top, Position width, Position height,
                    Fl_Scrollbar* hScrollBar, Fl_Scrollbar* vScrollBar,
                    TextBuffer *buffer,
                    int continuousWrap, int wrapMargin )
		: Fl_Widget( left, top, width, height )
{
	damage_range_start = 0;
	damage_range_end = 0;

	mLeft = left + LEFT_MARGIN;
	mTop = top + TOP_MARGIN;
	mWidth = width - LEFT_MARGIN - RIGHT_MARGIN;
	mHeight = height - TOP_MARGIN - BOTTOM_MARGIN;

	int i;

	mCursorOn = True;
	mCursorPos = 0;
	mCursorX = -100;
	mCursorY = -100;
	mCursorToHint = NO_HINT;
	mCursorStyle = NORMAL_CURSOR;
	mCursorPreferredCol = -1;
	mBuffer = buffer;
	mFirstChar = 0;
	mLastChar = 0;
	mNBufferLines = 0;
	mTopLineNum = 1;
	mHorizOffset = 0;
	//    mVisibility = VisibilityUnobscured;
	mHScrollBar = hScrollBar;
	mVScrollBar = vScrollBar;

	mTextfont = FL_COURIER;
	mMaxsize = mTextsize = 12;
	mTextcolor = FL_BLACK;

	mSelect_background = FL_GRAY;
	mSelect_foreground = FL_BLACK;

	mHighlight_background = FL_RED;
	mHighlight_foreground = FL_GREEN;

	mCursor_color = FL_BLACK;

	//    mAscent = fontStruct->ascent;
	//    mDescent = fontStruct->descent;
	mFixedFontWidth = TMPFONTWIDTH;    //fontStruct->min_bounds.width ==
	//    	    fontStruct->max_bounds.width ? fontStruct->min_bounds.width : -1;
	mStyleBuffer = NULL;
	mStyleTable = NULL;
	mNStyles = 0;
	//    color() = bgPixel;
	//    mSelectBGPixel = selectBGPixel;
	//    mHighlightBGPixel = highlightBGPixel;
	mWrapMargin = wrapMargin;
	mContinuousWrap = continuousWrap;
	//    allocateFixedFontGCs( fontStruct, bgPixel, fgPixel, selectFGPixel,
	//	    selectBGPixel, highlightFGPixel, highlightBGPixel);
	//    mStyleGC = allocateGC(mW, 0, 0, 0, fontStruct->fid,
	//    	    GCClipMask|GCForeground|GCBackground, GCArcMode);
	mNVisibleLines =
	    ( height - 1 ) / ( mMaxsize ) + 1;
	//    gcValues.foreground = cursorFGPixel;
	//    mCursorFGGC = XtGetGC(widget, GCForeground, &gcValues);
	mLineStarts = new int [ mNVisibleLines ];
	mLineStarts[ 0 ] = 0;
	for ( i = 1; i < mNVisibleLines; i++ )
		mLineStarts[ i ] = -1;

	/* Attach an event handler to the widget so we can know the visibility
	   (used for choosing the fastest drawing method) */
	//    XtAddEventHandler(widget, VisibilityChangeMask, False,
	//    	    visibilityEH, textD);

	/* Attach the callback to the text buffer for receiving modification
	   information */
	if ( buffer != NULL )
		buffer->AddModifyCB( bufModifiedCB, this );

	/* Initialize the scroll bars and attach movement callbacks */
	if ( vScrollBar != NULL )
	{
		/*	XtVaSetValues(vScrollBar, XmNminimum, 1, XmNmaximum, 2,
		    		XmNsliderSize, 1, XmNrepeatDelay, 10, XmNvalue, 1, 0);
			XtAddCallback(vScrollBar, XmNdragCallback, vScrollCB, (XtPointer)textD);
			XtAddCallback(vScrollBar, XmNvalueChangedCallback, vScrollCB, 
				(XtPointer)textD);
		*/
		vScrollBar->value( 1, 1, 1, 1 );
		vScrollBar->callback( ( Fl_Callback* ) vScrollCB, this );
	}
	if ( hScrollBar != NULL )
	{
		/*	XtVaSetValues(hScrollBar, XmNminimum, 0, XmNmaximum, 1,
		    		XmNsliderSize, 1, XmNrepeatDelay, 10, XmNvalue, 0,
		    		XmNincrement, fontStruct->max_bounds.width, 0);
			XtAddCallback(hScrollBar, XmNdragCallback, hScrollCB, (XtPointer)textD);
			XtAddCallback(hScrollBar, XmNvalueChangedCallback, hScrollCB,
				(XtPointer)textD);
		*/
		hScrollBar->value( 0, 1, 0, 1 );
		hScrollBar->callback( ( Fl_Callback* ) hScrollCB, this );
	}

	/* Update the display to reflect the contents of the buffer */
	if ( buffer != NULL )
		bufModifiedCB( 0, buffer->mLength, 0, 0, NULL, this );

	/* Decide if the horizontal scroll bar needs to be visible */
	hideOrShowHScrollBar();
}

/*
** Free a text display and release its associated memory.  Note, the text
** BUFFER that the text display displays is a separate entity and is not
** freed, nor are the style buffer or style table.
*/
TextDisp::~TextDisp()
{
	mBuffer->RemoveModifyCB( bufModifiedCB, this );
	/*    releaseGC(mW, mGc);
	    releaseGC(mW, mSelectGC);
	    releaseGC(mW, mHighlightGC);
	    releaseGC(mW, mSelectBGGC);
	    releaseGC(mW, mHighlightBGGC);
	    releaseGC(mW, mStyleGC);
	*/
	delete [] mLineStarts;
}

/*
** Attach a text buffer to display, replacing the current buffer (if any)
*/
void TextDisp::SetBuffer( TextBuffer *buffer )
{
	/* If the text display is already displaying a buffer, clear it off
	   of the display and remove our callback from it */
	if ( mBuffer != NULL )
	{
		bufModifiedCB( 0, 0, mBuffer->mLength, 0, NULL, this );
		mBuffer->RemoveModifyCB( bufModifiedCB, this );
	}

	/* Add the buffer to the display, and attach a callback to the buffer for
	   receiving modification information when the buffer contents change */
	mBuffer = buffer;
	mBuffer->AddModifyCB( bufModifiedCB, this );

	/* Update the display */
	bufModifiedCB( 0, buffer->mLength, 0, 0, NULL, this );
}

/*
** return the displayed text buffer
*/
TextBuffer *TextDisp::GetBuffer()
{
	return mBuffer;
}

/*
** Attach (or remove) highlight information in text display and redisplay.
** Highlighting information consists of a style buffer which parallels the
** normal text buffer, but codes font and color information for the display;
** a style table which translates style buffer codes (indexed by buffer
** character - 'A') into fonts and colors; and a callback mechanism for
** as-needed highlighting, triggered by a style buffer entry of
** "unfinishedStyle".  Style buffer can trigger additional redisplay during
** a normal buffer modification if the buffer contains a primary Selection
** (see extendRangeForStyleMods for more information on this protocol).
**
** Style buffers, tables and their associated memory are managed by the caller.
*/
void TextDisp::AttachHighlightData( TextBuffer *styleBuffer,
                                    styleTableEntry *styleTable, int nStyles, char unfinishedStyle,
                                    unfinishedStyleCBProc unfinishedHighlightCB, void *cbArg )
{
	mStyleBuffer = styleBuffer;
	mStyleTable = styleTable;
	mNStyles = nStyles;
	mUnfinishedStyle = unfinishedStyle;
	mUnfinishedHighlightCB = unfinishedHighlightCB;
	mHighlightCBArg = cbArg;

	/* Call SetFont to combine font information from style table and
	   primary font, adjust font-related parameters, and then redisplay */
	SetFont( mTextfont, mTextsize );
}

/*
** Change the (non highlight) font
*/
//void TextDisp::SetFont( XFontStruct *fontStruct)
void TextDisp::SetFont( Fl_Font font, int size )
{
	int i, maxsize = mTextsize;    //, maxAscent = fontStruct->ascent, maxDescent = fontStruct->descent;
	int width, height;    //!!!, fontWidth;

	blankCursorProtrusions();

	/* If there is a (syntax highlighting) style table in use, find the new
	   maximum font height for this text display */
	for ( i = 0; i < mNStyles; i++ )
	{
		if ( mStyleTable[ i ].size > maxsize )
			maxsize = mStyleTable[ i ].size;
	}
	mMaxsize = maxsize;

	/* If all of the current fonts are fixed and match in width, compute */
	/*
	    fontWidth = fontStruct->max_bounds.width;
	    if (fontWidth != fontStruct->min_bounds.width)
		fontWidth = -1;
	    else {
		for (i=0; i<mNStyles; i++) {
	    	    styleFont = mStyleTable[i].font;
		    if (styleFont->max_bounds.width != fontWidth ||
			    styleFont->max_bounds.width != styleFont->min_bounds.width)
			fontWidth = -1;
		}
	    }
	    mFixedFontWidth = fontWidth;
	*/

	/* Don't let the height dip below one line, or bad things can happen */

	/* Change the font.  In most cases, this means re-allocating the
	   affected GCs (they are shared with other widgets, and if the primary
	   font changes, must be re-allocated to change it). Unfortunately,
	   this requres recovering all of the colors from the existing GCs */
	/*
	    mFontStruct = fontStruct;
	    XGetGCValues(display, mGc, GCForeground|GCBackground, &values);
	    fgPixel = values.foreground;
	    bgPixel = values.background;
	    XGetGCValues(display, mSelectGC, GCForeground|GCBackground, &values);
	    selectFGPixel = values.foreground;
	    selectBGPixel = values.background;
	    XGetGCValues(display, mHighlightGC,GCForeground|GCBackground,&values);
	    highlightFGPixel = values.foreground;
	    highlightBGPixel = values.background;
	    releaseGC(mW, mGc);
	    releaseGC(mW, mSelectGC);
	    releaseGC(mW, mHighlightGC);
	    releaseGC(mW, mSelectBGGC);
	    releaseGC(mW, mHighlightBGGC);
	    allocateFixedFontGCs( fontStruct, bgPixel, fgPixel, selectFGPixel,
		    selectBGPixel, highlightFGPixel, highlightBGPixel);
	    XSetFont(display, mStyleGC, fontStruct->fid);
	*/
	/* Do a full resize to force recalculation of font related parameters */
	width = w();
	height = h();

	if ( height < mMaxsize )
		height = mMaxsize;

	Resize( width, height );

	/* Redisplay */
	RedisplayRect( x(), y(), w(), h() );
}

void TextDisp::resize( int X, int Y, int W, int H )
{
	mLeft = X + LEFT_MARGIN;
	mWidth = W - LEFT_MARGIN - RIGHT_MARGIN;
	mTop = Y + TOP_MARGIN;
	mHeight = H - TOP_MARGIN - BOTTOM_MARGIN;

	Resize_( W, H );
	Fl_Widget::resize( X, Y, W, H );
}


/*
** Change the size of the displayed text area
*/
void TextDisp::Resize_( int width, int height )
{
	int oldVisibleLines = mNVisibleLines;
	int canRedraw = visible();
	int newVisibleLines = height / ( mMaxsize );
	int redrawAll = False;
	int oldWidth = w();
	//    int exactHeight = height - height % (mMaxsize);

	/* In continuous wrap mode, a change in width affects the total number of
	   lines in the buffer, and can leave the top line number incorrect, and
	   the top character no longer pointing at a valid line start */
	if ( mContinuousWrap && mWrapMargin == 0 && width != oldWidth )
	{
		mNBufferLines = CountLines( 0, mBuffer->mLength,
		                            True );
		mFirstChar = StartOfLine( mFirstChar );
		mTopLineNum = CountLines( 0, mFirstChar, True ) + 1;
		redrawAll = True;
	}

	/* reallocate and update the line starts array, which may have changed
	   size and/or contents. (contents can change in continuous wrap mode
	   when the width changes, even without a change in height) */
	if ( oldVisibleLines < newVisibleLines )
	{
		delete [] mLineStarts;
		mLineStarts = new int [ newVisibleLines ];
	}
	mNVisibleLines = newVisibleLines;
	calcLineStarts( 0, newVisibleLines );
	calcLastChar();

	/* if the window became shorter, there may be partially drawn
	   text left at the bottom edge, which must be cleaned up */
	/*!!!
	    if (canRedraw && oldVisibleLines>newVisibleLines && exactHeight!=height) {
			fl_color(FL_WHITE);
	    	fl_rectf(x(),
	    		y() + exactHeight,  w(),
	    		height - exactHeight);
		}
	*/
	/* if the window became taller, there may be an opportunity to display
	   more text by scrolling down */
	if ( canRedraw && oldVisibleLines < newVisibleLines && mTopLineNum +
	        mNVisibleLines > mNBufferLines )
		setScroll( max( 1, mNBufferLines - mNVisibleLines + 2 ),
		           mHorizOffset, False, False );

	/* Update the scroll bar page increment size (as well as other scroll
	   bar parameters.  If updating the horizontal range caused scrolling,
	   redraw */
	updateVScrollBarRange();
	if ( updateHScrollBarRange() )
		redrawAll = True;

	/* If a full redraw is needed */
	if ( redrawAll && canRedraw )
		RedisplayRect( x(), y(), w(), h() );

	/* Decide if the horizontal scroll bar needs to be visible */
	hideOrShowHScrollBar();
}

void TextDisp::RedisplayRect( int left, int top, int width,
                              int height )
{
	//		printf("FL_DAMAGE_EXPOSE %d %d %d %d\n",left, top, width, height );
	damage( FL_DAMAGE_EXPOSE, left, top, width, height );
}

/*
** Refresh a rectangle of the text display.  left and top are in coordinates of
** the text drawing window
*/
void TextDisp::RedisplayRect_( int left, int top, int width,
                               int height )
{
	//		printf("RedisplayRect_ %d %d %d %d\n",left, top, width, height );
	int fontHeight, firstLine, lastLine, line;

	/* find the line number range of the display */
	fontHeight = mMaxsize;
	firstLine = ( top - mTop - fontHeight + 1 ) / fontHeight;
	lastLine = ( top + height - mTop ) / fontHeight;

	/* If the graphics contexts are shared using XtAllocateGC, their
	   clipping rectangles may have changed since the last use */

	//    resetClipRectangles();

	if ( left < mLeft ) left = mLeft;
	if ( top < mTop ) top = mTop;
	if ( width > mWidth ) width = mWidth;
	if ( height > mHeight ) height = mHeight;

	fl_push_clip( left, top, width, height );

	/* draw the lines */
	for ( line = firstLine; line <= lastLine; line++ )
		redisplayLine( line, left, left + width, 0, INT_MAX );

	fl_pop_clip();
}

void TextDisp::RedisplayRange( int start, int end )
{
	if ( damage_range_start == 0 && damage_range_end == 0 )
	{
		damage_range_start = start;
		damage_range_end = end;
	}
	else
	{
		damage_range_start = min( damage_range_start, start );
		damage_range_end = max( damage_range_end, end );
	}
	damage( FL_DAMAGE_RANGE );
	//		printf("FL_DAMAGE_RANGE %d %d\n",damage_range_start,damage_range_end);
}
/*
** Refresh all of the text between buffer positions "start" and "end"
** not including the character at the position "end".
** If end points beyond the end of the buffer, refresh the whole display
** after pos, including blank lines which are not technically part of
** any range of characters.
*/
void TextDisp::RedisplayRange_( int start, int end )
{
	//		printf("RedisplayRange %d %d\n",damage_range_start,damage_range_end);
	int i, startLine, lastLine, startIndex, endIndex;

	/* If the range is outside of the displayed text, just return */
	if ( end < mFirstChar || ( start > mLastChar &&
	                           !emptyLinesVisible() ) )
		return ;

	fl_push_clip( mLeft, mTop, mWidth, mHeight );

	/* Clean up the starting and ending values */
	if ( start < 0 ) start = 0;
	if ( start > mBuffer->mLength ) start = mBuffer->mLength;
	if ( end < 0 ) end = 0;
	if ( end > mBuffer->mLength ) end = mBuffer->mLength;

	/* Get the starting and ending lines */
	if ( start < mFirstChar )
		start = mFirstChar;
	if ( !posToVisibleLineNum( start, &startLine ) )
		startLine = mNVisibleLines - 1;
	if ( end >= mLastChar )
	{
		lastLine = mNVisibleLines - 1;
	}
	else
	{
		if ( !posToVisibleLineNum( end, &lastLine ) )
		{
			/* shouldn't happen */
			lastLine = mNVisibleLines - 1;
		}
	}

	/* Get the starting and ending positions within the lines */
	startIndex = mLineStarts[ startLine ] == -1 ? 0 :
	             start - mLineStarts[ startLine ];
	if ( end >= mLastChar )
		endIndex = INT_MAX;
	else if ( mLineStarts[ lastLine ] == -1 )
		endIndex = 0;
	else
		endIndex = end - mLineStarts[ lastLine ];

	/* Reset the clipping rectangles for the drawing GCs which are shared
	   using XtAllocateGC, and may have changed since the last use */

	//    resetClipRectangles();

	/* If the starting and ending lines are the same, redisplay the single
	   line between "start" and "end" */
	if ( startLine == lastLine )
	{
		redisplayLine( startLine, 0, INT_MAX, startIndex, endIndex );
		fl_pop_clip();
		return ;
	}

	/* Redisplay the first line from "start" */
	redisplayLine( startLine, 0, INT_MAX, startIndex, INT_MAX );

	/* Redisplay the lines in between at their full width */
	for ( i = startLine + 1; i < lastLine; i++ )
		redisplayLine( i, 0, INT_MAX, 0, INT_MAX );

	/* Redisplay the last line to "end" */
	redisplayLine( lastLine, 0, INT_MAX, 0, endIndex );

	fl_pop_clip();
}

/*
** Set the scroll position of the text display vertically by line number and
** horizontally by pixel offset from the left margin
*/
void TextDisp::SetScroll( int topLineNum, int horizOffset )
{
	int sliderSize, sliderMax;

	/* Limit the requested scroll position to allowable values */
	if ( topLineNum < 1 )
		topLineNum = 1;
	else if ( topLineNum > mTopLineNum &&
	          topLineNum > mNBufferLines + 2 - mNVisibleLines )
		topLineNum = max( mTopLineNum,
		                  mNBufferLines + 2 - mNVisibleLines );
	//    XtVaGetValues(mHScrollBar, XmNmaximum, &sliderMax,
	//    	    XmNsliderSize, &sliderSize, 0);
	sliderMax = ( int ) mHScrollBar->maximum();
	sliderSize = ( int ) ( mHScrollBar->slider_size() * ( float ) sliderMax );

	if ( horizOffset < 0 )
		horizOffset = 0;
	if ( horizOffset > sliderMax - sliderSize )
		horizOffset = sliderMax - sliderSize;

	setScroll( topLineNum, horizOffset, True, True );
}

/*
** Get the current scroll position for the text display, in terms of line
** number of the top line and horizontal pixel offset from the left margin
*/
void TextDisp::GetScroll( int *topLineNum, int *horizOffset )
{
	*topLineNum = mTopLineNum;
	*horizOffset = mHorizOffset;
}

/*
** Set the position of the text insertion cursor for text display "textD"
*/
void TextDisp::SetInsertPosition( int newPos )
{
	/* make sure new position is ok, do nothing if it hasn't changed */
	if ( newPos == mCursorPos )
		return ;
	if ( newPos < 0 ) newPos = 0;
	if ( newPos > mBuffer->mLength ) newPos = mBuffer->mLength;

	/* cursor movement cancels vertical cursor motion column */
	mCursorPreferredCol = -1;

	/* erase the cursor at it's previous position */
	BlankCursor();

	/* draw it at its new position */
	mCursorPos = newPos;
	mCursorOn = True;
	RedisplayRange( mCursorPos, mCursorPos + 1 );
}

void TextDisp::BlankCursor()
{
	if ( !mCursorOn )
		return ;
	blankCursorProtrusions();
	mCursorOn = False;
	RedisplayRange( mCursorPos - 1, mCursorPos + 1 );
}

void TextDisp::UnblankCursor()
{
	if ( !mCursorOn )
	{
		mCursorOn = True;
		RedisplayRange( mCursorPos - 1, mCursorPos + 1 );
	}
}

void TextDisp::SetCursorStyle( int style )
{
	mCursorStyle = style;
	blankCursorProtrusions();
	if ( mCursorOn )
		RedisplayRange( mCursorPos - 1, mCursorPos + 1 );
}

void TextDisp::SetWrapMode( int wrap, int wrapMargin )
{
	mWrapMargin = wrapMargin;
	mContinuousWrap = wrap;

	/* wrapping can change change the total number of lines, re-count */
	mNBufferLines = CountLines( 0, mBuffer->mLength, True );

	/* changing wrap margins wrap or changing from wrapped mode to non-wrapped
	   can leave the character at the top no longer at a line start, and/or
	   change the line number */
	mFirstChar = StartOfLine( mFirstChar );
	mTopLineNum = CountLines( 0, mFirstChar, True ) + 1;

	/* update the line starts array */
	calcLineStarts( 0, mNVisibleLines );
	calcLastChar();

	/* Update the scroll bar page increment size (as well as other scroll
	   bar parameters) */
	updateVScrollBarRange();
	updateHScrollBarRange();

	/* Decide if the horizontal scroll bar needs to be visible */
	hideOrShowHScrollBar();

	/* Do a full redraw */
	RedisplayRect( x(), y(), w(), h() );
}

int TextDisp::GetInsertPosition()
{
	return mCursorPos;
}

/*
** Insert "text" at the current cursor location.  This has the same
** effect as inserting the text into the buffer using BufInsert and
** then moving the insert position after the newly inserted text, except
** that it's optimized to do less redrawing.
*/
void TextDisp::Insert( const char *text )
{
	int pos = mCursorPos;

	mCursorToHint = pos + strlen( text );
	mBuffer->Insert( pos, text );
	mCursorToHint = NO_HINT;
}

/*
** Insert "text" (which must not contain newlines), overstriking the current
** cursor location.
*/
void TextDisp::Overstrike( const char *text )
{
	int startPos = mCursorPos;
	TextBuffer *buf = mBuffer;
	int lineStart = buf->StartOfLine( startPos );
	int textLen = strlen( text );
	int i, p, endPos, indent, startIndent, endIndent;
	const char *c;
	char ch, *paddedText = NULL;

	/* determine how many displayed character positions are covered */
	startIndent = mBuffer->CountDispChars( lineStart, startPos );
	indent = startIndent;
	for ( c = text; *c != '\0'; c++ )
		indent += TextBuffer::CharWidth( *c, indent, buf->mTabDist, buf->mNullSubsChar );
	endIndent = indent;

	/* find which characters to remove, and if necessary generate additional
	   padding to make up for removed control characters at the end */
	indent = startIndent;
	for ( p = startPos; ; p++ )
	{
		if ( p == buf->mLength )
			break;
		ch = buf->GetCharacter( p );
		if ( ch == '\n' )
			break;
		indent += TextBuffer::CharWidth( ch, indent, buf->mTabDist, buf->mNullSubsChar );
		if ( indent == endIndent )
		{
			p++;
			break;
		}
		else if ( indent > endIndent )
		{
			if ( ch != '\t' )
			{
				p++;
				paddedText = new char [ textLen + MAX_EXP_CHAR_LEN + 1 ];
				strcpy( paddedText, text );
				for ( i = 0; i < indent - endIndent; i++ )
					paddedText[ textLen + i ] = ' ';
				paddedText[ textLen + i ] = '\0';
			}
			break;
		}
	}
	endPos = p;

	mCursorToHint = startPos + textLen;
	buf->Replace( startPos, endPos, paddedText == NULL ? text : paddedText );
	mCursorToHint = NO_HINT;
	if ( paddedText != NULL )
		delete [] paddedText;
}

/*
** Translate window coordinates to the nearest (insert cursor) text position.
*/
int TextDisp::XYToPosition( int X, int Y )
{
	return xyToPos( X, Y, CURSOR_POS );
}

/*
** Translate window coordinates to the nearest row and column number for
** positioning the cursor.  This, of course, makes no sense when the font
** is proportional, since there are no absolute columns.
*/
void TextDisp::XYToUnconstrainedPosition( int X, int Y, int *row,
        int *column )
{
	xyToUnconstrainedPos( X, Y, row, column, CURSOR_POS );
}

/*
** Translate a buffer text position to the XY location where the center
** of the cursor would be positioned to point to that character.  Returns
** False if the position is not displayed because it is VERTICALLY out
** of view.  If the position is horizontally out of view, returns the
** X coordinate where the position would be if it were visible.
*/
int TextDisp::PositionToXY( int pos, int *X, int *Y )
{
	int charIndex, lineStartPos, fontHeight, lineLen;
	int visLineNum, charLen, outIndex, xStep, charStyle;
	char *lineStr, expandedChar[ MAX_EXP_CHAR_LEN ];

	/* If position is not displayed, return false */
	if ( pos < mFirstChar ||
	        ( pos > mLastChar && !emptyLinesVisible() ) )
		return False;

	/* Calculate Y coordinate */
	if ( !posToVisibleLineNum( pos, &visLineNum ) )
		return False;
	fontHeight = mMaxsize;
	*X = mTop + visLineNum * fontHeight + fontHeight / 2;

	/* Get the text, length, and  buffer position of the line. If the position
	   is beyond the end of the buffer and should be at the first position on
	   the first empty line, don't try to get or scan the text  */
	lineStartPos = mLineStarts[ visLineNum ];
	if ( lineStartPos == -1 )
	{
		*Y = mLeft - mHorizOffset;
		return True;
	}
	lineLen = visLineLength( visLineNum );
	lineStr = mBuffer->GetRange( lineStartPos, lineStartPos + lineLen );

	/* Step through character positions from the beginning of the line
	   to "pos" to calculate the X coordinate */
	xStep = mLeft - mHorizOffset;
	outIndex = 0;
	for ( charIndex = 0; charIndex < pos - lineStartPos; charIndex++ )
	{
		charLen = TextBuffer::ExpandCharacter( lineStr[ charIndex ], outIndex, expandedChar,
		                                       mBuffer->mTabDist, mBuffer->mNullSubsChar );
		charStyle = styleOfPos( lineStartPos, lineLen, charIndex,
		                        outIndex );
		xStep += stringWidth( expandedChar, charLen, charStyle );
		outIndex += charLen;
	}
	*X = xStep;
	delete [] lineStr;
	return True;
}

/*
** Find the line number of position "pos".  Note: this only works for
** displayed lines.  If the line is not displayed, the function returns
** False (without the lineStarts array it could turn in to very long
** calculation involving scanning large amounts of text in the buffer).
*/
int TextDisp::PosToLineAndCol( int pos, int *lineNum, int *column )
{
	int retVal;

	retVal = posToVisibleLineNum( pos, lineNum );
	if ( retVal )
	{
		*column = mBuffer->CountDispChars(
		              mLineStarts[ *lineNum ], pos );
		*lineNum += mTopLineNum;
	}
	return retVal;
}

/*
** Return True if position (X, Y) is inside of the primary Selection
*/
int TextDisp::InSelection( int X, int Y )
{
	int row, column, pos = xyToPos( X, Y, CHARACTER_POS );
	TextBuffer *buf = mBuffer;

	xyToUnconstrainedPos( X, Y, &row, &column, CHARACTER_POS );
	if ( rangeTouchesRectSel( &buf->mPrimary, mFirstChar, mLastChar ) )
		column = OffsetWrappedColumn( row, column );
	return inSelection( &buf->mPrimary, pos, buf->StartOfLine( pos ), column );
}

/*
** Correct a column number based on an unconstrained position (as returned by
** XYToUnconstrainedPosition) to be relative to the last actual newline
** in the buffer before the row and column position given, rather than the
** last line start created by line wrapping.  This is an adapter
** for rectangular Selections and code written before continuous wrap mode,
** which thinks that the unconstrained column is the number of characters
** from the last newline.  Obviously this is time consuming, because it
** invloves character re-counting.
*/
int TextDisp::OffsetWrappedColumn( int row, int column )
{
	int lineStart, dispLineStart;

	if ( !mContinuousWrap || row < 0 || row > mNVisibleLines )
		return column;
	dispLineStart = mLineStarts[ row ];
	if ( dispLineStart == -1 )
		return column;
	lineStart = mBuffer->StartOfLine( dispLineStart );
	return column + mBuffer->CountDispChars( lineStart, dispLineStart );
}

/*
** Correct a row number from an unconstrained position (as returned by
** XYToUnconstrainedPosition) to a straight number of newlines from the
** top line of the display.  Because rectangular Selections are based on
** newlines, rather than display wrapping, and anywhere a rectangular Selection
** needs a row, it needs it in terms of un-wrapped lines.
*/
int TextDisp::OffsetWrappedRow( int row )
{
	if ( !mContinuousWrap || row < 0 || row > mNVisibleLines )
		return row;
	return mBuffer->CountLines( mFirstChar,
	                            mLineStarts[ row ] );
}

/*
** Scroll the display to bring insertion cursor into view.
**
** Note: it would be nice to be able to do this without counting lines twice
** (setScroll counts them too) and/or to count from the most efficient
** starting point, but the efficiency of this routine is not as important to
** the overall performance of the text display.
*/
void TextDisp::MakeInsertPosVisible()
{
	int hOffset, topLine, X, Y;
	int cursorPos = mCursorPos;

	hOffset = mHorizOffset;
	topLine = mTopLineNum;

	/* Find the new top line number */
	if ( cursorPos < mFirstChar )
		topLine -= CountLines( cursorPos, mFirstChar, False );
	else if ( cursorPos > mLastChar && !emptyLinesVisible() )
	{
		topLine += CountLines( mLastChar -
		                       ( wrapUsesCharacter( mLastChar ) ? 0 : 1 ),
		                       cursorPos, False );
	}
	else if ( cursorPos == mLastChar && !emptyLinesVisible() &&
	          !wrapUsesCharacter( mLastChar ) )
		topLine++;
	if ( topLine < 1 )
	{
		fprintf( stderr, "internal consistency check tl1 failed\n" );
		topLine = 1;
	}

	/* Find the new setting for horizontal offset (this is a bit ungraceful).
	   If the line is visible, just use PositionToXY to get the position
	   to scroll to, otherwise, do the vertical scrolling first, then the
	   horizontal */
	if ( !PositionToXY( cursorPos, &X, &Y ) )
	{
		setScroll( topLine, hOffset, True, True );
		if ( !PositionToXY( cursorPos, &X, &Y ) )
			return ;    /* Give up, it's not worth it (but why does it fail?) */
	}
	if ( X > mLeft + mWidth )
		hOffset += X - ( mLeft + mWidth );
	else if ( X < mLeft )
		hOffset += X - mLeft;

	/* Do the scroll */
	setScroll( topLine, hOffset, True, True );
}

/*
** Cursor movement functions
*/
int TextDisp::MoveRight()
{
	if ( mCursorPos >= mBuffer->mLength )
		return False;
	SetInsertPosition( mCursorPos + 1 );
	return True;
}

int TextDisp::MoveLeft()
{
	if ( mCursorPos <= 0 )
		return False;
	SetInsertPosition( mCursorPos - 1 );
	return True;
}

int TextDisp::MoveUp()
{
	int lineStartPos, column, prevLineStartPos, newPos, visLineNum;

	/* Find the position of the start of the line.  Use the line starts array
	   if possible, to avoid unbounded line-counting in continuous wrap mode */
	if ( posToVisibleLineNum( mCursorPos, &visLineNum ) )
		lineStartPos = mLineStarts[ visLineNum ];
	else
	{
		lineStartPos = StartOfLine( mCursorPos );
		visLineNum = -1;
	}
	if ( lineStartPos == 0 )
		return False;

	/* Decide what column to move to, if there's a preferred column use that */
	column = mCursorPreferredCol >= 0 ? mCursorPreferredCol :
	         mBuffer->CountDispChars( lineStartPos, mCursorPos );

	/* count forward from the start of the previous line to reach the column */
	if ( visLineNum != -1 && visLineNum != 0 )
		prevLineStartPos = mLineStarts[ visLineNum - 1 ];
	else
		prevLineStartPos = CountBackwardNLines( lineStartPos, 1 );
	newPos = mBuffer->CountForwardDispChars( prevLineStartPos, column );
	if ( mContinuousWrap )
		newPos = min( newPos, EndOfLine( prevLineStartPos, True ) );

	/* move the cursor */
	SetInsertPosition( newPos );

	/* if a preferred column wasn't aleady established, establish it */
	mCursorPreferredCol = column;
	return True;
}
int TextDisp::MoveDown()
{
	int lineStartPos, column, nextLineStartPos, newPos, visLineNum;

	if ( mCursorPos == mBuffer->mLength )
		return False;
	if ( posToVisibleLineNum( mCursorPos, &visLineNum ) )
		lineStartPos = mLineStarts[ visLineNum ];
	else
	{
		lineStartPos = StartOfLine( mCursorPos );
		visLineNum = -1;
	}
	column = mCursorPreferredCol >= 0 ? mCursorPreferredCol :
	         mBuffer->CountDispChars( lineStartPos, mCursorPos );
	nextLineStartPos = CountForwardNLines( lineStartPos, 1, True );
	newPos = mBuffer->CountForwardDispChars( nextLineStartPos, column );
	if ( mContinuousWrap )
		newPos = min( newPos, EndOfLine( nextLineStartPos, True ) );
	SetInsertPosition( newPos );
	mCursorPreferredCol = column;
	return True;
}

/*
** Same as BufCountLines, but takes in to account wrapping if wrapping is
** turned on.  If the caller knows that startPos is at a line start, it
** can pass "startPosIsLineStart" as True to make the call more efficient
** by avoiding the additional step of scanning back to the last newline.
*/
int TextDisp::CountLines( int startPos, int endPos,
                          int startPosIsLineStart )
{
	int retLines, retPos, retLineStart, retLineEnd;

	/* If we're not wrapping use simple (and more efficient) BufCountLines */
	if ( !mContinuousWrap )
		return mBuffer->CountLines( startPos, endPos );

	wrappedLineCounter( mBuffer, startPos, endPos, INT_MAX,
	                    startPosIsLineStart, &retPos, &retLines, &retLineStart, &retLineEnd );
	return retLines;
}

/*
** Same as BufCountForwardNLines, but takes in to account line breaks when
** wrapping is turned on. If the caller knows that startPos is at a line start,
** it can pass "startPosIsLineStart" as True to make the call more efficient
** by avoiding the additional step of scanning back to the last newline.
*/
int TextDisp::CountForwardNLines( int startPos, int nLines,
                                  int startPosIsLineStart )
{
	int retLines, retPos, retLineStart, retLineEnd;

	/* if we're not wrapping use more efficient BufCountForwardNLines */
	if ( !mContinuousWrap )
		return mBuffer->CountForwardNLines( startPos, nLines );

	/* wrappedLineCounter can't handle the 0 lines case */
	if ( nLines == 0 )
		return startPos;

	/* use the common line counting routine to count forward */
	wrappedLineCounter( mBuffer, startPos, mBuffer->mLength,
	                    nLines, startPosIsLineStart, &retPos, &retLines, &retLineStart,
	                    &retLineEnd );
	return retPos;
}

/*
** Same as BufEndOfLine, but takes in to account line breaks when wrapping
** is turned on.  If the caller knows that startPos is at a line start, it
** can pass "startPosIsLineStart" as True to make the call more efficient
** by avoiding the additional step of scanning back to the last newline.
**
** Note that the definition of the end of a line is less clear when continuous
** wrap is on.  With continuous wrap off, it's just a pointer to the newline
** that ends the line.  When it's on, it's the character beyond the last
** DISPLAYABLE character on the line, where a whitespace character which has
** been "converted" to a newline for wrapping is not considered displayable.
** Also note that, a line can be wrapped at a non-whitespace character if the
** line had no whitespace.  In this case, this routine returns a pointer to
** the start of the next line.  This is also consistent with the model used by
** visLineLength.
*/
int TextDisp::EndOfLine( int pos, int startPosIsLineStart )
{
	int retLines, retPos, retLineStart, retLineEnd;

	/* If we're not wrapping use more efficien BufEndOfLine */
	if ( !mContinuousWrap )
		return mBuffer->EndOfLine( pos );

	if ( pos == mBuffer->mLength )
		return pos;
	wrappedLineCounter( mBuffer, pos, mBuffer->mLength, 1,
	                    startPosIsLineStart, &retPos, &retLines, &retLineStart, &retLineEnd );
	return retLineEnd;
}

/*
** Same as BufStartOfLine, but returns the character after last wrap point
** rather than the last newline.
*/
int TextDisp::StartOfLine( int pos )
{
	int retLines, retPos, retLineStart, retLineEnd;

	/* If we're not wrapping, use the more efficient BufStartOfLine */
	if ( !mContinuousWrap )
		return mBuffer->StartOfLine( pos );

	wrappedLineCounter( mBuffer, mBuffer->StartOfLine( pos ),
	                    pos, INT_MAX, True, &retPos, &retLines, &retLineStart, &retLineEnd );
	return retLineStart;
}

/*
** Same as BufCountBackwardNLines, but takes in to account line breaks when
** wrapping is turned on.
*/
int TextDisp::CountBackwardNLines( int startPos, int nLines )
{
	TextBuffer * buf = mBuffer;
	int pos, lineStart, retLines, retPos, retLineStart, retLineEnd;

	/* If we're not wrapping, use the more efficient BufCountBackwardNLines */
	if ( !mContinuousWrap )
		return mBuffer->CountBackwardNLines( startPos, nLines );

	pos = startPos;
	while ( True )
	{
		lineStart = buf->StartOfLine( pos );
		wrappedLineCounter( mBuffer, lineStart, pos, INT_MAX,
		                    True, &retPos, &retLines, &retLineStart, &retLineEnd );
		if ( retLines > nLines )
			return CountForwardNLines( lineStart, retLines - nLines,
			                           True );
		nLines -= retLines;
		pos = lineStart - 1;
		if ( pos <= 0 )
			return 0;
		nLines -= 1;
	}
}

/*
** Callback attached to the text buffer to receive modification information
*/
void TextDisp::bufModifiedCB( int pos, int nInserted, int nDeleted,
                              int nRestyled, char *deletedText, void *cbArg )
{
	int linesInserted, linesDeleted, startDispPos, endDispPos;
	TextDisp *textD = ( TextDisp * ) cbArg;
	TextBuffer *buf = textD->mBuffer;
	int scrolled, origCursorPos = textD->mCursorPos;
	int wrapModStart, wrapModEnd;

	/* buffer modification cancels vertical cursor motion column */
	if ( nInserted != 0 || nDeleted != 0 )
		textD->mCursorPreferredCol = -1;

	/* Count the number of lines inserted and deleted, and in the case
	   of continuous wrap mode, how much has changed */
	if ( textD->mContinuousWrap )
	{
		textD->findWrapRange( deletedText, pos, nInserted, nDeleted,
		                      &wrapModStart, &wrapModEnd, &linesInserted, &linesDeleted );
	}
	else
	{
		linesInserted = nInserted == 0 ? 0 :
		                buf->CountLines( pos, pos + nInserted );
		linesDeleted = nDeleted == 0 ? 0 : countLines( deletedText );
	}

	/* Update the line starts and topLineNum */
	if ( nInserted != 0 || nDeleted != 0 )
	{
		if ( textD->mContinuousWrap )
		{
			textD->updateLineStarts( wrapModStart, wrapModEnd - wrapModStart,
			                         nDeleted + pos - wrapModStart + ( wrapModEnd - ( pos + nInserted ) ),
			                         linesInserted, linesDeleted, &scrolled );
		}
		else
		{
			textD->updateLineStarts( pos, nInserted, nDeleted, linesInserted,
			                         linesDeleted, &scrolled );
		}
	}
	else
		scrolled = False;

	/* Update the line count for the whole buffer */
	textD->mNBufferLines += linesInserted - linesDeleted;

	/* Update the scroll bar ranges (and value if the value changed).  Note
	   that updating the horizontal scroll bar range requires scanning the
	   entire displayed text, however, it doesn't seem to hurt performance
	   much.  Note also, that the horizontal scroll bar update routine is
	   allowed to re-adjust horizOffset if there is blank space to the right
	   of all lines of text. */
	textD->updateVScrollBarRange();
	scrolled |= textD->updateHScrollBarRange();

	/* Update the cursor position */
	if ( textD->mCursorToHint != NO_HINT )
	{
		textD->mCursorPos = textD->mCursorToHint;
		textD->mCursorToHint = NO_HINT;
	}
	else if ( textD->mCursorPos > pos )
	{
		if ( textD->mCursorPos < pos + nDeleted )
			textD->mCursorPos = pos;
		else
			textD->mCursorPos += nInserted - nDeleted;
	}

	/* If the changes caused scrolling, re-paint everything and we're done. */
	if ( scrolled )
	{
		textD->blankCursorProtrusions();
		textD->RedisplayRect( textD->x(), textD->y(), textD->w(),
		                      textD->h() );
		if ( textD->mStyleBuffer )    /* See comments in extendRangeForStyleMods */
			textD->mStyleBuffer->mPrimary.mSelected = False;
		return ;
	}

	/* If the changes didn't cause scrolling, decide the range of characters
	   that need to be re-painted.  Also if the cursor position moved, be
	   sure that the redisplay range covers the old cursor position so the
	   old cursor gets erased, and erase the bits of the cursor which extend
	   beyond the left and right edges of the text. */
	startDispPos = textD->mContinuousWrap ? wrapModStart : pos;
	if ( origCursorPos == startDispPos && textD->mCursorPos != startDispPos )
		startDispPos = min( startDispPos, origCursorPos - 1 );
	if ( linesInserted == linesDeleted )
	{
		if ( nInserted == 0 && nDeleted == 0 )
			endDispPos = pos + nRestyled;
		else
		{
			endDispPos = textD->mContinuousWrap ? wrapModEnd :
			             buf->EndOfLine( pos + nInserted ) + 1;
			if ( origCursorPos >= startDispPos &&
			        ( origCursorPos <= endDispPos || endDispPos == buf->mLength ) )
				textD->blankCursorProtrusions();
		}
	}
	else
	{
		endDispPos = textD->mLastChar + 1;
		if ( origCursorPos >= pos )
			textD->blankCursorProtrusions();
	}

	/* If there is a style buffer, check if the modification caused additional
	   changes that need to be redisplayed.  (Redisplaying separately would
	   cause double-redraw on almost every modification involving styled
	   text).  Extend the redraw range to incorporate style changes */
	if ( textD->mStyleBuffer )
		textD->extendRangeForStyleMods( &startDispPos, &endDispPos );

	/* Redisplay computed range */
	textD->RedisplayRange( startDispPos, endDispPos );
}

/*
** Find the line number of position "pos" relative to the first line of
** displayed text. Returns False if the line is not displayed.
*/
int TextDisp::posToVisibleLineNum( int pos, int *lineNum )
{
	int i;

	if ( pos < mFirstChar )
		return False;
	if ( pos > mLastChar )
	{
		if ( emptyLinesVisible() )
		{
			if ( mLastChar < mBuffer->mLength )
			{
				if ( !posToVisibleLineNum( mLastChar, lineNum ) )
				{
					fprintf( stderr, "Consistency check ptvl failed\n" );
					return False;
				}
				return ++( *lineNum ) <= mNVisibleLines - 1;
			}
			else
			{
				posToVisibleLineNum( mLastChar - 1, lineNum );
				return True;
			}
		}
		return False;
	}

	for ( i = mNVisibleLines - 1; i >= 0; i-- )
	{
		if ( mLineStarts[ i ] != -1 && pos >= mLineStarts[ i ] )
		{
			*lineNum = i;
			return True;
		}
	}
	return False;    /* probably never be reached */
}

/*
** Redisplay the text on a single line represented by "visLineNum" (the
** number of lines down from the top of the display), limited by
** "leftClip" and "rightClip" window coordinates and "leftCharIndex" and
** "rightCharIndex" character positions (not including the character at
** position "rightCharIndex").
**
** The cursor is also drawn if it appears on the line.
*/
void TextDisp::redisplayLine( int visLineNum, int leftClip,
                              int rightClip, int leftCharIndex, int rightCharIndex )
{
	TextBuffer * buf = mBuffer;
	int i, X, Y, startX, charIndex, lineStartPos, lineLen, fontHeight;
	int stdCharWidth, charWidth, startIndex, charStyle, style;
	int charLen, outStartIndex, outIndex, cursorX, hasCursor = False;
	int dispIndexOffset, cursorPos = mCursorPos;
	char expandedChar[ MAX_EXP_CHAR_LEN ], outStr[ MAX_DISP_LINE_LEN ];
	char *lineStr, *outPtr;

	/* If line is not displayed, skip it */
	if ( visLineNum < 0 || visLineNum >= mNVisibleLines )
		return ;

	/* Calculate Y coordinate of the string to draw */
	fontHeight = mMaxsize;
	Y = mTop + visLineNum * fontHeight;

	/* Get the text, length, and  buffer position of the line to display */
	lineStartPos = mLineStarts[ visLineNum ];
	if ( lineStartPos == -1 )
	{
		lineLen = 0;
		lineStr = NULL;
	}
	else
	{
		lineLen = visLineLength( visLineNum );
		lineStr = buf->GetRange( lineStartPos, lineStartPos + lineLen );
	}

	/* Space beyond the end of the line is still counted in units of characters
	   of a standardized character width (this is done mostly because style
	   changes based on character position can still occur in this region due
	   to rectangular Selections).  stdCharWidth must be non-zero to prevent a
	   potential infinite loop if X does not advance */
	stdCharWidth = TMPFONTWIDTH;    //mFontStruct->max_bounds.width;
	if ( stdCharWidth <= 0 )
	{
		fprintf( stderr, "Internal Error, bad font measurement\n" );
		delete [] lineStr;
		return ;
	}

	/* Shrink the clipping range to the active display area */
	leftClip = max( x(), leftClip );
	rightClip = min( rightClip, x() + w() );

	/* Rectangular Selections are based on "real" line starts (after a newline
	   or start of buffer).  Calculate the difference between the last newline
	   position and the line start we're using.  Since scanning back to find a
	   newline is expensive, only do so if there's actually a rectangular
	   Selection which needs it */
	if ( mContinuousWrap && ( rangeTouchesRectSel( &buf->mPrimary,
	                          lineStartPos, lineStartPos + lineLen ) || rangeTouchesRectSel(
	                              &buf->mSecondary, lineStartPos, lineStartPos + lineLen ) ||
	                          rangeTouchesRectSel( &buf->mHighlight, lineStartPos,
	                                               lineStartPos + lineLen ) ) )
	{
		dispIndexOffset = buf->CountDispChars(
		                      buf->StartOfLine( lineStartPos ), lineStartPos );
	}
	else
		dispIndexOffset = 0;

	/* Step through character positions from the beginning of the line (even if
	   that's off the left edge of the displayed area) to find the first
	   character position that's not clipped, and the X coordinate for drawing
	   that character */
	X = mLeft - mHorizOffset;
	outIndex = 0;
	for ( charIndex = 0; ; charIndex++ )
	{
		charLen = charIndex >= lineLen ? 1 :
		          TextBuffer::ExpandCharacter( lineStr[ charIndex ], outIndex,
		                                       expandedChar, buf->mTabDist, buf->mNullSubsChar );
		style = styleOfPos( lineStartPos, lineLen, charIndex,
		                    outIndex + dispIndexOffset );
		charWidth = charIndex >= lineLen ? stdCharWidth :
		            stringWidth( expandedChar, charLen, style );
		if ( X + charWidth >= leftClip && charIndex >= leftCharIndex )
		{
			startIndex = charIndex;
			outStartIndex = outIndex;
			startX = X;
			break;
		}
		X += charWidth;
		outIndex += charLen;
	}

	/* Scan character positions from the beginning of the clipping range, and
	   draw parts whenever the style changes (also note if the cursor is on
	   this line, and where it should be drawn to take advantage of the x
	   position which we've gone to so much trouble to calculate) */
	outPtr = outStr;
	outIndex = outStartIndex;
	X = startX;
	for ( charIndex = startIndex; charIndex < rightCharIndex; charIndex++ )
	{
		if ( lineStartPos + charIndex == cursorPos )
		{
			if ( charIndex < lineLen || ( charIndex == lineLen &&
			                              cursorPos >= buf->mLength ) )
			{
				hasCursor = True;
				cursorX = X - 1;
			}
			else if ( charIndex == lineLen )
			{
				if ( wrapUsesCharacter( cursorPos ) )
				{
					hasCursor = True;
					cursorX = X - 1;
				}
			}
		}
		charLen = charIndex >= lineLen ? 1 :
		          TextBuffer::ExpandCharacter( lineStr[ charIndex ], outIndex, expandedChar,
		                                       buf->mTabDist, buf->mNullSubsChar );
		charStyle = styleOfPos( lineStartPos, lineLen, charIndex,
		                        outIndex + dispIndexOffset );
		for ( i = 0; i < charLen; i++ )
		{
			if ( i != 0 && charIndex < lineLen && lineStr[ charIndex ] == '\t' )
				charStyle = styleOfPos( lineStartPos, lineLen,
				                        charIndex, outIndex + dispIndexOffset );
			if ( charStyle != style )
			{
				drawString( style, startX, Y, X, outStr, outPtr - outStr );
				outPtr = outStr;
				startX = X;
				style = charStyle;
			}
			if ( charIndex < lineLen )
			{
				*outPtr = expandedChar[ i ];
				charWidth = stringWidth( &expandedChar[ i ], 1, charStyle );
			}
			else
				charWidth = stdCharWidth;
			outPtr++;
			X += charWidth;
			outIndex++;
		}
		if ( outPtr - outStr + MAX_EXP_CHAR_LEN >= MAX_DISP_LINE_LEN || X >= rightClip )
			break;
	}

	/* Draw the remaining style segment */
	drawString( style, startX, Y, X, outStr, outPtr - outStr );

	/* Draw the cursor if part of it appeared on the redisplayed part of
	   this line.  Also check for the cases which are not caught as the
	   line is scanned above: when the cursor appears at the very end
	   of the redisplayed section. */
	if ( mCursorOn )
	{
		if ( hasCursor )
			drawCursor( cursorX, Y );
		else if ( charIndex < lineLen && ( lineStartPos + charIndex + 1 == cursorPos )
		          && X == rightClip )
		{
			if ( cursorPos >= buf->mLength )
				drawCursor( X - 1, Y );
			else
			{
				if ( wrapUsesCharacter( cursorPos ) )
					drawCursor( X - 1, Y );
			}
		}
	}

	if ( lineStr != NULL )
		delete [] lineStr;
}

/*
** Draw a string or blank area according to parameter "style", using the
** appropriate colors and drawing method for that style, with top left
** corner at X, y.  If style says to draw text, use "string" as source of
** characters, and draw "nChars", if style is FILL, erase
** rectangle where text would have drawn from X to toX and from Y to
** the maximum Y extent of the current font(s).
*/
void TextDisp::drawString( int style, int X, int Y, int toX,
                           char *string, int nChars )
{
	styleTableEntry * styleRec;

	if ( !visible() ) return ;

	/* Draw blank area rather than text, if that was the request */
	if ( style & FILL_MASK )
	{
		clearRect( style, X, Y, toX - X, mMaxsize );
		return ;
	}

	/* Set font, color, and gc depending on style.  For normal text, GCs
	   for normal drawing, or drawing within a Selection or highlight are
	   pre-allocated and pre-configured.  For syntax highlighting, GCs are
	   configured here, on the fly. */

	Fl_Font font = mTextfont;
	int size = mTextsize;
	Fl_Color foreground;
	Fl_Color background;

	if ( style & STYLE_LOOKUP_MASK )
	{
		styleRec = &mStyleTable[ ( style & STYLE_LOOKUP_MASK ) - 'A' ];
		font = styleRec->font;
		size = styleRec->size;
		foreground = styleRec->color;
		background = style & PRIMARY_MASK ? mSelect_background :
		             style & HIGHLIGHT_MASK ? mHighlight_background : color();
		if ( foreground == background )    /* B&W kludge */
			foreground = color();
	}
	else if ( style & HIGHLIGHT_MASK )
	{
		foreground = mHighlight_foreground;
		background = mHighlight_background;
	}
	else if ( style & PRIMARY_MASK )
	{
		foreground = mSelect_foreground;
		background = mSelect_background;
	}
	else
	{
		foreground = mTextcolor;
		background = color();
	}

	/* Draw the string using gc and font set above */
	//    XDrawImageString(XtDisplay(mW), XtWindow(mW), gc, x,
	//    	    Y + mAscent, string, nChars);

	fl_color( background );
	fl_rectf( X, Y, toX - X, mMaxsize );
	fl_color( foreground );
	fl_font( font, size );
	fl_draw( string, nChars, X, Y + mMaxsize - fl_descent() );

	/* If any space around the character remains unfilled (due to use of
	   different sized fonts for highlighting), fill in above or below
	   to erase previously drawn characters */
	/*
	    if (fs->ascent < mAscent)
	    	clearRect( style, X, Y, toX - X, mAscent - fs->ascent);
	    if (fs->descent < mDescent)
	    	clearRect( style, X, Y + mAscent + fs->descent, toX - x,
	    		mDescent - fs->descent);
	*/
	/* Underline if style is secondary Selection */

	/*
	    if (style & SECONDARY_MASK)
	    	XDrawLine(XtDisplay(mW), XtWindow(mW), gc, x,
	    	    	y + mAscent, toX - 1, Y + fs->ascent);
	*/
}

/*
** Clear a rectangle with the appropriate background color for "style"
*/
void TextDisp::clearRect( int style, int X, int Y,
                          int width, int height )
{
	/* A width of zero means "clear to end of window" to XClearArea */
	if ( width == 0 )
		return ;

	if ( style & HIGHLIGHT_MASK )
	{
		fl_color( mHighlight_background );
		fl_rectf( X, Y, width, height );
	}
	else if ( style & PRIMARY_MASK )
	{
		fl_color( mSelect_background );
		fl_rectf( X, Y, width, height );
	}
	else
	{
		fl_color( color() );
		fl_rectf( X, Y, width, height );
	}
}


void TextDisp::drawCursor( int X, int Y )
{
	damage_cursor_x = X;
	damage_cursor_y = Y;
	damage( FL_DAMAGE_CURSOR );
}

/*
** Draw a cursor with top center at X, y.
*/
void TextDisp::drawCursor_( int X, int Y )
{
	typedef struct
	{
		int x1, y1, x2, y2;
	}
	Segment;

	Segment segs[ 5 ];
	int left, right, cursorWidth, midY;
	//    int fontWidth = mFontStruct->min_bounds.width, nSegs = 0;
	int fontWidth = TMPFONTWIDTH;
	int nSegs = 0;
	int fontHeight = mMaxsize;
	int bot = Y + fontHeight - 1;

	if ( !visible() || X < x() - 1 ||
	        X > x() + w() )
		return ;

	fl_push_clip( x(), y(), w(), h() );

	/* For cursors other than the block, make them around 2/3 of a character
	   width, rounded to an even number of pixels so that X will draw an
	   odd number centered on the stem at x. */
	cursorWidth = 4;    //(fontWidth/3) * 2;
	left = X - cursorWidth / 2;
	right = left + cursorWidth;

	/* Create segments and draw cursor */
	if ( mCursorStyle == CARET_CURSOR )
	{
		midY = bot - fontHeight / 5;
		segs[ 0 ].x1 = left;
		segs[ 0 ].y1 = bot;
		segs[ 0 ].x2 = X;
		segs[ 0 ].y2 = midY;
		segs[ 1 ].x1 = X;
		segs[ 1 ].y1 = midY;
		segs[ 1 ].x2 = right;
		segs[ 1 ].y2 = bot;
		segs[ 2 ].x1 = left;
		segs[ 2 ].y1 = bot;
		segs[ 2 ].x2 = X;
		segs[ 2 ].y2 = midY - 1;
		segs[ 3 ].x1 = X;
		segs[ 3 ].y1 = midY - 1;
		segs[ 3 ].x2 = right;
		segs[ 3 ].y2 = bot;
		nSegs = 4;
	}
	else if ( mCursorStyle == NORMAL_CURSOR )
	{
		segs[ 0 ].x1 = left;
		segs[ 0 ].y1 = Y;
		segs[ 0 ].x2 = right;
		segs[ 0 ].y2 = Y;
		segs[ 1 ].x1 = X;
		segs[ 1 ].y1 = Y;
		segs[ 1 ].x2 = X;
		segs[ 1 ].y2 = bot;
		segs[ 2 ].x1 = left;
		segs[ 2 ].y1 = bot;
		segs[ 2 ].x2 = right;
		segs[ 2 ].y2 = bot;
		nSegs = 3;
	}
	else if ( mCursorStyle == HEAVY_CURSOR )
	{
		segs[ 0 ].x1 = X - 1;
		segs[ 0 ].y1 = Y;
		segs[ 0 ].x2 = X - 1;
		segs[ 0 ].y2 = bot;
		segs[ 1 ].x1 = X;
		segs[ 1 ].y1 = Y;
		segs[ 1 ].x2 = X;
		segs[ 1 ].y2 = bot;
		segs[ 2 ].x1 = X + 1;
		segs[ 2 ].y1 = Y;
		segs[ 2 ].x2 = X + 1;
		segs[ 2 ].y2 = bot;
		segs[ 3 ].x1 = left;
		segs[ 3 ].y1 = Y;
		segs[ 3 ].x2 = right;
		segs[ 3 ].y2 = Y;
		segs[ 4 ].x1 = left;
		segs[ 4 ].y1 = bot;
		segs[ 4 ].x2 = right;
		segs[ 4 ].y2 = bot;
		nSegs = 5;
	}
	else if ( mCursorStyle == DIM_CURSOR )
	{
		midY = Y + fontHeight / 2;
		segs[ 0 ].x1 = X;
		segs[ 0 ].y1 = Y;
		segs[ 0 ].x2 = X;
		segs[ 0 ].y2 = Y;
		segs[ 1 ].x1 = X;
		segs[ 1 ].y1 = midY;
		segs[ 1 ].x2 = X;
		segs[ 1 ].y2 = midY;
		segs[ 2 ].x1 = X;
		segs[ 2 ].y1 = bot;
		segs[ 2 ].x2 = X;
		segs[ 2 ].y2 = bot;
		nSegs = 3;
	}
	else if ( mCursorStyle == BLOCK_CURSOR )
	{
		right = X + fontWidth;
		segs[ 0 ].x1 = X;
		segs[ 0 ].y1 = Y;
		segs[ 0 ].x2 = right;
		segs[ 0 ].y2 = Y;
		segs[ 1 ].x1 = right;
		segs[ 1 ].y1 = Y;
		segs[ 1 ].x2 = right;
		segs[ 1 ].y2 = bot;
		segs[ 2 ].x1 = right;
		segs[ 2 ].y1 = bot;
		segs[ 2 ].x2 = X;
		segs[ 2 ].y2 = bot;
		segs[ 3 ].x1 = X;
		segs[ 3 ].y1 = bot;
		segs[ 3 ].x2 = X;
		segs[ 3 ].y2 = Y;
		nSegs = 4;
	}
	//    XDrawSegments(XtDisplay(mW), XtWindow(mW),
	//    	    mCursorFGGC, segs, nSegs);
	fl_color( mCursor_color );

	for ( int k = 0; k < nSegs; k++ )
	{
		fl_line( segs[ k ].x1, segs[ k ].y1, segs[ k ].x2, segs[ k ].y2 );
	}

	/* Save the last position drawn */
	mCursorX = X;
	mCursorY = Y;

	fl_pop_clip();
}

/*
** Determine the drawing method to use to draw a specific character from "buf".
** "lineStartPos" gives the character index where the line begins, "lineIndex",
** the number of characters past the beginning of the line, and "dispIndex",
** the number of displayed characters past the beginning of the line.  Passing
** lineStartPos of -1 returns the drawing style for "no text".
**
** Why not just: styleOfPos( pos)?  Because style applies to blank areas
** of the window beyond the text boundaries, and because this routine must also
** decide whether a position is inside of a rectangular Selection, and do so
** efficiently, without re-counting character positions from the start of the
** line.
**
** Note that style is a somewhat incorrect name, drawing method would
** be more appropriate.
*/
int TextDisp::styleOfPos( int lineStartPos,
                          int lineLen, int lineIndex, int dispIndex )
{
	TextBuffer * buf = mBuffer;
	TextBuffer *styleBuf = mStyleBuffer;
	int pos, style = 0;

	if ( lineStartPos == -1 || buf == NULL )
		return FILL_MASK;

	pos = lineStartPos + min( lineIndex, lineLen );

	if ( lineIndex >= lineLen )
		style = FILL_MASK;
	else if ( styleBuf != NULL )
	{
		style = ( unsigned char ) styleBuf->GetCharacter( pos );
		/*!!!   	if (style == mUnfinishedStyle) {
		    	    // encountered "unfinished" style, trigger parsing 
		    	    (mUnfinishedHighlightCB)( pos, mHighlightCBArg);
		    	    style = (unsigned char) styleBuf->GetCharacter( pos);
		    	}
					*/
	}
	if ( inSelection( &buf->mPrimary, pos, lineStartPos, dispIndex ) )
		style |= PRIMARY_MASK;
	if ( inSelection( &buf->mHighlight, pos, lineStartPos, dispIndex ) )
		style |= HIGHLIGHT_MASK;
	if ( inSelection( &buf->mSecondary, pos, lineStartPos, dispIndex ) )
		style |= SECONDARY_MASK;
	return style;
}

/*
** Find the width of a string in the font of a particular style
*/
int TextDisp::stringWidth( char *string, int length, int style )
{
	Fl_Font font;
	int size;

	if ( style & STYLE_LOOKUP_MASK )
	{
		font = mStyleTable[ ( style & STYLE_LOOKUP_MASK ) - 'A' ].font;
		size = mStyleTable[ ( style & STYLE_LOOKUP_MASK ) - 'A' ].size;
	}
	else
	{
		font = mTextfont;
		size = mTextsize;
	}
	fl_font( font, size );

	return ( int ) ( fl_width( string, length ) );
}

/*
** Return true if position "pos" with indentation "dispIndex" is in
** Selection "sel"
*/
int inSelection( Selection *sel, int pos, int lineStartPos, int dispIndex )
{
	return sel->mSelected &&
	       ( ( !sel->mRectangular &&
	           pos >= sel->mStart && pos < sel->mEnd ) ||
	         ( sel->mRectangular &&
	           pos >= sel->mStart && lineStartPos <= sel->mEnd &&
	           dispIndex >= sel->mRectStart && dispIndex < sel->mRectEnd ) );
}

/*
** Translate window coordinates to the nearest (insert cursor or character
** cell) text position.  The parameter posType specifies how to interpret the
** position: CURSOR_POS means translate the coordinates to the nearest cursor
** position, and CHARACTER_POS means return the position of the character
** closest to (X, Y).
*/
int TextDisp::xyToPos( int X, int Y, int posType )
{
	int charIndex, lineStart, lineLen, fontHeight;
	int charWidth, charLen, charStyle, visLineNum, xStep, outIndex;
	char *lineStr, expandedChar[ MAX_EXP_CHAR_LEN ];

	/* Find the visible line number corresponding to the Y coordinate */
	fontHeight = mMaxsize;
	visLineNum = ( Y - mTop ) / fontHeight;
	if ( visLineNum < 0 )
		return mFirstChar;
	if ( visLineNum >= mNVisibleLines )
		visLineNum = mNVisibleLines - 1;

	/* Find the position at the start of the line */
	lineStart = mLineStarts[ visLineNum ];

	/* If the line start was empty, return the last position in the buffer */
	if ( lineStart == -1 )
		return mBuffer->mLength;

	/* Get the line text and its length */
	lineLen = visLineLength( visLineNum );
	lineStr = mBuffer->GetRange( lineStart, lineStart + lineLen );

	/* Step through character positions from the beginning of the line
	   to find the character position corresponding to the X coordinate */
	xStep = mLeft - mHorizOffset;
	outIndex = 0;
	for ( charIndex = 0; charIndex < lineLen; charIndex++ )
	{
		charLen = TextBuffer::ExpandCharacter( lineStr[ charIndex ], outIndex, expandedChar,
		                                       mBuffer->mTabDist, mBuffer->mNullSubsChar );
		charStyle = styleOfPos( lineStart, lineLen, charIndex, outIndex );
		charWidth = stringWidth( expandedChar, charLen, charStyle );
		if ( X < xStep + ( posType == CURSOR_POS ? charWidth / 2 : charWidth ) )
		{
			delete [] lineStr;
			return lineStart + charIndex;
		}
		xStep += charWidth;
		outIndex += charLen;
	}

	/* If the X position was beyond the end of the line, return the position
	   of the newline at the end of the line */
	delete [] lineStr;
	return lineStart + lineLen;
}

/*
** Translate window coordinates to the nearest row and column number for
** positioning the cursor.  This, of course, makes no sense when the font is
** proportional, since there are no absolute columns.  The parameter posType
** specifies how to interpret the position: CURSOR_POS means translate the
** coordinates to the nearest position between characters, and CHARACTER_POS
** means translate the position to the nearest character cell.
*/
void TextDisp::xyToUnconstrainedPos( int X, int Y, int *row,
                                     int *column, int posType )
{
	int fontHeight = mMaxsize;
	int fontWidth = TMPFONTWIDTH;    //mFontStruct->max_bounds.width;

	/* Find the visible line number corresponding to the Y coordinate */
	*row = ( Y - mTop ) / fontHeight;
	if ( *row < 0 ) * row = 0;
	if ( *row >= mNVisibleLines ) * row = mNVisibleLines - 1;
	*column = ( ( X - mLeft ) + mHorizOffset +
	            ( posType == CURSOR_POS ? fontWidth / 2 : 0 ) ) / fontWidth;
	if ( *column < 0 ) * column = 0;
}

/*
** Offset the line starts array, topLineNum, firstChar and lastChar, for a new
** vertical scroll position given by newTopLineNum.  If any currently displayed
** lines will still be visible, salvage the line starts values, otherwise,
** count lines from the nearest known line start (start or end of buffer, or
** the closest value in the lineStarts array)
*/
void TextDisp::offsetLineStarts( int newTopLineNum )
{
	int oldTopLineNum = mTopLineNum;
	int lineDelta = newTopLineNum - oldTopLineNum;
	int nVisLines = mNVisibleLines;
	int *lineStarts = mLineStarts;
	int i, lastLineNum;
	TextBuffer *buf = mBuffer;

	/* If there was no offset, nothing needs to be changed */
	if ( lineDelta == 0 )
		return ;

	/* {   int i;
		printf("Scroll, lineDelta %d\n", lineDelta);
		printf("lineStarts Before: ");
		for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		printf("\n");
} */

	/* Find the new value for firstChar by counting lines from the nearest
	   known line start (start or end of buffer, or the closest value in the
	   lineStarts array) */
	lastLineNum = oldTopLineNum + nVisLines - 1;
	if ( newTopLineNum < oldTopLineNum && newTopLineNum < -lineDelta )
	{
		mFirstChar = CountForwardNLines( 0, newTopLineNum - 1,
		                                 True );
		/* printf("counting forward %d lines from start\n", newTopLineNum-1);*/
	}
	else if ( newTopLineNum < oldTopLineNum )
	{
		mFirstChar = CountBackwardNLines( mFirstChar,
		                                  -lineDelta );
		/* printf("counting backward %d lines from firstChar\n", -lineDelta);*/
	}
	else if ( newTopLineNum < lastLineNum )
	{
		mFirstChar = lineStarts[ newTopLineNum - oldTopLineNum ];
		/* printf("taking new start from lineStarts[%d]\n",
			newTopLineNum - oldTopLineNum); */
	}
	else if ( newTopLineNum - lastLineNum < mNBufferLines - newTopLineNum )
	{
		mFirstChar = CountForwardNLines( lineStarts[ nVisLines - 1 ],
		                                 newTopLineNum - lastLineNum, True );
		/* printf("counting forward %d lines from start of last line\n",
			newTopLineNum - lastLineNum); */
	}
	else
	{
		mFirstChar = CountBackwardNLines( buf->mLength,
		                                  mNBufferLines - newTopLineNum + 1 );
		/* printf("counting backward %d lines from end\n",
		   		mNBufferLines - newTopLineNum + 1); */
	}

	/* Fill in the line starts array */
	if ( lineDelta < 0 && -lineDelta < nVisLines )
	{
		for ( i = nVisLines - 1; i >= -lineDelta; i-- )
			lineStarts[ i ] = lineStarts[ i + lineDelta ];
		calcLineStarts( 0, -lineDelta );
	}
	else if ( lineDelta > 0 && lineDelta < nVisLines )
	{
		for ( i = 0; i < nVisLines - lineDelta; i++ )
			lineStarts[ i ] = lineStarts[ i + lineDelta ];
		calcLineStarts( nVisLines - lineDelta, nVisLines - 1 );
	}
	else
		calcLineStarts( 0, nVisLines );

	/* Set lastChar and topLineNum */
	calcLastChar();
	mTopLineNum = newTopLineNum;

	/* {   int i;
		printf("lineStarts After: ");
		for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		printf("\n");
} */
}

/*
** Update the line starts array, topLineNum, firstChar and lastChar for text
** display "textD" after a modification to the text buffer, given by the
** position where the change began "pos", and the nmubers of characters
** and lines inserted and deleted.
*/
void TextDisp::updateLineStarts( int pos, int charsInserted,
                                 int charsDeleted, int linesInserted, int linesDeleted, int *scrolled )
{
	int * lineStarts = mLineStarts;
	int i, lineOfPos, lineOfEnd, nVisLines = mNVisibleLines;
	int charDelta = charsInserted - charsDeleted;
	int lineDelta = linesInserted - linesDeleted;

	/* {   int i;
		printf("linesDeleted %d, linesInserted %d, charsInserted %d, charsDeleted %d\n",
		    	linesDeleted, linesInserted, charsInserted, charsDeleted);
		printf("lineStarts Before: ");
		for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		printf("\n");
} */
	/* If all of the changes were before the displayed text, the display
	   doesn't change, just update the top line num and offset the line
	   start entries and first and last characters */
	if ( pos + charsDeleted < mFirstChar )
	{
		mTopLineNum += lineDelta;
		for ( i = 0; i < nVisLines; i++ )
			lineStarts[ i ] += charDelta;
		/* {   int i;
		    printf("lineStarts after delete doesn't touch: ");
		    for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		    printf("\n");
	} */
		mFirstChar += charDelta;
		mLastChar += charDelta;
		*scrolled = False;
		return ;
	}

	/* The change began before the beginning of the displayed text, but
	   part or all of the displayed text was deleted */
	if ( pos < mFirstChar )
	{
		/* If some text remains in the window, anchor on that  */
		if ( posToVisibleLineNum( pos + charsDeleted, &lineOfEnd ) &&
		        ++lineOfEnd < nVisLines && lineStarts[ lineOfEnd ] != -1 )
		{
			mTopLineNum = max( 1, mTopLineNum + lineDelta );
			mFirstChar = CountBackwardNLines(
			                 lineStarts[ lineOfEnd ] + charDelta, lineOfEnd );
			/* Otherwise anchor on original line number and recount everything */
		}
		else
		{
			if ( mTopLineNum > mNBufferLines + lineDelta )
			{
				mTopLineNum = 1;
				mFirstChar = 0;
			}
			else
				mFirstChar = CountForwardNLines( 0,
				                                 mTopLineNum - 1, True );
		}
		calcLineStarts( 0, nVisLines - 1 );
		/* {   int i;
		    printf("lineStarts after delete encroaches: ");
		    for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		    printf("\n");
	} */
		/* calculate lastChar by finding the end of the last displayed line */
		calcLastChar();
		*scrolled = True;
		return ;
	}

	/* If the change was in the middle of the displayed text (it usually is),
	   salvage as much of the line starts array as possible by moving and
	   offsetting the entries after the changed area, and re-counting the
	   added lines or the lines beyond the salvaged part of the line starts
	   array */
	if ( pos <= mLastChar )
	{
		/* find line on which the change began */
		posToVisibleLineNum( pos, &lineOfPos );
		/* salvage line starts after the changed area */
		if ( lineDelta == 0 )
		{
			for ( i = lineOfPos + 1; i < nVisLines && lineStarts[ i ] != -1; i++ )
				lineStarts[ i ] += charDelta;
		}
		else if ( lineDelta > 0 )
		{
			for ( i = nVisLines - 1; i >= lineOfPos + lineDelta + 1; i-- )
				lineStarts[ i ] = lineStarts[ i - lineDelta ] +
				                  ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta );
		}
		else /* (lineDelta < 0) */
		{
			for ( i = max( 0, lineOfPos + 1 ); i < nVisLines + lineDelta; i++ )
				lineStarts[ i ] = lineStarts[ i - lineDelta ] +
				                  ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta );
		}
		/* {   int i;
		    printf("lineStarts after salvage: ");
		    for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		    printf("\n");
	} */
		/* fill in the missing line starts */
		if ( linesInserted >= 0 )
			calcLineStarts( lineOfPos + 1, lineOfPos + linesInserted );
		if ( lineDelta < 0 )
			calcLineStarts( nVisLines + lineDelta, nVisLines );
		/* {   int i;
		    printf("lineStarts after recalculation: ");
		    for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		    printf("\n");
	} */
		/* calculate lastChar by finding the end of the last displayed line */
		calcLastChar();
		*scrolled = False;
		return ;
	}

	/* Change was past the end of the displayed text, but displayable by virtue
	   of being an insert at the end of the buffer into visible blank lines */
	if ( emptyLinesVisible() )
	{
		posToVisibleLineNum( pos, &lineOfPos );
		calcLineStarts( lineOfPos, lineOfPos + linesInserted );
		calcLastChar();
		/* {   int i;
		    printf("lineStarts after insert at end: ");
		    for(i=0; i<nVisLines; i++) printf("%d ", lineStarts[i]);
		    printf("\n");
	} */
		*scrolled = False;
		return ;
	}

	/* Change was beyond the end of the buffer and not visible, do nothing */
	*scrolled = False;
}

/*
** Scan through the text in the "textD"'s buffer and recalculate the line
** starts array values beginning at index "startLine" and continuing through
** (including) "endLine".  It assumes that the line starts entry preceding
** "startLine" (or mFirstChar if startLine is 0) is good, and re-counts
** newlines to fill in the requested entries.  Out of range values for
** "startLine" and "endLine" are acceptable.
*/
void TextDisp::calcLineStarts( int startLine, int endLine )
{
	int startPos, bufLen = mBuffer->mLength;
	int line, lineEnd, nextLineStart, nVis = mNVisibleLines;
	int *lineStarts = mLineStarts;

	/* Clean up (possibly) messy input parameters */
	if ( endLine < 0 ) endLine = 0;
	if ( endLine >= nVis ) endLine = nVis - 1;
	if ( startLine < 0 ) startLine = 0;
	if ( startLine >= nVis ) startLine = nVis - 1;
	if ( startLine > endLine )
		return ;

	/* Find the last known good line number -> position mapping */
	if ( startLine == 0 )
	{
		lineStarts[ 0 ] = mFirstChar;
		startLine = 1;
	}
	startPos = lineStarts[ startLine - 1 ];

	/* If the starting position is already past the end of the text,
	   fill in -1's (means no text on line) and return */
	if ( startPos == -1 )
	{
		for ( line = startLine; line <= endLine; line++ )
			lineStarts[ line ] = -1;
		return ;
	}

	/* Loop searching for ends of lines and storing the positions of the
	   start of the next line in lineStarts */
	for ( line = startLine; line <= endLine; line++ )
	{
		findLineEnd( startPos, True, &lineEnd, &nextLineStart );
		startPos = nextLineStart;
		if ( startPos >= bufLen )
		{
			/* If the buffer ends with a newline or line break, put
			   buf->mLength in the next line start position (instead of
			   a -1 which is the normal marker for an empty line) to
			   indicate that the cursor may safely be displayed there */
			if ( line == 0 || ( lineStarts[ line - 1 ] != bufLen &&
			                    lineEnd != nextLineStart ) )
			{
				lineStarts[ line ] = bufLen;
				line++;
			}
			break;
		}
		lineStarts[ line ] = startPos;
	}

	/* Set any entries beyond the end of the text to -1 */
	for ( ; line <= endLine; line++ )
		lineStarts[ line ] = -1;
}

/*
** Given a textDisp with a complete, up-to-date lineStarts array, update
** the lastChar entry to point to the last buffer position displayed.
*/
void TextDisp::calcLastChar()
{
	int i;

	for ( i = mNVisibleLines - 1; i > 0 && mLineStarts[ i ] == -1; i-- );
	mLastChar = i < 0 ? 0 :
	            EndOfLine( mLineStarts[ i ], True );
}

void TextDisp::setScroll( int topLineNum, int horizOffset,
                          int updateVScrollBar, int updateHScrollBar )
{
	int fontHeight = mMaxsize;
	int origHOffset = mHorizOffset;
	int lineDelta = mTopLineNum - topLineNum;
	int xOffset, yOffset, srcX, srcY, dstX, dstY, width, height;
	int exactHeight = mHeight - mHeight %
	                  ( mMaxsize );

	/* Do nothing if scroll position hasn't actually changed or there's no
	   window to draw in yet */
	if ( !visible() || ( mHorizOffset == horizOffset &&
	                     mTopLineNum == topLineNum ) )
		return ;

	/* If part of the cursor is protruding beyond the text clipping region,
	   clear it off */
	blankCursorProtrusions();

	/* If the vertical scroll position has changed, update the line
	   starts array and related counters in the text display */
	offsetLineStarts( topLineNum );

	/* Just setting mHorizOffset is enough information for redisplay */
	mHorizOffset = horizOffset;

	/* Update the scroll bar positions if requested, note: updating the
	   horizontal scroll bars can have the further side-effect of changing
	   the horizontal scroll position, mHorizOffset */
	if ( updateVScrollBar && mVScrollBar != NULL )
		updateVScrollBarRange();
	if ( updateHScrollBar && mHScrollBar != NULL )
	{
		updateHScrollBarRange();
	}

	/* Redisplay everything if the window is partially obscured (since
	   it's too hard to tell what displayed areas are salvageable) or
	   if there's nothing to recover because the scroll distance is large */
	xOffset = origHOffset - mHorizOffset;
	yOffset = lineDelta * fontHeight;
	if ( visible() /*!!! mVisibility != VisibilityUnobscured*/ ||
	        abs( xOffset ) > w() || abs( yOffset ) > exactHeight )
	{
		RedisplayRect( x(), y(), w(), h() );

		/* If the window is not obscured, paint most of the window using XCopyArea
		   from existing displayed text, and redraw only what's necessary */
	}
	else
	{
		/* Recover the useable window areas by moving to the proper location */
		srcX = x() + ( xOffset >= 0 ? 0 : -xOffset );
		dstX = x() + ( xOffset >= 0 ? xOffset : 0 );
		width = w() - abs( xOffset );
		srcY = y() + ( yOffset >= 0 ? 0 : -yOffset );
		dstY = y() + ( yOffset >= 0 ? yOffset : 0 );
		height = exactHeight - abs( yOffset );
		resetClipRectangles();
		//!!!	XCopyArea(XtDisplay(mW), XtWindow(mW), XtWindow(mW),
		//!!!    		mGc, srcX, srcY, width, height, dstX, dstY);
		/* redraw the un-recoverable parts */

		if ( yOffset > 0 )
			RedisplayRect( x(), y(),
			               w(), yOffset );
		else if ( yOffset < 0 )
			RedisplayRect( x(), y() +
			               h() + yOffset, w(), -yOffset );
		if ( xOffset > 0 )
			RedisplayRect( x(), y(),
			               xOffset, h() );
		else if ( xOffset < 0 )
			RedisplayRect( x() + w() + xOffset,
			               y(), -xOffset, h() );

		/* Restore protruding parts of the cursor */
		RedisplayRange( mCursorPos - 1, mCursorPos + 1 );
	}
}

/*
** Update the minimum, maximum, slider size, page increment, and value
** for vertical scroll bar.
*/
void TextDisp::updateVScrollBarRange()
{
	int sliderSize, sliderMax, sliderValue;

	if ( mVScrollBar == NULL )
		return ;

	/* The Vert. scroll bar value and slider size directly represent the top
	   line number, and the number of visible lines respectively.  The scroll
	   bar maximum value is chosen to generally represent the size of the whole
	   buffer, with minor adjustments to keep the scroll bar widget happy */
	sliderSize = mNVisibleLines;
	sliderValue = mTopLineNum;
	sliderMax = max( mNBufferLines + 2, sliderSize + sliderValue );

	mVScrollBar->value( sliderValue, sliderSize, 1, sliderMax - 1 );
	/*
	    XtVaSetValues(mVScrollBar,
	    	    XmNmaximum, sliderMax,
	    	    XmNsliderSize, sliderSize,
	     	    XmNpageIncrement, max(1, mNVisibleLines - 1),
	   	    XmNvalue, sliderValue, 0);
	*/
}

/*
** Update the minimum, maximum, slider size, page increment, and value
** for the horizontal scroll bar.  If scroll position is such that there
** is blank space to the right of all lines of text, scroll back (adjust
** horizOffset but don't redraw) to take up the slack and position the
** right edge of the text at the right edge of the display.
** 
** Note, there is some cost to this routine, since it scans the whole range
** of displayed text, particularly since it's usually called for each typed
** character!
*/
int TextDisp::updateHScrollBarRange()
{
	int i, maxWidth = 0, sliderMax, sliderWidth;
	int origHOffset = mHorizOffset;

	if ( mHScrollBar == NULL )    // || !XtIsManaged(mHScrollBar))
		return False;

	/* Scan all the displayed lines to find the width of the longest line */
	for ( i = 0; i < mNVisibleLines && mLineStarts[ i ] != -1; i++ )
		maxWidth = max( measureVisLine( i ), maxWidth );

	/* If the scroll position is beyond what's necessary to keep all lines
	   in view, scroll to the left to bring the end of the longest line to
	   the right margin */
	if ( maxWidth < mWidth + mHorizOffset && mHorizOffset > 0 )
		mHorizOffset = max( 0, maxWidth - mWidth );

	/* Readjust the scroll bar */
	sliderWidth = mWidth;
	sliderMax = max( maxWidth, sliderWidth + mHorizOffset );

	/*
	    XtVaSetValues(mHScrollBar,
	    	    XmNmaximum, sliderMax,
	    	    XmNsliderSize, sliderWidth,
	    	    XmNpageIncrement, max(w() - 100, 10),
	    	    XmNvalue, mHorizOffset, 0);
	*/

	mHScrollBar->value( mHorizOffset, sliderWidth, 0, sliderMax );

	/* Return True if scroll position was changed */
	return origHOffset != mHorizOffset;
}

/*
** Callbacks for drag or valueChanged on scroll bars
*/
void TextDisp::vScrollCB( Fl_Scrollbar* b, TextDisp* textD )
{
	int newValue = b->value();
	int lineDelta = newValue - textD->mTopLineNum;

	if ( lineDelta == 0 )
		return ;
	textD->setScroll( newValue, textD->mHorizOffset, False, True );
}
void TextDisp::hScrollCB( Fl_Scrollbar* b, TextDisp* textD )
{
	int newValue = b->value();

	if ( newValue == textD->mHorizOffset )
		return ;
	textD->setScroll( textD->mTopLineNum, newValue, False, False );
}
/*
static void visibilityEH(Widget w, XtPointer data, XEvent *event,
	Boolean *continueDispatch)
{
    / Record whether the window is fully visible or not.  This information
       is used for choosing the scrolling methodology for optimal performance,
       if the window is partially obscured, XCopyArea may not work /
    ((textDisp *)data)->visibility = ((XVisibilityEvent *)event)->state;
}
*/

static int max( int i1, int i2 )
{
	return i1 >= i2 ? i1 : i2;
}

static int min( int i1, int i2 )
{
	return i1 <= i2 ? i1 : i2;
}

/*
** Count the number of newlines in a null-terminated text string;
*/
static int countLines( char *string )
{
	char * c;
	int lineCount = 0;

	for ( c = string; *c != '\0'; c++ )
		if ( *c == '\n' ) lineCount++;
	return lineCount;
}

/*
** Return the width in pixels of the displayed line pointed to by "visLineNum"
*/
int TextDisp::measureVisLine( int visLineNum )
{
	int i, width = 0, len, style, lineLen = visLineLength( visLineNum );
	int charCount = 0, lineStartPos = mLineStarts[ visLineNum ];
	char expandedChar[ MAX_EXP_CHAR_LEN ];

	if ( mStyleBuffer == NULL )
	{
		for ( i = 0; i < lineLen; i++ )
		{
			len = mBuffer->GetExpandedChar( lineStartPos + i,
			                                charCount, expandedChar );

			fl_font( mTextfont, mTextsize );

			width += ( int ) fl_width( expandedChar, len );

			charCount += len;
		}
	}
	else
	{
		for ( i = 0; i < lineLen; i++ )
		{
			len = mBuffer->GetExpandedChar( lineStartPos + i,
			                                charCount, expandedChar );
			style = ( unsigned char ) mStyleBuffer->GetCharacter(
			            lineStartPos + i ) - 'A';

			if ( style < 0 ) style = 0;

			fl_font( mStyleTable[ style ].font, mStyleTable[ style ].size );

			width += ( int ) fl_width( expandedChar, len );

			charCount += len;
		}
	}
	return width;
}

/*
** Return true if there are lines visible with no corresponding buffer text
*/
int TextDisp::emptyLinesVisible()
{
	return mNVisibleLines > 0 &&
	       mLineStarts[ mNVisibleLines - 1 ] == -1;
}

/*
** When the cursor is at the left or right edge of the text, part of it
** sticks off into the clipped region beyond the text.  Normal redrawing
** can not overwrite this protruding part of the cursor, so it must be
** erased independently by calling this routine.
*/

void TextDisp::blankCursorProtrusions()
{
	damage( FL_DAMAGE_CURSORPROTRUSIONS );
}

void TextDisp::blankCursorProtrusions_()
{
	int X, width, cursorX = mCursorX, cursorY = mCursorY;
	int fontWidth = TMPFONTWIDTH;    //mFontStruct->max_bounds.width;
	int fontHeight = mMaxsize;
	int cursorWidth, left = mLeft, right = left + mWidth;

	fl_push_clip( x(), y(), w(), h() );

	cursorWidth = ( fontWidth / 3 ) * 2;
	if ( cursorX >= left - 1 && cursorX <= left + cursorWidth / 2 - 1 )
	{
		X = cursorX - cursorWidth / 2;
		width = left - X;
	}
	else if ( cursorX >= right - cursorWidth / 2 && cursorX <= right )
	{
		X = right;
		width = cursorX + cursorWidth / 2 + 2 - right;
	}
	else
		return ;

	fl_color( color() );
	fl_rectf( X, cursorY, width, fontHeight );

	/*    XClearArea(XtDisplay(mW), XtWindow(mW), X, cursorY,
	    	    width, fontHeight, False);
	*/

	fl_pop_clip();
}

/*
** Allocate shared graphics contexts used by the widget, which must be
** re-allocated on a font change.
*/
/*
static void TextDisp::allocateFixedFontGCs( XFontStruct *fontStruct,
	Pixel bgPixel, Pixel fgPixel, Pixel selectFGPixel, Pixel selectBGPixel,
	Pixel highlightFGPixel, Pixel highlightBGPixel)
{
    mGc = allocateGC(mW, GCFont | GCForeground | GCBackground,
    	    fgPixel, bgPixel, fontStruct->fid, GCClipMask, GCArcMode); 
    mSelectGC = allocateGC(mW, GCFont | GCForeground | GCBackground,
    	    selectFGPixel, selectBGPixel, fontStruct->fid, GCClipMask,
    	    GCArcMode);
    mSelectBGGC = allocateGC(mW, GCForeground, selectBGPixel, 0,
    	    fontStruct->fid, GCClipMask, GCArcMode);
    mHighlightGC = allocateGC(mW, GCFont|GCForeground|GCBackground,
    	    highlightFGPixel, highlightBGPixel, fontStruct->fid, GCClipMask,
    	    GCArcMode);
    mHighlightBGGC = allocateGC(mW, GCForeground, highlightBGPixel,
	    0, fontStruct->fid, GCClipMask, GCArcMode);
}
*/

/*
** X11R4 does not have the XtAllocateGC function for sharing graphics contexts
** with changeable fields.  Unfortunately the R4 call for creating shared
** graphics contexts (XtGetGC) is rarely useful because most widgets need
** to be able to set and change clipping, and that makes the GC unshareable.
**
** This function allocates and returns a gc, using XtAllocateGC if possible,
** or XCreateGC on X11R4 systems where XtAllocateGC is not available.
*/
/*
static GC allocateGC(Widget w, unsigned long valueMask,
	unsigned long foreground, unsigned long background, Font font,
	unsigned long dynamicMask, unsigned long dontCareMask)
{
    XGCValues gcValues;
 
    gcValues.font = font;
    gcValues.background = background;
    gcValues.foreground = foreground;
#if defined(XlibSpecificationRelease) && XlibSpecificationRelease > 4
    return XtAllocateGC(w, 0, valueMask, &gcValues, dynamicMask,
    	    dontCareMask);
#else
    return XCreateGC(XtDisplay(w), RootWindowOfScreen(XtScreen(w)),
    	    valueMask, &gcValues);
#endif
}
*/

/*
** Release a gc allocated with allocateGC above
*/
/*
static void releaseGC(Widget w, GC gc)
{
#if defined(XlibSpecificationRelease) && XlibSpecificationRelease > 4
    XtReleaseGC(w, gc);
#else
    XFreeGC(XtDisplay(w), gc);
#endif
}
*/

/*
** resetClipRectangles sets the clipping rectangles for GCs which clip
** at the text boundary (as opposed to the window boundary).  These GCs
** are shared such that the drawing styles are constant, but the clipping
** rectangles are allowed to change among different users of the GCs (the
** GCs were created with XtAllocGC).  This routine resets them so the clipping
** rectangles are correct for this text display.
*/
void TextDisp::resetClipRectangles()
{
	/*!!!
	    XRectangle clipRect;
	    Display *display = fl_display; //XtDisplay(mW);
	    
	    clipRect.x = x();
	    clipRect.y = y();
	    clipRect.width = w();
	    clipRect.height = h() - h() %
	    	    (mMaxsize);
	    
	    XSetClipRectangles(display, mGc, 0, 0,
	    	    &clipRect, 1, Unsorted);
	    XSetClipRectangles(display, mSelectGC, 0, 0,
	            &clipRect, 1, Unsorted);
	    XSetClipRectangles(display, mHighlightGC, 0, 0,
	            &clipRect, 1, Unsorted);
	    XSetClipRectangles(display, mSelectBGGC, 0, 0,
	            &clipRect, 1, Unsorted);
	    XSetClipRectangles(display, mHighlightBGGC, 0, 0,
	            &clipRect, 1, Unsorted);
	    XSetClipRectangles(display, mStyleGC, 0, 0,
	            &clipRect, 1, Unsorted);
	*/
}

/*
** Return the length of a line (number of displayable characters) by examining
** entries in the line starts array rather than by scanning for newlines
*/
int TextDisp::visLineLength( int visLineNum )
{
	int nextLineStart, lineStartPos = mLineStarts[ visLineNum ];

	if ( lineStartPos == -1 )
		return 0;
	if ( visLineNum + 1 >= mNVisibleLines )
		return mLastChar - lineStartPos;
	nextLineStart = mLineStarts[ visLineNum + 1 ];
	if ( nextLineStart == -1 )
		return mLastChar - lineStartPos;
	if ( wrapUsesCharacter( nextLineStart - 1 ) )
		return nextLineStart - 1 - lineStartPos;
	return nextLineStart - lineStartPos;
}

/*
** When continuous wrap is on, and the user inserts or deletes characters,
** wrapping can happen before and beyond the changed position.  This routine
** finds the extent of the changes, and counts the deleted and inserted lines
** over that range.  It also attempts to minimize the size of the range to
** what has to be counted and re-displayed, so the results can be useful
** both for delimiting where the line starts need to be recalculated, and
** for deciding what part of the text to redisplay.
*/
void TextDisp::findWrapRange( char *deletedText, int pos,
                              int nInserted, int nDeleted, int *modRangeStart, int *modRangeEnd,
                              int *linesInserted, int *linesDeleted )
{
	int length, retPos, retLines, retLineStart, retLineEnd;
	TextBuffer *deletedTextBuf, *buf = mBuffer;
	int nVisLines = mNVisibleLines;
	int *lineStarts = mLineStarts;
	int countFrom, countTo, lineStart, adjLineStart, i;
	int visLineNum = 0, nLines = 0;

	/*
	** Determine where to begin searching: either the previous newline, or
	** if possible, limit to the start of the (original) previous displayed
	** line, using information from the existing line starts array
	*/
	if ( pos >= mFirstChar && pos <= mLastChar )
	{
		for ( i = nVisLines - 1; i > 0; i-- )
			if ( lineStarts[ i ] != -1 && pos >= lineStarts[ i ] )
				break;
		if ( i > 0 )
		{
			countFrom = lineStarts[ i - 1 ];
			visLineNum = i - 1;
		}
		else
			countFrom = buf->StartOfLine( pos );
	}
	else
		countFrom = buf->StartOfLine( pos );


	/*
	** Move forward through the (new) text one line at a time, counting
	** displayed lines, and looking for either a real newline, or for the
	** line starts to re-sync with the original line starts array
	*/
	lineStart = countFrom;
	*modRangeStart = countFrom;
	while ( True )
	{

		/* advance to the next line.  If the line ended in a real newline
		   or the end of the buffer, that's far enough */
		wrappedLineCounter( buf, lineStart, buf->mLength, 1, True,
		                    &retPos, &retLines, &retLineStart, &retLineEnd );
		if ( retPos >= buf->mLength )
		{
			countTo = buf->mLength;
			*modRangeEnd = countTo;
			if ( retPos != retLineEnd )
				nLines++;
			break;
		}
		else
			lineStart = retPos;
		nLines++;
		if ( lineStart > pos + nInserted &&
		        buf->GetCharacter( lineStart - 1 ) == '\n' )
		{
			countTo = lineStart;
			*modRangeEnd = lineStart;
			break;
		}

		/* check for synchronization with the original line starts array
		   before pos, if so, the modified range can begin later */
		if ( lineStart <= pos )
		{
			while ( visLineNum < nVisLines && lineStarts[ visLineNum ] < lineStart )
				visLineNum++;
			if ( visLineNum < nVisLines && lineStarts[ visLineNum ] == lineStart )
			{
				countFrom = lineStart;
				nLines = 0;
				if ( visLineNum + 1 < nVisLines && lineStarts[ visLineNum + 1 ] != -1 )
					* modRangeStart = min( pos, lineStarts[ visLineNum + 1 ] - 1 );
				else
					*modRangeStart = countFrom;
			}
			else
				*modRangeStart = min( *modRangeStart, lineStart - 1 );
		}

		/* check for synchronization with the original line starts array
			   after pos, if so, the modified range can end early */
		else if ( lineStart > pos + nInserted )
		{
			adjLineStart = lineStart - nInserted + nDeleted;
			while ( visLineNum < nVisLines && lineStarts[ visLineNum ] < adjLineStart )
				visLineNum++;
			if ( visLineNum < nVisLines && lineStarts[ visLineNum ] != -1 &&
			        lineStarts[ visLineNum ] == adjLineStart )
			{
				countTo = EndOfLine( lineStart, True );
				*modRangeEnd = lineStart;
				break;
			}
		}
	}
	*linesInserted = nLines;


	/* Count deleted lines between countFrom and countTo as the text existed
	   before the modification (that is, as if the text between pos and
	   pos+nInserted were replaced by "deletedText").  This extra context is
	   necessary because wrapping can occur outside of the modified region
	   as a result of adding or deleting text in the region. This is done by
	   creating a TextBuffer containing the deleted text and the necessary
	   additional context, and calling the wrappedLineCounter on it. */
	length = ( pos - countFrom ) + nDeleted + ( countTo - ( pos + nInserted ) );
	deletedTextBuf = new TextBuffer( length );
	mBuffer->CopyFromBuf( deletedTextBuf, countFrom, pos, 0 );
	if ( nDeleted != 0 )
		deletedTextBuf->Insert( pos - countFrom, deletedText );
	mBuffer->CopyFromBuf( deletedTextBuf,
	                      pos + nInserted, countTo, pos - countFrom + nDeleted );
	wrappedLineCounter( deletedTextBuf, 0, length, INT_MAX, True,
	                    &retPos, &retLines, &retLineStart, &retLineEnd );
	delete deletedTextBuf;
	*linesDeleted = retLines;
}

/*
** Count forward from startPos to either maxPos or maxLines (whichever is
** reached first), and return all relevant positions and line count.
**
** Returned values:
**
**   retPos:	    Position where counting ended.  When counting lines, the
**  	    	    position returned is the start of the line "maxLines"
**  	    	    lines beyond "startPos".
**   retLines:	    Number of line breaks counted
**   retLineStart:  Start of the line where counting ended
**   retLineEnd:    End position of the last line traversed
*/
void TextDisp::wrappedLineCounter( TextBuffer *buf, int startPos,
                                   int maxPos, int maxLines, int startPosIsLineStart, int *retPos,
                                   int *retLines, int *retLineStart, int *retLineEnd )
{
	int lineStart, newLineStart, b, p, colNum, wrapMargin;
	int maxWidth, width, countPixels, expLen, i, foundBreak;
	int nLines = 0, tabDist = mBuffer->mTabDist;
	//!!!    int fontWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width;
	unsigned char c;
	char expChar[ MAX_EXP_CHAR_LEN ], nullSubsChar = mBuffer->mNullSubsChar;

	/* If the font is fixed, or there's a wrap margin set, it's more efficient
	   to measure in columns, than to count pixels.  Determine if we can count
	   in columns (countPixels == False) or must count pixels (countPixels ==
	   True), and set the wrap target for either pixels or columns */
	/*!!!    if (mFontStruct->min_bounds.width == fontWidth ||
	    	    mWrapMargin != 0) {
	    	countPixels = False;
		wrapMargin = mWrapMargin != 0 ? mWrapMargin :
	            	w() / fontWidth;
	        maxWidth = INT_MAX;
	    } else */ 
	{
		countPixels = True;
		wrapMargin = INT_MAX;
		maxWidth = mWidth;
	}

	/* Find the start of the line if the start pos is not marked as a
	   line start. */
	if ( startPosIsLineStart )
		lineStart = startPos;
	else
		lineStart = StartOfLine( startPos );

	/*
	** Loop until position exceeds maxPos or line count exceeds maxLines.
	** (actually, contines beyond maxPos to end of line containing maxPos,
	** in case later characters cause a word wrap back before maxPos)
	*/
	colNum = 0;
	width = 0;
	for ( p = lineStart; p < buf->mLength; p++ )
	{
		c = buf->GetCharacter( p );

		/* If the character was a newline, count the line and start over,
		   otherwise, add it to the width and column counts */
		if ( c == '\n' )
		{
			if ( p >= maxPos )
			{
				*retPos = maxPos;
				*retLines = nLines;
				*retLineStart = lineStart;
				*retLineEnd = maxPos;
				return ;
			}
			nLines++;
			if ( nLines >= maxLines )
			{
				*retPos = p + 1;
				*retLines = nLines;
				*retLineStart = p + 1;
				*retLineEnd = p;
				return ;
			}
			lineStart = p + 1;
			colNum = 0;
			width = 0;
		}
		else
		{
			colNum += TextBuffer::CharWidth( c, colNum, tabDist, nullSubsChar );
			if ( countPixels )
			{
				expLen = TextBuffer::ExpandCharacter( c, colNum, expChar, tabDist,
				                                      nullSubsChar );
				fl_font( mTextfont, mTextsize );

				width += ( int ) fl_width( expChar, expLen );
			}
		}

		/* If character exceeded wrap margin, find the break point
		   and wrap there */
		if ( colNum > wrapMargin || width > maxWidth )
		{
			foundBreak = False;
			for ( b = p; b >= lineStart; b-- )
			{
				c = buf->GetCharacter( b );
				if ( c == '\t' || c == ' ' )
				{
					newLineStart = b + 1;
					if ( countPixels )
					{
						colNum = 0;
						width = 0;
						for ( i = b + 1; i < p + 1; i++ )
						{
							expLen = buf->GetExpandedChar( i, colNum, expChar );
							fl_font( mTextfont, mTextsize );

							width += ( int ) fl_width( expChar, expLen );

							colNum++;
						}
					}
					else
						colNum = buf->CountDispChars( b + 1, p + 1 );
					foundBreak = True;
					break;
				}
			}
			if ( !foundBreak )
			{ /* no whitespace, just break at margin */
				newLineStart = p;
				colNum = TextBuffer::CharWidth( c, colNum, tabDist, nullSubsChar );
				if ( countPixels )
				{
					expLen = TextBuffer::ExpandCharacter( c, colNum, expChar, tabDist,
					                                      nullSubsChar );
					fl_font( mTextfont, mTextsize );

					width += ( int ) fl_width( expChar, expLen );
				}
			}
			if ( p >= maxPos )
			{
				*retPos = maxPos;
				*retLines = maxPos < newLineStart ? nLines : nLines + 1;
				*retLineStart = maxPos < newLineStart ? lineStart :
				                newLineStart;
				*retLineEnd = maxPos;
				return ;
			}
			nLines++;
			if ( nLines >= maxLines )
			{
				*retPos = foundBreak ? b + 1 : p;
				*retLines = nLines;
				*retLineStart = lineStart;
				*retLineEnd = foundBreak ? b : p;
				return ;
			}
			lineStart = newLineStart;
		}
	}

	/* reached end of buffer before reaching pos or line target */
	*retPos = buf->mLength;
	*retLines = nLines;
	*retLineStart = lineStart;
	*retLineEnd = buf->mLength;
}


/*
** Finds both the end of the current line and the start of the next line.  Why?
** In continuous wrap mode, if you need to know both, figuring out one from the
** other can be expensive or error prone.  The problem comes when there's a
** trailing space or tab just before the end of the buffer.  To translate an
** end of line value to or from the next lines start value, you need to know
** whether the trailing space or tab is being used as a line break or just a
** normal character, and to find that out would otherwise require counting all
** the way back to the beginning of the line.
*/
void TextDisp::findLineEnd( int startPos, int startPosIsLineStart,
                            int *lineEnd, int *nextLineStart )
{
	int retLines, retLineStart;

	/* if we're not wrapping use more efficient BufEndOfLine */
	if ( !mContinuousWrap )
	{
		*lineEnd = mBuffer->EndOfLine( startPos );
		*nextLineStart = min( mBuffer->mLength, *lineEnd + 1 );
		return ;
	}

	/* use the wrapped line counter routine to count forward one line */
	wrappedLineCounter( mBuffer, startPos, mBuffer->mLength,
	                    1, startPosIsLineStart, nextLineStart, &retLines,
	                    &retLineStart, lineEnd );
	return ;
}

/*
** Line breaks in continuous wrap mode usually happen at newlines or
** whitespace.  This line-terminating character is not included in line
** width measurements and has a special status as a non-visible character.
** However, lines with no whitespace are wrapped without the benefit of a
** line terminating character, and this distinction causes endless trouble
** with all of the text display code which was originally written without
** continuous wrap mode and always expects to wrap at a newline character.
**
** Given the position of the end of the line, as returned by EndOfLine
** or BufEndOfLine, this returns true if there is a line terminating
** character, and false if there's not.  On the last character in the
** buffer, this function can't tell for certain whether a trailing space was
** used as a wrap point, and just guesses that it wasn't.  So if an exact
** accounting is necessary, don't use this function.
*/
int TextDisp::wrapUsesCharacter( int lineEndPos )
{
	char c;

	if ( !mContinuousWrap || lineEndPos == mBuffer->mLength )
		return True;

	c = mBuffer->GetCharacter( lineEndPos );
	return c == '\n' || ( ( c == '\t' || c == ' ' ) &&
	                      lineEndPos + 1 != mBuffer->mLength );
}

/*
** Decide whether the user needs (or may need) a horizontal scroll bar,
** and manage or unmanage the scroll bar widget accordingly.  The H.
** scroll bar is only hidden in continuous wrap mode when it's absolutely
** certain that the user will not need it: when wrapping is set
** to the window edge, or when the wrap margin is strictly less than
** the longest possible line.
*/
void TextDisp::hideOrShowHScrollBar()
{
	/*
	    if (mContinuousWrap && (mWrapMargin == 0 || mWrapMargin *
	    	    mFontStruct->max_bounds.width < w()))
	    	XtUnmanageChild(mHScrollBar);
	    else
	    	XtManageChild(mHScrollBar);
	*/
}

/*
** Return true if the Selection "sel" is rectangular, and touches a
** buffer position withing "rangeStart" to "rangeEnd"
*/
static int rangeTouchesRectSel( Selection *sel, int rangeStart, int rangeEnd )
{
	return sel->mSelected && sel->mRectangular && sel->mEnd >= rangeStart &&
	       sel->mStart <= rangeEnd;
}

/*
** Extend the range of a redraw request (from *start to *end) with additional
** redraw requests resulting from changes to the attached style buffer (which
** contains auxiliary information for coloring or styling text).
*/
void TextDisp::extendRangeForStyleMods( int *start, int *end )
{
	Selection * sel = &mStyleBuffer->mPrimary;
	int extended = False;

	/* The peculiar protocol used here is that modifications to the style
	   buffer are marked by selecting them with the buffer's primary Selection.
	   The style buffer is usually modified in response to a modify callback on
	   the text buffer BEFORE textDisp.c's modify callback, so that it can keep
	   the style buffer in step with the text buffer.  The style-update
	   callback can't just call for a redraw, because textDisp hasn't processed
	   the original text changes yet.  Anyhow, to minimize redrawing and to
	   avoid the complexity of scheduling redraws later, this simple protocol
	   tells the text display's buffer modify callback to extend it's redraw
	   range to show the text color/and font changes as well. */
	if ( sel->mSelected )
	{
		if ( sel->mStart < *start )
		{
			*start = sel->mStart;
			extended = True;
		}
		if ( sel->mEnd > *end )
		{
			*end = sel->mEnd;
			extended = True;
		}
	}

	/* If the Selection was extended due to a style change, and some of the
	   fonts don't match in spacing, extend redraw area to end of line to
	   redraw characters exposed by possible font size changes */
	if ( mFixedFontWidth == -1 && extended )
		* end = mBuffer->EndOfLine( *end ) + 1;
}


void TextDisp::draw( void )
{
	//	printf("damage=%d\n",damage());
	if ( damage() & FL_DAMAGE_ALL || damage() & FL_DAMAGE_EXPOSE || damage() & FL_DAMAGE_SCROLL )
	{
		RedisplayRect_( x(), y(), w(), h() );
	}
	if ( damage() & FL_DAMAGE_RANGE )
	{
		RedisplayRange_( damage_range_start, damage_range_end );
		damage_range_start = 0;
		damage_range_end = 0;
	}
	if ( damage() & FL_DAMAGE_CURSORPROTRUSIONS )
	{
		blankCursorProtrusions_();
	}
	if ( damage() & FL_DAMAGE_CURSOR )
	{
		drawCursor_( damage_cursor_x, damage_cursor_y );
	}
}
