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