File: shift.c

package info (click to toggle)
nedit 1%3A5.5-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 7,124 kB
  • ctags: 6,957
  • sloc: ansic: 92,920; xml: 1,427; yacc: 621; makefile: 342; awk: 40; sh: 10
file content (760 lines) | stat: -rw-r--r-- 24,615 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
static const char CVSID[] = "$Id: shift.c,v 1.16 2004/07/21 11:32:05 yooden Exp $";
/*******************************************************************************
*									       *
* shift.c -- Nirvana Editor built-in filter commands			       *
*									       *
* Copyright (C) 1999 Mark Edel						       *
*									       *
* This is free software; you can redistribute it and/or modify it under the    *
* terms of the GNU General Public License as published by the Free Software    *
* Foundation; either version 2 of the License, or (at your option) any later   *
* version. In addition, you may distribute version of this program linked to   *
* Motif or Open Motif. See README for details.                                 *
* 									       *
* This software is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or        *
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License        *
* for more details.							       *
* 									       *
* You should have received a copy of the GNU General Public License along with *
* software; if not, write to the Free Software Foundation, Inc., 59 Temple     *
* Place, Suite 330, Boston, MA  02111-1307 USA		                       *
*									       *
* Nirvana Text Editor	    						       *
* June 18, 1991								       *
*									       *
* Written by Mark Edel							       *
*									       *
*******************************************************************************/

#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

#include "shift.h"
#include "textBuf.h"
#include "text.h"
#include "nedit.h"
#include "window.h"

#include <string.h>
#include <limits.h>
#include <ctype.h>
#ifdef VMS
#include "../util/VMSparam.h"
#else
#ifndef __MVS__
#include <sys/param.h>
#endif
#endif /*VMS*/

#include <Xm/Xm.h>

#ifdef HAVE_DEBUG_H
#include "../debug.h"
#endif


static void shiftRect(WindowInfo *window, int direction, int byTab,
	int selStart, int selEnd, int rectStart, int rectEnd);
static void changeCase(WindowInfo *window, int makeUpper);
static char *shiftLineRight(char *line, int lineLen, int tabsAllowed,
	int tabDist, int nChars);
static char *shiftLineLeft(char *line, int lineLen, int tabDist, int nChars);
static int findLeftMargin(char *text, int length, int tabDist);
static char *fillParagraphs(char *text, int rightMargin, int tabDist,
	int useTabs, char nullSubsChar, int *filledLen, int alignWithFirst);
static char *fillParagraph(char *text, int leftMargin, int firstLineIndent,
	int rightMargin, int tabDist, int allowTabs, char nullSubsChar,
	int *filledLen);
static char *makeIndentString(int indent, int tabDist, int allowTabs, int *nChars);
static int atTabStop(int pos, int tabDist);
static int nextTab(int pos, int tabDist);
static int countLines(const char *text);
static int findParagraphStart(textBuffer *buf, int startPos);
static int findParagraphEnd(textBuffer *buf, int startPos);

