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