]> git.lyx.org Git - lyx.git/blob - src/text.C
lots of small stuff
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "buffer.h"
22 #include "bufferparams.h"
23 #include "BufferView.h"
24 #include "debug.h"
25 #include "encoding.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "language.h"
29 #include "LColor.h"
30 #include "lyxlength.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lyxrow_funcs.h"
34 #include "metricsinfo.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "rowpainter.h"
39 #include "text_funcs.h"
40 #include "undo.h"
41 #include "vspace.h"
42 #include "WordLangTuple.h"
43
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46
47 #include "insets/insettext.h"
48
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
51
52 using bv_funcs::number;
53
54 using lyx::pos_type;
55 using lyx::word_location;
56
57 using lyx::support::contains;
58 using lyx::support::lowercase;
59 using lyx::support::uppercase;
60
61 using std::max;
62 using std::endl;
63 using std::string;
64
65
66 /// top, right, bottom pixel margin
67 extern int const PAPER_MARGIN = 20;
68 /// margin for changebar
69 extern int const CHANGEBAR_MARGIN = 10;
70 /// left margin
71 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
72
73
74
75 int bibitemMaxWidth(BufferView *, LyXFont const &);
76
77
78 namespace {
79
80 unsigned int maxParagraphWidth(ParagraphList const & plist)
81 {
82         unsigned int width = 0;
83         ParagraphList::const_iterator pit = plist.begin();
84         ParagraphList::const_iterator end = plist.end();
85                 for (; pit != end; ++pit)
86                         width = std::max(width, pit->width);
87         return width;
88 }
89
90 } // namespace anon
91
92
93 BufferView * LyXText::bv()
94 {
95         BOOST_ASSERT(bv_owner != 0);
96         return bv_owner;
97 }
98
99
100 double LyXText::spacing(Paragraph const & par) const
101 {
102         if (par.params().spacing().isDefault())
103                 return bv()->buffer()->params().spacing().getValue();
104         return par.params().spacing().getValue();
105 }
106
107
108 BufferView * LyXText::bv() const
109 {
110         BOOST_ASSERT(bv_owner != 0);
111         return bv_owner;
112 }
113
114
115 void LyXText::updateRowPositions()
116 {
117         ParagraphList::iterator pit = ownerParagraphs().begin();
118         ParagraphList::iterator end = ownerParagraphs().end();
119         for (height = 0; pit != end; ++pit) {
120                 pit->y = height;
121                 height += pit->height;
122         }
123 }
124
125
126 int LyXText::workWidth() const
127 {
128         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
129 }
130
131
132 int LyXText::getRealCursorX() const
133 {
134         int x = cursor.x();
135         if (the_locking_inset && the_locking_inset->getLyXText(bv()) != this)
136                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
137         return x;
138 }
139
140
141 // This is the comments that some of the warnings below refers to.
142 // There are some issues in this file and I don't think they are
143 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
144 // this is a problem that has been here almost from day one and that a
145 // larger userbase with different access patters triggers the bad
146 // behaviour. (segfaults.) What I think happen is: In several places
147 // we store the paragraph in the current cursor and then moves the
148 // cursor. This movement of the cursor will delete paragraph at the
149 // old position if it is now empty. This will make the temporary
150 // pointer to the old cursor paragraph invalid and dangerous to use.
151 // And is some cases this will trigger a segfault. I have marked some
152 // of the cases where this happens with a warning, but I am sure there
153 // are others in this file and in text2.C. There is also a note in
154 // Delete() that you should read. In Delete I store the paragraph->id
155 // instead of a pointer to the paragraph. I am pretty sure this faulty
156 // use of temporary pointers to paragraphs that might have gotten
157 // invalidated (through a cursor movement) before they are used, are
158 // the cause of the strange crashes we get reported often.
159 //
160 // It is very tiresom to change this code, especially when it is as
161 // hard to read as it is. Help to fix all the cases where this is done
162 // would be greately appreciated.
163 //
164 // Lgb
165
166 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
167 {
168         if (pos >= pit->size())
169                 return 0;
170
171         char const c = pit->getChar(pos);
172         LyXFont const & font = getFont(pit, pos);
173         return singleWidth(pit, pos, c, font);
174 }
175
176
177 int LyXText::singleWidth(ParagraphList::iterator pit,
178                          pos_type pos, char c, LyXFont const & font) const
179 {
180         if (pos >= pit->size()) {
181                 lyxerr << "in singleWidth(), pos: " << pos << endl;
182                 BOOST_ASSERT(false);
183                 return 0;
184         }
185
186         // The most common case is handled first (Asger)
187         if (IsPrintable(c)) {
188                 if (!font.language()->RightToLeft()) {
189                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
190                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
191                             && font.language()->lang() == "arabic") {
192                                 if (Encodings::IsComposeChar_arabic(c))
193                                         return 0;
194                                 else
195                                         c = pit->transformChar(c, pos);
196                         } else if (font.language()->lang() == "hebrew" &&
197                                  Encodings::IsComposeChar_hebrew(c))
198                                 return 0;
199                 }
200                 return font_metrics::width(c, font);
201         }
202
203         if (c == Paragraph::META_INSET) 
204                 return pit->getInset(pos)->width();
205
206         if (IsSeparatorChar(c))
207                 c = ' ';
208         return font_metrics::width(c, font);
209 }
210
211
212 int LyXText::leftMargin(ParagraphList::iterator pit, Row const & row) const
213 {
214         LyXTextClass const & tclass =
215                 bv()->buffer()->params().getLyXTextClass();
216         LyXLayout_ptr const & layout = pit->layout();
217
218         string parindent = layout->parindent;
219
220         int x = LEFT_MARGIN;
221
222         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
223
224         // this is the way, LyX handles the LaTeX-Environments.
225         // I have had this idea very late, so it seems to be a
226         // later added hack and this is true
227         if (pit->getDepth() == 0) {
228                 if (pit->layout() == tclass.defaultLayout()) {
229                         // find the previous same level paragraph
230                         if (pit != ownerParagraphs().begin()) {
231                                 ParagraphList::iterator newpit =
232                                         depthHook(pit, ownerParagraphs(), pit->getDepth());
233                                 if (newpit == pit && newpit->layout()->nextnoindent)
234                                         parindent.erase();
235                         }
236                 }
237         } else {
238                 // find the next level paragraph
239                 ParagraphList::iterator newpar =
240                         outerHook(pit, ownerParagraphs());
241
242                 // make a corresponding row. Needed to call leftMargin()
243                 // check wether it is a sufficent paragraph
244                 if (newpar != ownerParagraphs().end()
245                     && newpar->layout()->isEnvironment()) {
246                         x = leftMargin(newpar, Row(newpar->size()));
247                 }
248
249                 if (newpar != ownerParagraphs().end()
250                     && pit->layout() == tclass.defaultLayout()) {
251                         if (newpar->params().noindent())
252                                 parindent.erase();
253                         else
254                                 parindent = newpar->layout()->parindent;
255                 }
256         }
257
258         LyXFont const labelfont = getLabelFont(pit);
259         switch (layout->margintype) {
260         case MARGIN_DYNAMIC:
261                 if (!layout->leftmargin.empty())
262                         x += font_metrics::signedWidth(layout->leftmargin,
263                                                   tclass.defaultfont());
264                 if (!pit->getLabelstring().empty()) {
265                         x += font_metrics::signedWidth(layout->labelindent,
266                                                   labelfont);
267                         x += font_metrics::width(pit->getLabelstring(),
268                                             labelfont);
269                         x += font_metrics::width(layout->labelsep, labelfont);
270                 }
271                 break;
272
273         case MARGIN_MANUAL:
274                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
275                 // The width of an empty par, even with manual label, should be 0
276                 if (!pit->empty() && row.pos() >= pit->beginningOfBody()) {
277                         if (!pit->getLabelWidthString().empty()) {
278                                 x += font_metrics::width(pit->getLabelWidthString(),
279                                                labelfont);
280                                 x += font_metrics::width(layout->labelsep, labelfont);
281                         }
282                 }
283                 break;
284
285         case MARGIN_STATIC:
286                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
287                         / (pit->getDepth() + 4);
288                 break;
289
290         case MARGIN_FIRST_DYNAMIC:
291                 if (layout->labeltype == LABEL_MANUAL) {
292                         if (row.pos() >= pit->beginningOfBody()) {
293                                 x += font_metrics::signedWidth(layout->leftmargin,
294                                                           labelfont);
295                         } else {
296                                 x += font_metrics::signedWidth(layout->labelindent,
297                                                           labelfont);
298                         }
299                 } else if (row.pos()
300                            // Special case to fix problems with
301                            // theorems (JMarc)
302                            || (layout->labeltype == LABEL_STATIC
303                                && layout->latextype == LATEX_ENVIRONMENT
304                                && !isFirstInSequence(pit, ownerParagraphs()))) {
305                         x += font_metrics::signedWidth(layout->leftmargin,
306                                                   labelfont);
307                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
308                            && layout->labeltype != LABEL_BIBLIO
309                            && layout->labeltype !=
310                            LABEL_CENTERED_TOP_ENVIRONMENT) {
311                         x += font_metrics::signedWidth(layout->labelindent,
312                                                   labelfont);
313                         x += font_metrics::width(layout->labelsep, labelfont);
314                         x += font_metrics::width(pit->getLabelstring(),
315                                             labelfont);
316                 }
317                 break;
318
319         case MARGIN_RIGHT_ADDRESS_BOX: {
320                 // ok, a terrible hack. The left margin depends on the widest
321                 // row in this paragraph.
322                 RowList::iterator rit = pit->rows.begin();
323                 RowList::iterator end = pit->rows.end();
324 #warning This is wrong.
325                 int minfill = workWidth() / 2;
326                 for ( ; rit != end; ++rit)
327                         if (rit->fill() < minfill)
328                                 minfill = rit->fill();
329                 x += font_metrics::signedWidth(layout->leftmargin,
330                         tclass.defaultfont());
331                 x += minfill;
332         }
333         break;
334         }
335
336         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
337                 LyXLength const len = pit->params().leftIndent();
338                 int const tw = inset_owner ?
339                         inset_owner->latexTextWidth(bv()) : workWidth();
340                 x += len.inPixels(tw);
341         }
342
343         LyXAlignment align;
344
345         if (pit->params().align() == LYX_ALIGN_LAYOUT)
346                 align = layout->align;
347         else
348                 align = pit->params().align();
349
350         // set the correct parindent
351         if (row.pos() == 0) {
352                 if ((layout->labeltype == LABEL_NO_LABEL
353                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
354                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
355                      || (layout->labeltype == LABEL_STATIC
356                          && layout->latextype == LATEX_ENVIRONMENT
357                          && !isFirstInSequence(pit, ownerParagraphs())))
358                     && align == LYX_ALIGN_BLOCK
359                     && !pit->params().noindent()
360                         // in tabulars and ert paragraphs are never indented!
361                         && (!pit->inInset() || !pit->inInset()->owner() ||
362                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
363                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
364                     && (pit->layout() != tclass.defaultLayout() ||
365                         bv()->buffer()->params().paragraph_separation ==
366                         BufferParams::PARSEP_INDENT)) {
367                         x += font_metrics::signedWidth(parindent,
368                                                   tclass.defaultfont());
369                 } else if (layout->labeltype == LABEL_BIBLIO) {
370                         // ale970405 Right width for bibitems
371                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
372                 }
373         }
374
375         return x;
376 }
377
378
379 int LyXText::rightMargin(Paragraph const & par, Buffer const & buf) const
380 {
381         LyXTextClass const & tclass = buf.params().getLyXTextClass();
382         LyXLayout_ptr const & layout = par.layout();
383
384         return PAPER_MARGIN
385                 + font_metrics::signedWidth(tclass.rightmargin(),
386                                        tclass.defaultfont())
387                 + font_metrics::signedWidth(layout->rightmargin,
388                                        tclass.defaultfont())
389                 * 4 / (par.getDepth() + 4);
390 }
391
392
393 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
394 {
395         // labelEnd is only needed if the layout fills a flushleft label.
396         if (pit->layout()->margintype != MARGIN_MANUAL)
397                 return 0;
398
399         Row tmprow = row;
400         tmprow.pos(pit->size());
401         // return the beginning of the body
402         return leftMargin(pit, tmprow);
403 }
404
405
406 namespace {
407
408 // this needs special handling - only newlines count as a break point
409 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
410 {
411         pos_type const end = par.size();
412         
413         for (; i < end; ++i)
414                 if (par.isNewline(i))
415                         return i + 1;
416
417         return end;
418 }
419
420 };
421
422
423 void LyXText::rowBreakPoint(ParagraphList::iterator pit, Row & row) const
424 {
425         pos_type const end = pit->size();
426         pos_type const pos = row.pos();
427         if (pos == end) {
428                 row.endpos(end);
429                 return;
430         }
431         
432         // maximum pixel width of a row.
433         int width = workWidth() - rightMargin(*pit, *bv()->buffer());
434 //              - leftMargin(pit, row);
435
436         // inset->textWidth() returns -1 via workWidth(),
437         // but why ?
438         if (width < 0) {
439                 row.endpos(end);
440                 return;
441         }
442
443         LyXLayout_ptr const & layout = pit->layout();
444
445         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
446                 row.endpos(addressBreakPoint(pos, *pit));
447                 return;
448         }
449
450         pos_type const body_pos = pit->beginningOfBody();
451
452
453         // Now we iterate through until we reach the right margin
454         // or the end of the par, then choose the possible break
455         // nearest that.
456
457         int const left = leftMargin(pit, row);
458         int x = left;
459
460         // pixel width since last breakpoint
461         int chunkwidth = 0;
462
463
464         // We re-use the font resolution for the entire font span when possible
465         LyXFont font = getFont(pit, pos);
466         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(pos);
467
468         pos_type point = end;
469         pos_type i = pos;
470         for ( ; i < end; ++i) {
471                 if (pit->isNewline(i)) {
472                         point = i + 1;
473                         break;
474                 }
475                 // Break before...      
476                 if (i + 1 < end) {
477                         InsetOld * in = pit->getInset(i + 1);
478                         if (in && in->display()) {
479                                 point = i + 1;
480                                 break;
481                         }
482                         // ...and after.
483                         in = pit->getInset(i);
484                         if (in && in->display()) {
485                                 point = i + 1;
486                                 break;
487                         }
488                 }
489
490                 char const c = pit->getChar(i);
491  
492                 if (i > endPosOfFontSpan) {
493                         font = getFont(pit, i);
494                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
495                 }
496                 
497                 {
498                         int thiswidth = singleWidth(pit, i, c, font);
499
500                         // add the auto-hfill from label end to the body
501                         if (body_pos && i == body_pos) {
502                                 int add = font_metrics::width(layout->labelsep, getLabelFont(pit));
503                                 if (pit->isLineSeparator(i - 1))
504                                         add -= singleWidth(pit, i - 1);
505
506                                 add = std::max(add, labelEnd(pit, row) - x);
507                                 thiswidth += add;
508                         }
509
510                         x += thiswidth;
511                         //lyxerr << "i: " << i << " x: "
512                         //<< x << " width: " << width << endl;
513                         chunkwidth += thiswidth;
514                 }
515                 
516
517                 // break before a character that will fall off
518                 // the right of the row
519                 if (x >= width) {
520                         // if no break before, break here
521                         if (point == end || chunkwidth >= width - left) {
522                                 if (i > pos) {
523                                         point = i;
524                                         break;  
525                                 }
526                         }
527                         // exit on last registered breakpoint:
528                         if (i + 1 < end)
529                                 break;
530                 }
531
532                 InsetOld * in = pit->getInset(i);
533                 if (!in || in->isChar()) {
534                         // some insets are line separators too
535                         if (pit->isLineSeparator(i)) {
536                                 // register breakpoint:
537                                 point = i + 1; 
538                                 chunkwidth = 0;
539                         }
540                 }
541         }
542
543         if (point == end && i != end && x >= width) {
544                 // didn't find one, break at the point we reached the edge
545                 point = i + 1;
546         } else if (i == end && x < width) {
547                 // maybe found one, but the par is short enough.
548                 point = end;
549         }
550
551         // manual labels cannot be broken in LaTeX. But we
552         // want to make our on-screen rendering of footnotes
553         // etc. still break
554         if (body_pos && point < body_pos)
555                 point = body_pos;
556
557         row.endpos(point);
558 }
559
560
561 // returns the minimum space a row needs on the screen in pixel
562 void LyXText::fill(ParagraphList::iterator pit, Row & row, int workwidth) const
563 {
564         // get the pure distance
565         pos_type const end = row.endpos();
566
567         LyXLayout_ptr const & layout = pit->layout();
568         int w = leftMargin(pit, row);
569
570         pos_type const body_pos = pit->beginningOfBody();
571         pos_type i = row.pos();
572
573         if (i < end) {
574                 // We re-use the font resolution for the entire span when possible
575                 LyXFont font = getFont(pit, i);
576                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
577                 for ( ; i < end; ++i) {
578                         if (body_pos > 0 && i == body_pos) {
579                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
580                                 if (pit->isLineSeparator(i - 1))
581                                         w -= singleWidth(pit, i - 1);
582                                 w = max(w, labelEnd(pit, row));
583                         }
584                         char const c = pit->getChar(i);
585                         if (IsPrintable(c) && i > endPosOfFontSpan) {
586                                 // We need to get the next font
587                                 font = getFont(pit, i);
588                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
589                         }
590                         w += singleWidth(pit, i, c, font);
591                 }
592         }
593
594         if (body_pos > 0 && body_pos >= end) {
595                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
596                 if (end > 0 && pit->isLineSeparator(end - 1))
597                         w -= singleWidth(pit, end - 1);
598                 w = max(w, labelEnd(pit, row));
599         }
600
601         int const fill = workwidth - w - rightMargin(*pit, *bv()->buffer());
602         row.fill(fill);
603         row.width(workwidth - fill);
604 }
605
606
607 // returns the minimum space a manual label needs on the screen in pixel
608 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
609 {
610         pos_type last = pit->beginningOfBody();
611
612         BOOST_ASSERT(last > 0);
613
614         // -1 because a label ends with a space that is in the label
615         --last;
616
617         // a separator at this end does not count
618         if (pit->isLineSeparator(last))
619                 --last;
620
621         int w = 0;
622         for (pos_type i = row.pos(); i <= last; ++i)
623                 w += singleWidth(pit, i);
624
625         string const & label = pit->params().labelWidthString();
626         if (label.empty())
627                 return 0;
628
629         return max(0, font_metrics::width(label, getLabelFont(pit)) - w);
630 }
631
632
633 LColor_color LyXText::backgroundColor() const
634 {
635         if (inset_owner)
636                 return inset_owner->backgroundColor();
637         return LColor::background;
638 }
639
640
641 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
642 {
643         // get the maximum ascent and the maximum descent
644         double layoutasc = 0;
645         double layoutdesc = 0;
646         double const dh = defaultRowHeight();
647
648         // ok, let us initialize the maxasc and maxdesc value.
649         // Only the fontsize count. The other properties
650         // are taken from the layoutfont. Nicer on the screen :)
651         LyXLayout_ptr const & layout = pit->layout();
652
653         // as max get the first character of this row then it can increase but not
654         // decrease the height. Just some point to start with so we don't have to
655         // do the assignment below too often.
656         LyXFont font = getFont(pit, row.pos());
657         LyXFont::FONT_SIZE const tmpsize = font.size();
658         font = getLayoutFont(pit);
659         LyXFont::FONT_SIZE const size = font.size();
660         font.setSize(tmpsize);
661
662         LyXFont labelfont = getLabelFont(pit);
663
664         // these are minimum values
665         double const spacing_val = layout->spacing.getValue() * spacing(*pit);
666         //lyxerr << "spacing_val = " << spacing_val << endl;
667         int maxasc  = int(font_metrics::maxAscent(font)  * spacing_val);
668         int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
669
670         // insets may be taller
671         InsetList::iterator ii = pit->insetlist.begin();
672         InsetList::iterator iend = pit->insetlist.end();
673         for ( ; ii != iend; ++ii) {
674                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
675                         maxasc  = max(maxasc,  ii->inset->ascent());
676                         maxdesc = max(maxdesc, ii->inset->descent());
677                 }
678         }
679
680         // Check if any custom fonts are larger (Asger)
681         // This is not completely correct, but we can live with the small,
682         // cosmetic error for now.
683         int labeladdon = 0;
684         pos_type const pos_end = row.endpos();
685
686         LyXFont::FONT_SIZE maxsize =
687                 pit->highestFontInRange(row.pos(), pos_end, size);
688         if (maxsize > font.size()) {
689                 font.setSize(maxsize);
690                 maxasc  = max(maxasc,  font_metrics::maxAscent(font));
691                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
692         }
693
694         // This is nicer with box insets:
695         ++maxasc;
696         ++maxdesc;
697
698         row.ascent_of_text(maxasc);
699
700         // is it a top line?
701         if (row.pos() == 0) {
702                 BufferParams const & bufparams = bv()->buffer()->params();
703                 // some parksips VERY EASY IMPLEMENTATION
704                 if (bv()->buffer()->params().paragraph_separation
705                     == BufferParams::PARSEP_SKIP 
706                         && pit != ownerParagraphs().begin()
707                         && ((layout->isParagraph() && pit->getDepth() == 0)
708                             || (boost::prior(pit)->layout()->isParagraph()
709                                 && boost::prior(pit)->getDepth() == 0)))
710                 {
711                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
712                 }
713
714                 // the top margin
715                 if (pit == ownerParagraphs().begin() && !isInInset())
716                         maxasc += PAPER_MARGIN;
717
718                 // add user added vertical space
719                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
720
721                 if (pit->params().startOfAppendix())
722                         maxasc += int(3 * dh);
723
724                 // This is special code for the chapter, since the label of this
725                 // layout is printed in an extra row
726                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
727                         labeladdon = int(font_metrics::maxHeight(labelfont)
728                                      * layout->spacing.getValue() * spacing(*pit));
729                 }
730
731                 // special code for the top label
732                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
733                      || layout->labeltype == LABEL_BIBLIO
734                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
735                     && isFirstInSequence(pit, ownerParagraphs())
736                     && !pit->getLabelstring().empty())
737                 {
738                         labeladdon = int(
739                                   font_metrics::maxHeight(labelfont)
740                                         * layout->spacing.getValue()
741                                         * spacing(*pit)
742                                 + (layout->topsep + layout->labelbottomsep) * dh);
743                 }
744
745                 // And now the layout spaces, for example before and after
746                 // a section, or between the items of a itemize or enumerate
747                 // environment.
748
749                 ParagraphList::iterator prev =
750                         depthHook(pit, ownerParagraphs(), pit->getDepth());
751                 if (prev != pit
752                     && prev->layout() == layout
753                     && prev->getDepth() == pit->getDepth()
754                     && prev->getLabelWidthString() == pit->getLabelWidthString())
755                 {
756                         layoutasc = layout->itemsep * dh;
757                 } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
758                         if (layout->topsep > 0)
759                                 layoutasc = layout->topsep * dh;
760                 }
761
762                 prev = outerHook(pit, ownerParagraphs());
763                 if (prev != ownerParagraphs().end()) {
764                         maxasc += int(prev->layout()->parsep * dh);
765                 } else if (pit != ownerParagraphs().begin()) {
766                         ParagraphList::iterator prior_pit = boost::prior(pit);
767                         if (prior_pit->getDepth() != 0 ||
768                                         prior_pit->layout() == layout) {
769                                 maxasc += int(layout->parsep * dh);
770                         }
771                 }
772         }
773
774         // is it a bottom line?
775         if (row.endpos() >= pit->size()) {
776                 // the bottom margin
777                 ParagraphList::iterator nextpit = boost::next(pit);
778                 if (nextpit == ownerParagraphs().end() && !isInInset())
779                         maxdesc += PAPER_MARGIN;
780
781                 // add the vertical spaces, that the user added
782                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
783
784                 // and now the layout spaces, for example before and after
785                 // a section, or between the items of a itemize or enumerate
786                 // environment
787                 if (nextpit != ownerParagraphs().end()) {
788                         ParagraphList::iterator cpit = pit;
789                         double usual = 0;
790                         double unusual = 0;
791
792                         if (cpit->getDepth() > nextpit->getDepth()) {
793                                 usual = cpit->layout()->bottomsep * dh;
794                                 cpit = depthHook(cpit, ownerParagraphs(), nextpit->getDepth());
795                                 if (cpit->layout() != nextpit->layout()
796                                         || nextpit->getLabelWidthString() != cpit->getLabelWidthString())
797                                 {
798                                         unusual = cpit->layout()->bottomsep * dh;
799                                 }
800                                 layoutdesc = max(unusual, usual);
801                         } else if (cpit->getDepth() == nextpit->getDepth()) {
802                                 if (cpit->layout() != nextpit->layout()
803                                         || nextpit->getLabelWidthString() != cpit->getLabelWidthString())
804                                         layoutdesc = int(cpit->layout()->bottomsep * dh);
805                         }
806                 }
807         }
808
809         // incalculate the layout spaces
810         maxasc  += int(layoutasc  * 2 / (2 + pit->getDepth()));
811         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
812
813         row.height(maxasc + maxdesc + labeladdon);
814         row.baseline(maxasc + labeladdon);
815         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
816 }
817
818
819 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
820 {
821         // allow only if at start or end, or all previous is new text
822         ParagraphList::iterator cpit = cursorPar();
823         if (cursor.pos() && cursor.pos() != cpit->size()
824             && cpit->isChangeEdited(0, cursor.pos()))
825                 return;
826
827         LyXTextClass const & tclass =
828                 bv()->buffer()->params().getLyXTextClass();
829         LyXLayout_ptr const & layout = cpit->layout();
830
831         // this is only allowed, if the current paragraph is not empty or caption
832         // and if it has not the keepempty flag active
833         if (cpit->empty() && !cpit->allowEmpty()
834            && layout->labeltype != LABEL_SENSITIVE)
835                 return;
836
837         recUndo(cursor.par());
838
839         // Always break behind a space
840         //
841         // It is better to erase the space (Dekel)
842         if (cursor.pos() < cpit->size() && cpit->isLineSeparator(cursor.pos()))
843            cpit->erase(cursor.pos());
844
845         // break the paragraph
846         if (keep_layout)
847                 keep_layout = 2;
848         else
849                 keep_layout = layout->isEnvironment();
850
851         // we need to set this before we insert the paragraph. IMO the
852         // breakParagraph call should return a bool if it inserts the
853         // paragraph before or behind and we should react on that one
854         // but we can fix this in 1.3.0 (Jug 20020509)
855         bool const isempty = cpit->allowEmpty() && cpit->empty();
856         ::breakParagraph(bv()->buffer()->params(), paragraphs, cpit,
857                          cursor.pos(), keep_layout);
858
859 #warning Trouble Point! (Lgb)
860         // When ::breakParagraph is called from within an inset we must
861         // ensure that the correct ParagraphList is used. Today that is not
862         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
863         cpit = cursorPar();
864         ParagraphList::iterator next_par = boost::next(cpit);
865
866         // well this is the caption hack since one caption is really enough
867         if (layout->labeltype == LABEL_SENSITIVE) {
868                 if (!cursor.pos())
869                         // set to standard-layout
870                         cpit->applyLayout(tclass.defaultLayout());
871                 else
872                         // set to standard-layout
873                         next_par->applyLayout(tclass.defaultLayout());
874         }
875
876         // if the cursor is at the beginning of a row without prior newline,
877         // move one row up!
878         // This touches only the screen-update. Otherwise we would may have
879         // an empty row on the screen
880         RowList::iterator crit = cpit->getRow(cursor.pos());
881         if (cursor.pos() && crit->pos() == cursor.pos()
882             && !cpit->isNewline(cursor.pos() - 1))
883         {
884                 cursorLeft(bv());
885         }
886
887         while (!next_par->empty() && next_par->isNewline(0))
888                 next_par->erase(0);
889
890         updateCounters();
891         redoParagraph(cpit);
892         redoParagraph(next_par);
893
894         // This check is necessary. Otherwise the new empty paragraph will
895         // be deleted automatically. And it is more friendly for the user!
896         if (cursor.pos() || isempty)
897                 setCursor(next_par, 0);
898         else
899                 setCursor(cpit, 0);
900 }
901
902
903 // convenience function
904 void LyXText::redoParagraph()
905 {
906         clearSelection();
907         redoParagraph(cursorPar());
908         setCursorIntern(cursor.par(), cursor.pos());
909 }
910
911
912 // insert a character, moves all the following breaks in the
913 // same Paragraph one to the right and make a rebreak
914 void LyXText::insertChar(char c)
915 {
916         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
917
918         // When the free-spacing option is set for the current layout,
919         // disable the double-space checking
920
921         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
922                 cursorPar()->isFreeSpacing();
923
924         if (lyxrc.auto_number) {
925                 static string const number_operators = "+-/*";
926                 static string const number_unary_operators = "+-";
927                 static string const number_seperators = ".,:";
928
929                 if (current_font.number() == LyXFont::ON) {
930                         if (!IsDigit(c) && !contains(number_operators, c) &&
931                             !(contains(number_seperators, c) &&
932                               cursor.pos() >= 1 &&
933                               cursor.pos() < cursorPar()->size() &&
934                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
935                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
936                            )
937                                 number(bv()); // Set current_font.number to OFF
938                 } else if (IsDigit(c) &&
939                            real_current_font.isVisibleRightToLeft()) {
940                         number(bv()); // Set current_font.number to ON
941
942                         if (cursor.pos() > 0) {
943                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
944                                 if (contains(number_unary_operators, c) &&
945                                     (cursor.pos() == 1 ||
946                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
947                                      cursorPar()->isNewline(cursor.pos() - 2))
948                                   ) {
949                                         setCharFont(
950                                                     cursorPar(),
951                                                     cursor.pos() - 1,
952                                                     current_font);
953                                 } else if (contains(number_seperators, c) &&
954                                            cursor.pos() >= 2 &&
955                                            getFont(
956                                                    cursorPar(),
957                                                    cursor.pos() - 2).number() == LyXFont::ON) {
958                                         setCharFont(
959                                                     cursorPar(),
960                                                     cursor.pos() - 1,
961                                                     current_font);
962                                 }
963                         }
964                 }
965         }
966
967         // First check, if there will be two blanks together or a blank at
968         // the beginning of a paragraph.
969         // I decided to handle blanks like normal characters, the main
970         // difference are the special checks when calculating the row.fill
971         // (blank does not count at the end of a row) and the check here
972
973         // The bug is triggered when we type in a description environment:
974         // The current_font is not changed when we go from label to main text
975         // and it should (along with realtmpfont) when we type the space.
976         // CHECK There is a bug here! (Asger)
977
978         // store the current font.  This is because of the use of cursor
979         // movements. The moving cursor would refresh the current font
980         LyXFont realtmpfont = real_current_font;
981         LyXFont rawtmpfont = current_font;
982
983         if (!freeSpacing && IsLineSeparatorChar(c)) {
984                 if ((cursor.pos() > 0
985                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
986                     || (cursor.pos() > 0
987                         && cursorPar()->isNewline(cursor.pos() - 1))
988                     || (cursor.pos() == 0)) {
989                         static bool sent_space_message = false;
990                         if (!sent_space_message) {
991                                 if (cursor.pos() == 0)
992                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
993                                 else
994                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
995                                 sent_space_message = true;
996                         }
997                         charInserted();
998                         return;
999                 }
1000         }
1001
1002         // Here case LyXText::InsertInset already inserted the character
1003         if (c != Paragraph::META_INSET)
1004                 cursorPar()->insertChar(cursor.pos(), c);
1005
1006         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1007
1008         current_font = rawtmpfont;
1009         real_current_font = realtmpfont;
1010         redoParagraph(cursorPar());
1011         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1012
1013         charInserted();
1014 }
1015
1016
1017 void LyXText::charInserted()
1018 {
1019         // Here we call finishUndo for every 20 characters inserted.
1020         // This is from my experience how emacs does it. (Lgb)
1021         static unsigned int counter;
1022         if (counter < 20) {
1023                 ++counter;
1024         } else {
1025                 finishUndo();
1026                 counter = 0;
1027         }
1028 }
1029
1030
1031 void LyXText::prepareToPrint(ParagraphList::iterator pit, Row & row) const
1032 {
1033         double w = row.fill();
1034         double fill_hfill = 0;
1035         double fill_label_hfill = 0;
1036         double fill_separator = 0;
1037         double x = 0;
1038
1039         bool const is_rtl =
1040                 pit->isRightToLeftPar(bv()->buffer()->params());
1041         if (is_rtl)
1042                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer()) : 0;
1043         else
1044                 x = workWidth() > 0 ? leftMargin(pit, row) : 0;
1045
1046         // is there a manual margin with a manual label
1047         LyXLayout_ptr const & layout = pit->layout();
1048
1049         if (layout->margintype == MARGIN_MANUAL
1050             && layout->labeltype == LABEL_MANUAL) {
1051                 /// We might have real hfills in the label part
1052                 int nlh = numberOfLabelHfills(*pit, row);
1053
1054                 // A manual label par (e.g. List) has an auto-hfill
1055                 // between the label text and the body of the
1056                 // paragraph too.
1057                 // But we don't want to do this auto hfill if the par
1058                 // is empty.
1059                 if (!pit->empty())
1060                         ++nlh;
1061
1062                 if (nlh && !pit->getLabelWidthString().empty())
1063                         fill_label_hfill = labelFill(pit, row) / double(nlh);
1064         }
1065
1066         // are there any hfills in the row?
1067         int const nh = numberOfHfills(*pit, row);
1068
1069         if (nh) {
1070                 if (w > 0)
1071                         fill_hfill = w / nh;
1072         // we don't have to look at the alignment if it is ALIGN_LEFT and
1073         // if the row is already larger then the permitted width as then
1074         // we force the LEFT_ALIGN'edness!
1075         } else if (int(row.width()) < workWidth()) {
1076                 // is it block, flushleft or flushright?
1077                 // set x how you need it
1078                 int align;
1079                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1080                         align = layout->align;
1081                 } else {
1082                         align = pit->params().align();
1083                 }
1084                 // ERT insets should always be LEFT ALIGNED on screen
1085                 InsetOld * inset = pit->inInset();
1086                 if (inset && inset->owner() &&
1087                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1088                 {
1089                         align = LYX_ALIGN_LEFT;
1090                 }
1091
1092                 // Display-style insets should always be on a centred row
1093                 // The test on pit->size() is to catch zero-size pars, which
1094                 // would trigger the assert in Paragraph::getInset().
1095                 //inset = pit->size() ? pit->getInset(row.pos()) : 0;
1096                 if (!pit->empty()
1097                     && pit->isInset(row.pos())
1098                     && pit->getInset(row.pos())->display())
1099                 {
1100                         align = LYX_ALIGN_CENTER;
1101                 }
1102                 
1103                 switch (align) {
1104     case LYX_ALIGN_BLOCK: {
1105                                 int const ns = numberOfSeparators(*pit, row);
1106                                 bool disp_inset = false;
1107                                 if (row.endpos() < pit->size()) {
1108                                         InsetOld * in = pit->getInset(row.endpos());
1109                                         if (in)
1110                                                 disp_inset = in->display();
1111                                 }
1112                                 // If we have separators, this is not the last row of a
1113                                 // par, does not end in newline, and is not row above a
1114                                 // display inset... then stretch it
1115                                 if (ns
1116                                         && row.endpos() < pit->size()
1117                                         && !pit->isNewline(row.endpos() - 1)
1118                                         && !disp_inset
1119                                         ) {
1120                                                 fill_separator = w / ns;
1121                                 } else if (is_rtl) {
1122                                         x += w;
1123                                 }
1124                                 break;
1125                         }
1126     case LYX_ALIGN_RIGHT:
1127                         x += w;
1128                         break;
1129     case LYX_ALIGN_CENTER:
1130                         x += w / 2;
1131                         break;
1132                 }
1133         }
1134
1135         bidi.computeTables(*pit, *bv()->buffer(), row);
1136         if (is_rtl) {
1137                 pos_type body_pos = pit->beginningOfBody();
1138                 pos_type end = row.endpos();
1139
1140                 if (body_pos > 0
1141                     && (body_pos > end || !pit->isLineSeparator(body_pos - 1)))
1142                 {
1143                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1144                         if (body_pos <= end)
1145                                 x += fill_label_hfill;
1146                 }
1147         }
1148
1149         row.fill_hfill(fill_hfill);
1150         row.fill_label_hfill(fill_label_hfill);
1151         row.fill_separator(fill_separator);
1152         row.x(x);
1153 }
1154
1155
1156 // important for the screen
1157
1158
1159 // the cursor set functions have a special mechanism. When they
1160 // realize, that you left an empty paragraph, they will delete it.
1161 // They also delete the corresponding row
1162
1163 void LyXText::cursorRightOneWord()
1164 {
1165         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1166         setCursor(cursorPar(), cursor.pos());
1167 }
1168
1169
1170 // Skip initial whitespace at end of word and move cursor to *start*
1171 // of prior word, not to end of next prior word.
1172 void LyXText::cursorLeftOneWord()
1173 {
1174         LyXCursor tmpcursor = cursor;
1175         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1176         setCursor(getPar(tmpcursor), tmpcursor.pos());
1177 }
1178
1179
1180 void LyXText::selectWord(word_location loc)
1181 {
1182         LyXCursor from = cursor;
1183         LyXCursor to = cursor;
1184         ::getWord(*this, from, to, loc, ownerParagraphs());
1185         if (cursor != from)
1186                 setCursor(from.par(), from.pos());
1187         if (to == from)
1188                 return;
1189         selection.cursor = cursor;
1190         setCursor(to.par(), to.pos());
1191         setSelection();
1192 }
1193
1194
1195 // Select the word currently under the cursor when no
1196 // selection is currently set
1197 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1198 {
1199         if (!selection.set()) {
1200                 selectWord(loc);
1201                 return selection.set();
1202         }
1203         return false;
1204 }
1205
1206
1207 void LyXText::acceptChange()
1208 {
1209         if (!selection.set() && cursorPar()->size())
1210                 return;
1211
1212         if (selection.start.par() == selection.end.par()) {
1213                 LyXCursor & startc = selection.start;
1214                 LyXCursor & endc = selection.end;
1215                 recordUndo(Undo::INSERT, this, startc.par());
1216                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1217                 finishUndo();
1218                 clearSelection();
1219                 redoParagraph(getPar(startc));
1220                 setCursorIntern(startc.par(), 0);
1221         }
1222 #warning handle multi par selection
1223 }
1224
1225
1226 void LyXText::rejectChange()
1227 {
1228         if (!selection.set() && cursorPar()->size())
1229                 return;
1230
1231         if (selection.start.par() == selection.end.par()) {
1232                 LyXCursor & startc = selection.start;
1233                 LyXCursor & endc = selection.end;
1234                 recordUndo(Undo::INSERT, this, startc.par());
1235                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1236                 finishUndo();
1237                 clearSelection();
1238                 redoParagraph(getPar(startc));
1239                 setCursorIntern(startc.par(), 0);
1240         }
1241 #warning handle multi par selection
1242 }
1243
1244
1245 // This function is only used by the spellchecker for NextWord().
1246 // It doesn't handle LYX_ACCENTs and probably never will.
1247 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1248 {
1249         if (the_locking_inset) {
1250                 WordLangTuple word =
1251                         the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1252                 if (!word.word().empty()) {
1253                         value += float(cursor.y());
1254                         value /= float(height);
1255                         return word;
1256                 }
1257                 // we have to go on checking so move cursor to the next char
1258                 if (cursor.pos() == cursorPar()->size()) {
1259                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1260                                 return word;
1261                         cursor.par(cursor.par() + 1);
1262                         cursor.pos(0);
1263                 } else {
1264                         cursor.pos(cursor.pos() + 1);
1265                 }
1266         }
1267         int const tmppar = cursor.par();
1268
1269         // If this is not the very first word, skip rest of
1270         // current word because we are probably in the middle
1271         // of a word if there is text here.
1272         if (cursor.pos() || cursor.par() != 0) {
1273                 while (cursor.pos() < cursorPar()->size()
1274                        && cursorPar()->isLetter(cursor.pos()))
1275                         cursor.pos(cursor.pos() + 1);
1276         }
1277
1278         // Now, skip until we have real text (will jump paragraphs)
1279         while (true) {
1280                 ParagraphList::iterator cpit = cursorPar();
1281                 pos_type const cpos = cursor.pos();
1282
1283                 if (cpos == cpit->size()) {
1284                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1285                                 cursor.par(cursor.par() + 1);
1286                                 cursor.pos(0);
1287                                 continue;
1288                         }
1289                         break;
1290                 }
1291
1292                 bool const is_good_inset = cpit->isInset(cpos)
1293                         && cpit->getInset(cpos)->allowSpellcheck();
1294
1295                 if (!isDeletedText(*cpit, cpos)
1296                     && (is_good_inset || cpit->isLetter(cpos)))
1297                         break;
1298
1299                 cursor.pos(cpos + 1);
1300         }
1301
1302         // now check if we hit an inset so it has to be a inset containing text!
1303         if (cursor.pos() < cursorPar()->size() &&
1304             cursorPar()->isInset(cursor.pos())) {
1305                 // lock the inset!
1306                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1307                 cursorPar()->getInset(cursor.pos())->dispatch(cmd);
1308                 // now call us again to do the above trick
1309                 // but obviously we have to start from down below ;)
1310                 return bv()->text->selectNextWordToSpellcheck(value);
1311         }
1312
1313         // Update the value if we changed paragraphs
1314         if (cursor.par() != tmppar) {
1315                 setCursor(cursor.par(), cursor.pos());
1316                 value = float(cursor.y())/float(height);
1317         }
1318
1319         // Start the selection from here
1320         selection.cursor = cursor;
1321
1322         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1323         // and find the end of the word (insets like optional hyphens
1324         // and ligature break are part of a word)
1325         while (cursor.pos() < cursorPar()->size()
1326                && cursorPar()->isLetter(cursor.pos())
1327                && !isDeletedText(*cursorPar(), cursor.pos()))
1328                 cursor.pos(cursor.pos() + 1);
1329
1330         // Finally, we copy the word to a string and return it
1331         string str;
1332         if (selection.cursor.pos() < cursor.pos()) {
1333                 for (pos_type i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1334                         if (!cursorPar()->isInset(i))
1335                                 str += cursorPar()->getChar(i);
1336                 }
1337         }
1338         return WordLangTuple(str, lang_code);
1339 }
1340
1341
1342 // This one is also only for the spellchecker
1343 void LyXText::selectSelectedWord()
1344 {
1345         if (the_locking_inset) {
1346                 the_locking_inset->selectSelectedWord(bv());
1347                 return;
1348         }
1349         // move cursor to the beginning
1350         setCursor(selection.cursor.par(), selection.cursor.pos());
1351
1352         // set the sel cursor
1353         selection.cursor = cursor;
1354
1355         // now find the end of the word
1356         while (cursor.pos() < cursorPar()->size()
1357                && cursorPar()->isLetter(cursor.pos()))
1358                 cursor.pos(cursor.pos() + 1);
1359
1360         setCursor(cursorPar(), cursor.pos());
1361
1362         // finally set the selection
1363         setSelection();
1364 }
1365
1366
1367 // Delete from cursor up to the end of the current or next word.
1368 void LyXText::deleteWordForward()
1369 {
1370         if (cursorPar()->empty())
1371                 cursorRight(bv());
1372         else {
1373                 LyXCursor tmpcursor = cursor;
1374                 selection.set(true); // to avoid deletion
1375                 cursorRightOneWord();
1376                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1377                 selection.cursor = cursor;
1378                 cursor = tmpcursor;
1379                 setSelection();
1380                 cutSelection(true, false);
1381         }
1382 }
1383
1384
1385 // Delete from cursor to start of current or prior word.
1386 void LyXText::deleteWordBackward()
1387 {
1388         if (cursorPar()->empty())
1389                 cursorLeft(bv());
1390         else {
1391                 LyXCursor tmpcursor = cursor;
1392                 selection.set(true); // to avoid deletion
1393                 cursorLeftOneWord();
1394                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1395                 selection.cursor = cursor;
1396                 cursor = tmpcursor;
1397                 setSelection();
1398                 cutSelection(true, false);
1399         }
1400 }
1401
1402
1403 // Kill to end of line.
1404 void LyXText::deleteLineForward()
1405 {
1406         if (cursorPar()->empty()) {
1407                 // Paragraph is empty, so we just go to the right
1408                 cursorRight(bv());
1409         } else {
1410                 LyXCursor tmpcursor = cursor;
1411                 // We can't store the row over a regular setCursor
1412                 // so we set it to 0 and reset it afterwards.
1413                 selection.set(true); // to avoid deletion
1414                 cursorEnd();
1415                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1416                 selection.cursor = cursor;
1417                 cursor = tmpcursor;
1418                 setSelection();
1419                 // What is this test for ??? (JMarc)
1420                 if (!selection.set())
1421                         deleteWordForward();
1422                 else
1423                         cutSelection(true, false);
1424         }
1425 }
1426
1427
1428 void LyXText::changeCase(LyXText::TextCase action)
1429 {
1430         LyXCursor from;
1431         LyXCursor to;
1432
1433         if (selection.set()) {
1434                 from = selection.start;
1435                 to = selection.end;
1436         } else {
1437                 from = cursor;
1438                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1439                 setCursor(to.par(), to.pos() + 1);
1440         }
1441
1442         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1443
1444         pos_type pos = from.pos();
1445         int par = from.par();
1446
1447         while (par != int(ownerParagraphs().size()) &&
1448                (pos != to.pos() || par != to.par())) {
1449                 ParagraphList::iterator pit = getPar(par);
1450                 if (pos == pit->size()) {
1451                         ++par;
1452                         pos = 0;
1453                         continue;
1454                 }
1455                 unsigned char c = pit->getChar(pos);
1456                 if (c != Paragraph::META_INSET) {
1457                         switch (action) {
1458                         case text_lowercase:
1459                                 c = lowercase(c);
1460                                 break;
1461                         case text_capitalization:
1462                                 c = uppercase(c);
1463                                 action = text_lowercase;
1464                                 break;
1465                         case text_uppercase:
1466                                 c = uppercase(c);
1467                                 break;
1468                         }
1469                 }
1470 #warning changes
1471                 pit->setChar(pos, c);
1472                 ++pos;
1473         }
1474 }
1475
1476
1477 void LyXText::Delete()
1478 {
1479         // this is a very easy implementation
1480
1481         LyXCursor old_cursor = cursor;
1482         int const old_cur_par_id = cursorPar()->id();
1483         int const old_cur_par_prev_id =
1484                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1485
1486         // just move to the right
1487         cursorRight(bv());
1488
1489         // CHECK Look at the comment here.
1490         // This check is not very good...
1491         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1492         // and that can very well delete the par or par->previous in
1493         // old_cursor. Will a solution where we compare paragraph id's
1494         //work better?
1495         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1496         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1497                 // delete-empty-paragraph-mechanism has done it
1498                 return;
1499         }
1500
1501         // if you had success make a backspace
1502         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1503                 recordUndo(Undo::DELETE, this, old_cursor.par());
1504                 backspace();
1505         }
1506 }
1507
1508
1509 void LyXText::backspace()
1510 {
1511         // Get the font that is used to calculate the baselineskip
1512         ParagraphList::iterator pit = cursorPar();
1513         pos_type lastpos = pit->size();
1514
1515         if (cursor.pos() == 0) {
1516                 // The cursor is at the beginning of a paragraph,
1517                 // so the the backspace will collapse two paragraphs into one.
1518
1519                 // but it's not allowed unless it's new
1520                 if (pit->isChangeEdited(0, pit->size()))
1521                         return;
1522
1523                 // we may paste some paragraphs
1524
1525                 // is it an empty paragraph?
1526
1527                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1528                         // This is an empty paragraph and we delete it just
1529                         // by moving the cursor one step
1530                         // left and let the DeleteEmptyParagraphMechanism
1531                         // handle the actual deletion of the paragraph.
1532
1533                         if (cursor.par()) {
1534                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1535                                 if (cursorPar()->layout() == tmppit->layout()
1536                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1537                                         // Inherit bottom DTD from the paragraph below.
1538                                         // (the one we are deleting)
1539                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1540                                 }
1541
1542                                 cursorLeft(bv());
1543
1544                                 // the layout things can change the height of a row !
1545                                 redoParagraph();
1546                                 return;
1547                         }
1548                 }
1549
1550                 if (cursor.par() != 0)
1551                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1552
1553                 ParagraphList::iterator tmppit = cursorPar();
1554                 // We used to do cursorLeftIntern() here, but it is
1555                 // not a good idea since it triggers the auto-delete
1556                 // mechanism. So we do a cursorLeftIntern()-lite,
1557                 // without the dreaded mechanism. (JMarc)
1558                 if (cursor.par() != 0) {
1559                         // steps into the above paragraph.
1560                         setCursorIntern(cursor.par() - 1,
1561                                         getPar(cursor.par() - 1)->size(),
1562                                         false);
1563                 }
1564
1565                 // Pasting is not allowed, if the paragraphs have different
1566                 // layout. I think it is a real bug of all other
1567                 // word processors to allow it. It confuses the user.
1568                 // Correction: Pasting is always allowed with standard-layout
1569                 Buffer & buf = *bv()->buffer();
1570                 BufferParams const & bufparams = buf.params();
1571                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1572                 ParagraphList::iterator const cpit = cursorPar();
1573
1574                 if (cpit != tmppit
1575                     && (cpit->layout() == tmppit->layout()
1576                         || tmppit->layout() == tclass.defaultLayout())
1577                     && cpit->getAlign() == tmppit->getAlign()) {
1578                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1579
1580                         if (cursor.pos() && cpit->isSeparator(cursor.pos() - 1))
1581                                 cursor.pos(cursor.pos() - 1);
1582
1583                         // the counters may have changed
1584                         updateCounters();
1585                         setCursor(cursor.par(), cursor.pos(), false);
1586                 }
1587         } else {
1588                 // this is the code for a normal backspace, not pasting
1589                 // any paragraphs
1590                 recordUndo(Undo::DELETE, this, cursor.par());
1591                 // We used to do cursorLeftIntern() here, but it is
1592                 // not a good idea since it triggers the auto-delete
1593                 // mechanism. So we do a cursorLeftIntern()-lite,
1594                 // without the dreaded mechanism. (JMarc)
1595                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1596                                 false, cursor.boundary());
1597                 cursorPar()->erase(cursor.pos());
1598         }
1599
1600         lastpos = cursorPar()->size();
1601         if (cursor.pos() == lastpos)
1602                 setCurrentFont();
1603
1604         redoParagraph();
1605         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
1606 }
1607
1608
1609 ParagraphList::iterator LyXText::cursorPar() const
1610 {
1611         if (cursor.par() != cache_pos_) {
1612                 cache_pos_ = cursor.par();
1613                 cache_par_ = getPar(cache_pos_);
1614         }
1615         return cache_par_;
1616 }
1617
1618
1619 RowList::iterator LyXText::cursorRow() const
1620 {
1621         return cursorPar()->getRow(cursor.pos());
1622 }
1623
1624
1625 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1626 {
1627         return getPar(cur.par());
1628 }
1629
1630
1631 ParagraphList::iterator LyXText::getPar(int par) const
1632 {
1633         BOOST_ASSERT(par >= 0);
1634         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1635         ParagraphList::iterator pit = ownerParagraphs().begin();
1636         std::advance(pit, par);
1637         return pit;
1638 }
1639
1640
1641 RowList::iterator
1642 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1643 {
1644         //lyxerr << "getRowNearY: y " << y << endl;
1645 #if 0
1646         ParagraphList::iterator const pend = ownerParagraphs().end();
1647         pit = ownerParagraphs().begin();
1648         while (int(pit->y + pit->height) < y && pit != pend)
1649                 ++pit;
1650
1651         RowList::iterator rit = pit->rows.begin();
1652         RowList::iterator const rend = pit->rows.end();
1653         while (int(pit->y + rit->y_offset()) < y && rit != rend)
1654                 ++rit;
1655         return rit;
1656
1657 #else
1658         pit = boost::prior(ownerParagraphs().end());
1659
1660         RowList::iterator rit = lastRow();
1661         RowList::iterator rbegin = firstRow();
1662
1663         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1664                 previousRow(pit, rit);
1665
1666         return rit;
1667 #endif
1668 }
1669
1670
1671 int LyXText::getDepth() const
1672 {
1673         return cursorPar()->getDepth();
1674 }
1675
1676
1677 RowList::iterator LyXText::firstRow() const
1678 {
1679         return ownerParagraphs().front().rows.begin();
1680 }
1681
1682
1683 RowList::iterator LyXText::lastRow() const
1684 {
1685         return boost::prior(endRow());
1686 }
1687
1688
1689 RowList::iterator LyXText::endRow() const
1690 {
1691         return ownerParagraphs().back().rows.end();
1692 }
1693
1694
1695 void LyXText::nextRow(ParagraphList::iterator & pit,
1696         RowList::iterator & rit) const
1697 {
1698         ++rit;
1699         if (rit == pit->rows.end()) {
1700                 ++pit;
1701                 if (pit == ownerParagraphs().end())
1702                         --pit;
1703                 else
1704                         rit = pit->rows.begin();
1705         }
1706 }
1707
1708
1709 void LyXText::previousRow(ParagraphList::iterator & pit,
1710         RowList::iterator & rit) const
1711 {
1712         if (rit != pit->rows.begin())
1713                 --rit;
1714         else {
1715                 BOOST_ASSERT(pit != ownerParagraphs().begin());
1716                 --pit;
1717                 rit = boost::prior(pit->rows.end());
1718         }
1719 }
1720
1721
1722 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1723 {
1724         if (!selection.set())
1725                 return string();
1726
1727         // should be const ...
1728         ParagraphList::iterator startpit = getPar(selection.start);
1729         ParagraphList::iterator endpit = getPar(selection.end);
1730         size_t const startpos = selection.start.pos();
1731         size_t const endpos = selection.end.pos();
1732
1733         if (startpit == endpit)
1734                 return startpit->asString(buffer, startpos, endpos, label);
1735
1736         // First paragraph in selection
1737         string result =
1738                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1739
1740         // The paragraphs in between (if any)
1741         ParagraphList::iterator pit = startpit;
1742         for (++pit; pit != endpit; ++pit)
1743                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1744
1745         // Last paragraph in selection
1746         result += endpit->asString(buffer, 0, endpos, label);
1747
1748         return result;
1749 }
1750
1751
1752 int LyXText::parOffset(ParagraphList::iterator pit) const
1753 {
1754         return std::distance(ownerParagraphs().begin(), pit);
1755 }
1756
1757
1758 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1759 {
1760         // remove rows of paragraph, keep track of height changes
1761         height -= pit->height;
1762
1763         // clear old data
1764         pit->rows.clear();
1765         pit->height = 0;
1766         pit->width = 0;
1767
1768         // redo insets
1769         InsetList::iterator ii = pit->insetlist.begin();
1770         InsetList::iterator iend = pit->insetlist.end();
1771         for (; ii != iend; ++ii) {
1772                 Dimension dim;
1773                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
1774                 ii->inset->metrics(mi, dim);
1775         }
1776
1777         // rebreak the paragraph
1778         int const ww = workWidth();
1779         pos_type z = 0;
1780         do {
1781                 Row row(z);
1782                 rowBreakPoint(pit, row);
1783                 z = row.endpos();
1784                 fill(pit, row, ww);
1785                 prepareToPrint(pit, row);
1786                 setHeightOfRow(pit, row);
1787                 row.y_offset(pit->height);
1788                 pit->rows.push_back(row);
1789                 pit->width = std::max(pit->width, row.width());
1790                 pit->height += row.height();
1791         } while (z < pit->size());
1792
1793         height += pit->height;
1794         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1795 }
1796
1797
1798 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1799   ParagraphList::iterator end)
1800 {
1801         for ( ; pit != end; ++pit)
1802                 redoParagraphInternal(pit);
1803         updateRowPositions();
1804 }
1805
1806
1807 void LyXText::redoParagraph(ParagraphList::iterator pit)
1808 {
1809         redoParagraphInternal(pit);
1810         updateRowPositions();
1811 }
1812
1813
1814 void LyXText::fullRebreak()
1815 {
1816         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1817         redoCursor();
1818         selection.cursor = cursor;
1819 }
1820
1821
1822 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1823 {
1824         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1825         //      << " workWidth: " << workWidth() << "\nfont: " << mi.base.font << endl;
1826         //BOOST_ASSERT(mi.base.textwidth);
1827
1828         // rebuild row cache. This recomputes height as well.
1829         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1830
1831         width = maxParagraphWidth(ownerParagraphs());
1832
1833         // final dimension
1834         dim.asc = firstRow()->ascent_of_text();
1835         dim.des = height - dim.asc;
1836         dim.wid = std::max(mi.base.textwidth, int(width));
1837 }
1838
1839
1840 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
1841 {
1842         return row.endpos() >= pit->size()
1843                && boost::next(pit) == ownerParagraphs().end();
1844 }
1845
1846
1847 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
1848 {
1849         return row.pos() == 0 && pit == ownerParagraphs().begin();
1850 }