/*
** Shift the selection left or right by a single character, or by one tab stop
** if "byTab" is true.  (The length of a tab stop is the size of an emulated
** tab if emulated tabs are turned on, or a hardware tab if not).
*/
void ShiftSelection(WindowInfo *window, int direction, int byTab)
{
    int selStart, selEnd, isRect, rectStart, rectEnd;
    int shiftedLen, newEndPos, cursorPos, origLength, emTabDist, shiftDist;
    char *text, *shiftedText;
    textBuffer *buf = window->buffer;

    /* get selection, if no text selected, use current insert position */
    if (!BufGetSelectionPos(buf, &selStart, &selEnd, &isRect,
    	    &rectStart, &rectEnd)) {
    	cursorPos = TextGetCursorPos(window->lastFocus);
    	selStart = BufStartOfLine(buf, cursorPos);
    	selEnd = BufEndOfLine(buf, cursorPos);
	if (selEnd < buf->length)
	    selEnd++;
	BufSelect(buf, selStart, selEnd);
    	isRect = False;
    	text = BufGetRange(buf, selStart, selEnd);
    } else if (isRect) {
	cursorPos = TextGetCursorPos(window->lastFocus);
	origLength = buf->length;
	shiftRect(window, direction, byTab, selStart, selEnd, rectStart,
		rectEnd);
	TextSetCursorPos(window->lastFocus, (cursorPos < (selEnd+selStart)/2) ?
		selStart : cursorPos + (buf->length - origLength));
	return;
    } else {
	selStart = BufStartOfLine(buf, selStart);
	if (selEnd != 0 && BufGetCharacter(buf, selEnd-1) != '\n') {
	    selEnd = BufEndOfLine(buf, selEnd);
	    if (selEnd < buf->length)
		selEnd++;
	}
	BufSelect(buf, selStart, selEnd);
	text = BufGetRange(buf, selStart, selEnd);
    }
    
    /* shift the text by the appropriate distance */
    if (byTab) {
    	XtVaGetValues(window->textArea, textNemulateTabs, &emTabDist, NULL);
    	shiftDist = emTabDist == 0 ? buf->tabDist : emTabDist;
    } else
    	shiftDist = 1;
    shiftedText = ShiftText(text, direction, buf->useTabs, buf->tabDist,
    	    shiftDist, &shiftedLen);
    XtFree(text);
    BufReplaceSelected(buf, shiftedText);
    XtFree(shiftedText);
    
    newEndPos = selStart + shiftedLen;
    BufSelect(buf, selStart, newEndPos);
}

static void shiftRect(WindowInfo *window, int direction, int byTab,
	int selStart, int selEnd, int rectStart, int rectEnd)
{
    int offset, emTabDist;
    textBuffer *tempBuf, *buf = window->buffer;
    char *text;
    
    /* Make sure selStart and SelEnd refer to whole lines */
    selStart = BufStartOfLine(buf, selStart);
    selEnd = BufEndOfLine(buf, selEnd);
    
    /* Calculate the the left/right offset for the new rectangle */
    if (byTab) {
    	XtVaGetValues(window->textArea, textNemulateTabs, &emTabDist, NULL);
    	offset = emTabDist == 0 ? buf->tabDist : emTabDist;
    } else
    	offset = 1;
    offset *= direction == SHIFT_LEFT ? -1 : 1;
    if (rectStart + offset < 0)
	offset = -rectStart;
    
    /* Create a temporary buffer for the lines containing the selection, to
       hide the intermediate steps from the display update routines */
    tempBuf = BufCreate();
    tempBuf->tabDist = buf->tabDist;
    tempBuf->useTabs = buf->useTabs;
    text = BufGetRange(buf, selStart, selEnd);
    BufSetAll(tempBuf, text);
    XtFree(text);
    
    /* Do the shift in the temporary buffer */
    text = BufGetTextInRect(buf, selStart, selEnd, rectStart, rectEnd);
    BufRemoveRect(tempBuf, 0, selEnd-selStart, rectStart, rectEnd);
    BufInsertCol(tempBuf, rectStart+offset, 0, text, NULL, NULL);
    XtFree(text);
    
    /* Make the change in the real buffer */
    text = BufGetAll(tempBuf);
    BufReplace(buf, selStart, selEnd, text);
    XtFree(text);
    BufRectSelect(buf, selStart, selStart + tempBuf->length,
	    rectStart+offset, rectEnd+offset);
    BufFree(tempBuf);
}

void UpcaseSelection(WindowInfo *window)
{
    changeCase(window, True);
}

void DowncaseSelection(WindowInfo *window)
{
    changeCase(window, False);
}

/*
** Capitalize or lowercase the contents of the selection (or of the character
** before the cursor if there is no selection).  If "makeUpper" is true,
** change to upper case, otherwise, change to lower case.
*/
static void changeCase(WindowInfo *window, int makeUpper)
{
    textBuffer *buf = window->buffer;
    char *text, *c;
    int cursorPos, start, end, isRect, rectStart, rectEnd;
    
    /* Get the selection.  Use character before cursor if no selection */
    if (!BufGetSelectionPos(buf, &start, &end, &isRect, &rectStart, &rectEnd)) {
    	char bufChar[2] = " ";
    	cursorPos = TextGetCursorPos(window->lastFocus);
    	if (cursorPos == 0) {
    	    XBell(TheDisplay, 0);
    	    return;
	}
    	*bufChar = BufGetCharacter(buf, cursorPos-1);
    	*bufChar = makeUpper ? toupper((unsigned char)*bufChar) :
		tolower((unsigned char)*bufChar);
    	BufReplace(buf, cursorPos-1, cursorPos, bufChar);
    } else {
	text = BufGetSelectionText(buf);
	for (c=text; *c!='\0'; c++)
    	    *c = makeUpper ? toupper((unsigned char)*c) :
		    tolower((unsigned char)*c);
	BufReplaceSelected(buf, text);
	XtFree(text);
	if (isRect)
	    BufRectSelect(buf, start, end, rectStart, rectEnd);
	else
	    BufSelect(buf, start, end);
    }
}

void FillSelection(WindowInfo *window)
{
    textBuffer *buf = window->buffer;
    char *text, *filledText;
    int left, right, nCols, len, isRect, rectStart, rectEnd;
    int rightMargin, wrapMargin;
    int insertPos = TextGetCursorPos(window->lastFocus);
    int hasSelection = window->buffer->primary.selected;
    
    /* Find the range of characters and get the text to fill.  If there is a
       selection, use it but extend non-rectangular selections to encompass
       whole lines.  If there is no selection, find the paragraph containing
       the insertion cursor */
    if (!BufGetSelectionPos(buf, &left, &right, &isRect, &rectStart, &rectEnd)) {
	left = findParagraphStart(buf, insertPos);
	right = findParagraphEnd(buf, insertPos);
	if (left == right) {
    	    XBell(TheDisplay, 0);
    	    return;
	}
	text = BufGetRange(buf, left, right);
    } else if (isRect) {
    	left = BufStartOfLine(buf, left);
    	right = BufEndOfLine(buf, right);
    	text = BufGetTextInRect(buf, left, right, rectStart, INT_MAX);
    } else {
	left = BufStartOfLine(buf, left);
	if (right != 0 && BufGetCharacter(buf, right-1) != '\n') {
	    right = BufEndOfLine(buf, right);
	    if (right < buf->length)
		right++;
	}
    	BufSelect(buf, left, right);
    	text = BufGetRange(buf, left, right);
    }
    
    /* Find right margin either as specified in the rectangular selection, or
       by measuring the text and querying the window's wrap margin (or width) */
    if (hasSelection && isRect) {
    	rightMargin = rectEnd - rectStart;
    } else
    {
        XtVaGetValues(window->textArea,
                textNcolumns, &nCols,
                textNwrapMargin, &wrapMargin,
                NULL);
        rightMargin = (wrapMargin == 0 ? nCols : wrapMargin);
    }
    
    /* Fill the text */
    filledText = fillParagraphs(text, rightMargin, buf->tabDist, buf->useTabs,
	    buf->nullSubsChar, &len, False);
    XtFree(text);
        
    /* Replace the text in the window */
    if (hasSelection && isRect) {
        BufReplaceRect(buf, left, right, rectStart, INT_MAX, filledText);
        BufRectSelect(buf, left,
        	BufEndOfLine(buf, BufCountForwardNLines(buf, left,
        	countLines(filledText)-1)), rectStart, rectEnd);
    } else {
	BufReplace(buf, left, right, filledText);
	if (hasSelection)
    	    BufSelect(buf, left, left + len);
    }
    XtFree(filledText);
    
    /* Find a reasonable cursor position.  Usually insertPos is best, but
       if the text was indented, positions can shift */
    if (hasSelection && isRect)
    	TextSetCursorPos(window->lastFocus, buf->cursorPosHint);
    else
	TextSetCursorPos(window->lastFocus, insertPos < left ? left :
    		(insertPos > left + len ? left + len : insertPos));
}

/*
** shift lines left and right in a multi-line text string.  Returns the
** shifted text in memory that must be freed by the caller with XtFree.
*/
char *ShiftText(char *text, int direction, int tabsAllowed, int tabDist,
	int nChars, int *newLen)
{
    char *shiftedText, *shiftedLine;
    char *textPtr, *lineStartPtr, *shiftedPtr;
    int bufLen;
    
    /*
    ** Allocate memory for shifted string.  Shift left adds a maximum of
    ** tabDist-2 characters per line (remove one tab, add tabDist-1 spaces).
    ** Shift right adds a maximum of nChars character per line.
    */
    if (direction == SHIFT_RIGHT)
        bufLen = strlen(text) + countLines(text) * nChars;
    else
        bufLen = strlen(text) + countLines(text) * tabDist;
    shiftedText = (char *)XtMalloc(bufLen + 1);
    
    /*
    ** break into lines and call shiftLine(Left/Right) on each
    */
    lineStartPtr = text;
    textPtr = text;
    shiftedPtr = shiftedText;
    while (TRUE) {
	if (*textPtr=='\n' || *textPtr=='\0') {
	    shiftedLine = (direction == SHIFT_RIGHT) ?
		    shiftLineRight(lineStartPtr, textPtr-lineStartPtr,
		        tabsAllowed, tabDist, nChars) :
	    	    shiftLineLeft(lineStartPtr, textPtr-lineStartPtr, tabDist,
			nChars);
	    strcpy(shiftedPtr, shiftedLine);
	    shiftedPtr += strlen(shiftedLine);
	    XtFree(shiftedLine);
	    if (*textPtr == '\0') {
	        /* terminate string & exit loop at end of text */
	    	*shiftedPtr = '\0';
		break;
	    } else {
	    	/* move the newline from text to shifted text */
		*shiftedPtr++ = *textPtr++;
	    }
	    /* start line over */
	    lineStartPtr = textPtr;
	} else
	    textPtr++;
    }
    *newLen = shiftedPtr - shiftedText;
    return shiftedText;
}

static char *shiftLineRight(char *line, int lineLen, int tabsAllowed,
	int tabDist, int nChars)
{
    char *lineOut;
    char *lineInPtr, *lineOutPtr;
    int whiteWidth, i;
    
    lineInPtr = line;
    lineOut = XtMalloc(lineLen + nChars + 1);
    lineOutPtr = lineOut;
    whiteWidth = 0;
    while (TRUE) {
        if (*lineInPtr == '\0' || (lineInPtr - line) >= lineLen) {
	    /* nothing on line, wipe it out */
	    *lineOut = '\0';
	    return lineOut;
        } else if (*lineInPtr == ' ') {
	    /* white space continues with tab, advance to next tab stop */
	    whiteWidth++;
	    *lineOutPtr++ = *lineInPtr++;
	} else if (*lineInPtr == '\t') {
	    /* white space continues with tab, advance to next tab stop */
	    whiteWidth = nextTab(whiteWidth, tabDist);
	    *lineOutPtr++ = *lineInPtr++;
	} else {
	    /* end of white space, add nChars of space */
	    for (i=0; i<nChars; i++) {
		*lineOutPtr++ = ' ';
		whiteWidth++;
		/* if we're now at a tab stop, change last 8 spaces to a tab */
		if (tabsAllowed && atTabStop(whiteWidth, tabDist)) {
		    lineOutPtr -= tabDist;
		    *lineOutPtr++ = '\t';
		}
	    }
	    /* move remainder of line */
    	    while (*lineInPtr!='\0' && (lineInPtr - line) < lineLen)
		*lineOutPtr++ = *lineInPtr++;
	    *lineOutPtr = '\0';
	    return lineOut;
	}
    }
}

static char *shiftLineLeft(char *line, int lineLen, int tabDist, int nChars)
{
    char *lineOut;
    int i, whiteWidth, lastWhiteWidth, whiteGoal;
    char *lineInPtr, *lineOutPtr;
    
    lineInPtr = line;
    lineOut = XtMalloc(lineLen + tabDist + 1);
    lineOutPtr = lineOut;
    whiteWidth = 0;
    lastWhiteWidth = 0;
    while (TRUE) {
        if (*lineInPtr == '\0' || (lineInPtr - line) >= lineLen) {
	    /* nothing on line, wipe it out */
	    *lineOut = '\0';
	    return lineOut;
        } else if (*lineInPtr == ' ') {
	    /* white space continues with space, advance one character */
	    whiteWidth++;
	    *lineOutPtr++ = *lineInPtr++;
	} else if (*lineInPtr == '\t') {
	    /* white space continues with tab, advance to next tab stop	    */
	    /* save the position, though, in case we need to remove the tab */
	    lastWhiteWidth = whiteWidth;
	    whiteWidth = nextTab(whiteWidth, tabDist);
	    *lineOutPtr++ = *lineInPtr++;
	} else {
	    /* end of white space, remove nChars characters */
	    for (i=1; i<=nChars; i++) {
		if (lineOutPtr > lineOut) {
		    if (*(lineOutPtr-1) == ' ') {
			/* end of white space is a space, just remove it */
			lineOutPtr--;
		    } else {
	    		/* end of white space is a tab, remove it and add
	    		   back spaces */
			lineOutPtr--;
			whiteGoal = whiteWidth - i;
			whiteWidth = lastWhiteWidth;
			while (whiteWidth < whiteGoal) {
			    *lineOutPtr++ = ' ';
			    whiteWidth++;
			}
		    }
		}
	    }
	    /* move remainder of line */
    	    while (*lineInPtr!='\0' && (lineInPtr - line) < lineLen)
		*lineOutPtr++ = *lineInPtr++;
	    /* add a null */
	    *lineOutPtr = '\0';
	    return lineOut;
	}
    }
}
       
static int atTabStop(int pos, int tabDist)
{
    return (pos%tabDist == 0);
}

static int nextTab(int pos, int tabDist)
{
    return (pos/tabDist)*tabDist + tabDist;
}

static int countLines(const char *text)
{
    int count = 1;
    
    while(*text != '\0') {
    	if (*text++ == '\n') {
	    count++;
	}
    }
    return count;
}

/*
** Find the implied left margin of a text string (the number of columns to the
** first non-whitespace character on any line) up to either the terminating
** null character at the end of the string, or "length" characters, whever
** comes first.
*/
static int findLeftMargin(char *text, int length, int tabDist)
{
    char *c;
    int col = 0, leftMargin = INT_MAX;
    int inMargin = True;
    
    for (c=text; *c!='\0' && c-text<length; c++) {
    	if (*c == '\t') {
    	    col += BufCharWidth('\t', col, tabDist, '\0');
    	} else if (*c == ' ') {
    	    col++;
    	} else if (*c == '\n') {
	    col = 0;
    	    inMargin = True;
    	} else {
    	    /* non-whitespace */
    	    if (col < leftMargin && inMargin)
    	    	leftMargin = col;
    	    inMargin = False;
    	}
    }
    
    /* if no non-white text is found, the leftMargin will never be set */
    if (leftMargin == INT_MAX)
    	return 0;
    
    return leftMargin;
}

/*
** Fill multiple paragraphs between rightMargin and an implied left margin
** and first line indent determined by analyzing the text.  alignWithFirst
** aligns subsequent paragraphs with the margins of the first paragraph (a
** capability not currently used in NEdit, but carried over from code for
** previous versions which did all paragraphs together).
*/
static char *fillParagraphs(char *text, int rightMargin, int tabDist,
	int useTabs, char nullSubsChar, int *filledLen, int alignWithFirst)
{
    int paraStart, paraEnd, fillEnd;
    char *c, ch, *secondLineStart, *paraText, *filledText;
    int firstLineLen, firstLineIndent, leftMargin, len;
    textBuffer *buf;
    
    /* Create a buffer to accumulate the filled paragraphs */
    buf = BufCreate();
    BufSetAll(buf, text);
    
    /*
    ** Loop over paragraphs, filling each one, and accumulating the results
    ** in buf
    */
    paraStart = 0;
    for (;;) {
	
	/* Skip over white space */
	while (paraStart < buf->length) {
	    ch = BufGetCharacter(buf, paraStart);
	    if (ch != ' ' && ch != '\t' && ch != '\n')
	    	break;
	    paraStart++;
	}
	if (paraStart >= buf->length)
	    break;
	paraStart = BufStartOfLine(buf, paraStart);
	
	/* Find the end of the paragraph */
	paraEnd = findParagraphEnd(buf, paraStart);
	
	/* Operate on either the one paragraph, or to make them all identical,
	   do all of them together (fill paragraph can format all the paragraphs
	   it finds with identical specs if it gets passed more than one) */
	fillEnd = alignWithFirst ? buf->length :  paraEnd;

	/* Get the paragraph in a text string (or all of the paragraphs if
	   we're making them all the same) */
	paraText = BufGetRange(buf, paraStart, fillEnd);
	
	/* Find separate left margins for the first and for the first line of
	   the paragraph, and for rest of the remainder of the paragraph */
	for (c=paraText ; *c!='\0' && *c!='\n'; c++);
	firstLineLen = c - paraText;
	secondLineStart = *c == '\0' ? paraText : c + 1;
	firstLineIndent = findLeftMargin(paraText, firstLineLen, tabDist);
	leftMargin = findLeftMargin(secondLineStart, paraEnd - paraStart -
		(secondLineStart - paraText), tabDist);

	/* Fill the paragraph */
	filledText = fillParagraph(paraText, leftMargin, firstLineIndent,
		rightMargin, tabDist, useTabs, nullSubsChar, &len);
	XtFree(paraText);
	
	/* Replace it in the buffer */
	BufReplace(buf, paraStart, fillEnd, filledText);
	XtFree(filledText);
	
	/* move on to the next paragraph */
	paraStart += len;
    }
    
    /* Free the buffer and return its contents */
    filledText = BufGetAll(buf);
    *filledLen = buf->length;
    BufFree(buf);
    return filledText;
}

/*
** Trim leading space, and arrange text to fill between leftMargin and
** rightMargin (except for the first line which fills from firstLineIndent),
** re-creating whitespace to the left of the text using tabs (if allowTabs is
** True) calculated using tabDist, and spaces.  Returns a newly allocated
** string as the function result, and the length of the new string in filledLen.
*/
static char *fillParagraph(char *text, int leftMargin, int firstLineIndent,
	int rightMargin, int tabDist, int allowTabs, char nullSubsChar,
	int *filledLen)
{
    char *cleanedText, *outText, *indentString, *leadIndentStr, *outPtr, *c, *b;
    int col, cleanedLen, indentLen, leadIndentLen, nLines = 1;
    int inWhitespace, inMargin;
    
    /* remove leading spaces, convert newlines to spaces */
    cleanedText = XtMalloc(strlen(text)+1);
    outPtr = cleanedText;
    inMargin = True;
    for (c=text; *c!='\0'; c++) {
    	if (*c == '\t' || *c == ' ') {
    	    if (!inMargin)
    	    	*outPtr++ = *c;
    	} else if (*c == '\n') {
    	    if (inMargin) {
    	    	/* a newline before any text separates paragraphs, so leave
    	    	   it in, back up, and convert the previous space back to \n */
    	    	if (outPtr > cleanedText && *(outPtr-1) == ' ')
    	    	    *(outPtr-1) = '\n';
    	    	*outPtr++ = '\n';
    	    	nLines +=2;
    	    } else
    	    	*outPtr++ = ' ';
    	    inMargin = True;
    	} else {
    	    *outPtr++ = *c;
    	    inMargin = False;
    	}
    }
    cleanedLen = outPtr - cleanedText;
    *outPtr = '\0';
    
    /* Put back newlines breaking text at word boundaries within the margins.
       Algorithm: scan through characters, counting columns, and when the
       margin width is exceeded, search backward for beginning of the word
       and convert the last whitespace character into a newline */
    col = firstLineIndent;
    for (c=cleanedText; *c!='\0'; c++) {
    	if (*c == '\n')
    	    col = leftMargin;
    	else
    	    col += BufCharWidth(*c, col, tabDist, nullSubsChar);
    	if (col-1 > rightMargin) {
    	    inWhitespace = True;
    	    for (b=c; b>=cleanedText && *b!='\n'; b--) {
    	    	if (*b == '\t' || *b == ' ') {
    	    	    if (!inWhitespace) {
    	    		*b = '\n';
    	    		c = b;
    	    		col = leftMargin;
     	    		nLines++;
   	    		break;
    	    	    }
    	    	} else 
    	    	    inWhitespace = False;
    	    }
    	}
    }
    nLines++;

    /* produce a string to prepend to lines to indent them to the left margin */
    leadIndentStr = makeIndentString(firstLineIndent, tabDist,
	    allowTabs, &leadIndentLen);
    indentString = makeIndentString(leftMargin, tabDist, allowTabs, &indentLen);
        
    /* allocate memory for the finished string */
    outText = XtMalloc(sizeof(char) * (cleanedLen + leadIndentLen +
	    indentLen * (nLines-1) + 1));
    outPtr = outText;
    
    /* prepend the indent string to each line of the filled text */
    strncpy(outPtr, leadIndentStr, leadIndentLen);
    outPtr += leadIndentLen;
    for (c=cleanedText; *c!='\0'; c++) {
    	*outPtr++ = *c;
    	if (*c == '\n') {
    	    strncpy(outPtr, indentString, indentLen);
    	    outPtr += indentLen;
    	}
    }
    
    /* convert any trailing space to newline.  Add terminating null */
    if (*(outPtr-1) == ' ')
    	*(outPtr-1) = '\n';
    *outPtr = '\0';
    
    /* clean up, return result */
    XtFree(cleanedText);
    XtFree(leadIndentStr);
    XtFree(indentString);
    *filledLen = outPtr - outText;
    return outText;
}

static char *makeIndentString(int indent, int tabDist, int allowTabs, int *nChars)
{
    char *indentString, *outPtr;
    int i;
    
    outPtr = indentString = XtMalloc(sizeof(char) * indent + 1);
    if (allowTabs) {
	for (i=0; i<indent/tabDist; i++)
    	    *outPtr++ = '\t';
	for (i=0; i<indent%tabDist; i++)
    	    *outPtr++ = ' ';
    } else {
    	for (i=0; i<indent; i++)
    	    *outPtr++ = ' ';
    }
    *outPtr = '\0';
    *nChars = outPtr - indentString;
    return indentString;
}

/*
** Find the boundaries of the paragraph containing pos
*/
static int findParagraphEnd(textBuffer *buf, int startPos)
{
    char c;
    int pos;
    static char whiteChars[] = " \t";

    pos = BufEndOfLine(buf, startPos)+1;
    while (pos < buf->length) {
    	c = BufGetCharacter(buf, pos);
    	if (c == '\n')
    	    break;
    	if (strchr(whiteChars, c) != NULL)
    	    pos++;
    	else
    	    pos = BufEndOfLine(buf, pos)+1;
    }
    return pos < buf->length ? pos : buf->length;
}
static int findParagraphStart(textBuffer *buf, int startPos)
{
    char c;
    int pos, parStart;
    static char whiteChars[] = " \t";

    if (startPos == 0)
    	return 0;
    parStart = BufStartOfLine(buf, startPos);
    pos = parStart - 2;
    while (pos > 0) {
    	c = BufGetCharacter(buf, pos);
    	if (c == '\n')
    	    break;
    	if (strchr(whiteChars, c) != NULL)
    	    pos--;
    	else {
    	    parStart = BufStartOfLine(buf, pos);
    	    pos = parStart - 2;
    	}
    }
    return parStart > 0 ? parStart : 0;
}