]> git.lyx.org Git - lyx.git/blob - src/text.C
Squash warning about variables being initialized in the wrong order.
[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 = ownerParagraphs().begin();
112         ParagraphList::iterator end = ownerParagraphs().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 != ownerParagraphs().begin()) {
196                                 ParagraphList::iterator newpit =
197                                         depthHook(pit, ownerParagraphs(), 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, ownerParagraphs());
206
207                 // Make a corresponding row. Need to call leftMargin()
208                 // to check whether it is a sufficent paragraph.
209                 if (newpar != ownerParagraphs().end()
210                     && newpar->layout()->isEnvironment()) {
211                         x = leftMargin(newpar);
212                 }
213
214                 if (newpar != ownerParagraphs().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, ownerParagraphs()))) {
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                 // ok, a terrible hack. The left margin depends on the widest
286                 // row in this paragraph.
287                 RowList::iterator rit = pit->rows.begin();
288                 RowList::iterator end = pit->rows.end();
289 #warning This is wrong.
290                 int minfill = textwidth_;
291                 for ( ; rit != end; ++rit)
292                         if (rit->fill() < minfill)
293                                 minfill = rit->fill();
294                 x += font_metrics::signedWidth(layout->leftmargin,
295                         tclass.defaultfont());
296                 x += minfill;
297                 break;
298         }
299         }
300
301         if (!pit->params().leftIndent().zero()) {
302                 int const tw = inset_owner ?
303                         inset_owner->latexTextWidth(bv()) : textWidth();
304                 x += pit->params().leftIndent().inPixels(tw);
305         }
306
307         LyXAlignment align;
308
309         if (pit->params().align() == LYX_ALIGN_LAYOUT)
310                 align = layout->align;
311         else
312                 align = pit->params().align();
313
314         // set the correct parindent
315         if (pos == 0) {
316                 if ((layout->labeltype == LABEL_NO_LABEL
317                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
318                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
319                      || (layout->labeltype == LABEL_STATIC
320                          && layout->latextype == LATEX_ENVIRONMENT
321                          && !isFirstInSequence(pit, ownerParagraphs())))
322                     && align == LYX_ALIGN_BLOCK
323                     && !pit->params().noindent()
324                         // in tabulars and ert paragraphs are never indented!
325                         && (!pit->inInset() || !pit->inInset()->owner() ||
326                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
327                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
328                     && (pit->layout() != tclass.defaultLayout() ||
329                         bv()->buffer()->params().paragraph_separation ==
330                         BufferParams::PARSEP_INDENT)) {
331                         x += font_metrics::signedWidth(parindent,
332                                                   tclass.defaultfont());
333                 }
334         }
335
336         return x;
337 }
338
339
340 int LyXText::rightMargin(Paragraph const & par) const
341 {
342         LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
343
344         return 
345                 RIGHT_MARGIN
346                 + font_metrics::signedWidth(tclass.rightmargin(),
347                                        tclass.defaultfont())
348                 + font_metrics::signedWidth(par.layout()->rightmargin,
349                                        tclass.defaultfont())
350                 * 4 / (par.getDepth() + 4);
351 }
352
353
354 int LyXText::labelEnd(ParagraphList::iterator pit) const
355 {
356         // labelEnd is only needed if the layout fills a flushleft label.
357         if (pit->layout()->margintype != MARGIN_MANUAL)
358                 return 0;
359         // return the beginning of the body
360         return leftMargin(pit);
361 }
362
363
364 namespace {
365
366 // this needs special handling - only newlines count as a break point
367 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
368 {
369         pos_type const end = par.size();
370
371         for (; i < end; ++i)
372                 if (par.isNewline(i))
373                         return i + 1;
374
375         return end;
376 }
377
378 };
379
380
381 void LyXText::rowBreakPoint(ParagraphList::iterator pit, Row & row) const
382 {
383         pos_type const end = pit->size();
384         pos_type const pos = row.pos();
385         if (pos == end) {
386                 row.endpos(end);
387                 return;
388         }
389
390         // maximum pixel width of a row
391         int width = textWidth() - rightMargin(*pit); // - leftMargin(pit, row);
392         if (width < 0) {
393                 row.endpos(end);
394                 return;
395         }
396
397         LyXLayout_ptr const & layout = pit->layout();
398
399         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
400                 row.endpos(addressBreakPoint(pos, *pit));
401                 return;
402         }
403
404         pos_type const body_pos = pit->beginOfBody();
405
406
407         // Now we iterate through until we reach the right margin
408         // or the end of the par, then choose the possible break
409         // nearest that.
410
411         int const left = leftMargin(pit, pos);
412         int x = left;
413
414         // pixel width since last breakpoint
415         int chunkwidth = 0;
416
417
418         // We re-use the font resolution for the entire font span when possible
419         LyXFont font = getFont(pit, pos);
420         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(pos);
421
422         pos_type point = end;
423         pos_type i = pos;
424         for ( ; i < end; ++i) {
425                 if (pit->isNewline(i)) {
426                         point = i + 1;
427                         break;
428                 }
429                 // Break before...
430                 if (i + 1 < end) {
431                         if (pit->isInset(i + 1) && pit->getInset(i + 1)->display()) {
432                                 point = i + 1;
433                                 break;
434                         }
435                         // ...and after.
436                         if (pit->isInset(i) && pit->getInset(i)->display()) {
437                                 point = i + 1;
438                                 break;
439                         }
440                 }
441
442                 char const c = pit->getChar(i);
443
444                 if (i > endPosOfFontSpan) {
445                         font = getFont(pit, i);
446                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
447                 }
448
449                 {
450                         int thiswidth = singleWidth(pit, i, c, font);
451
452                         // add the auto-hfill from label end to the body
453                         if (body_pos && i == body_pos) {
454                                 int add = font_metrics::width(layout->labelsep, getLabelFont(pit));
455                                 if (pit->isLineSeparator(i - 1))
456                                         add -= singleWidth(pit, i - 1);
457
458                                 add = std::max(add, labelEnd(pit) - x);
459                                 thiswidth += add;
460                         }
461
462                         x += thiswidth;
463                         //lyxerr << "i: " << i << " x: "
464                         //<< x << " width: " << width << endl;
465                         chunkwidth += thiswidth;
466                 }
467
468                 // break before a character that will fall off
469                 // the right of the row
470                 if (x >= width) {
471                         // if no break before, break here
472                         if (point == end || chunkwidth >= width - left) {
473                                 if (i > pos) {
474                                         point = i;
475                                         break;
476                                 }
477                         }
478                         // exit on last registered breakpoint:
479                         break;
480                 }
481
482                 if (!pit->isInset(i) || pit->getInset(i)->isChar()) {
483                         // some insets are line separators too
484                         if (pit->isLineSeparator(i)) {
485                                 // register breakpoint:
486                                 point = i + 1;
487                                 chunkwidth = 0;
488                         }
489                 }
490         }
491
492         if (i == end && x < width) {
493                 // maybe found one, but the par is short enough.
494                 point = end;
495         }
496
497         // manual labels cannot be broken in LaTeX. But we
498         // want to make our on-screen rendering of footnotes
499         // etc. still break
500         if (body_pos && point < body_pos)
501                 point = body_pos;
502
503         row.endpos(point);
504 }
505
506
507 // returns the minimum space a row needs on the screen in pixel
508 void LyXText::fill(ParagraphList::iterator pit, Row & row, int workwidth) const
509 {
510         // get the pure distance
511         pos_type const end = row.endpos();
512
513         string labelsep = pit->layout()->labelsep;
514         int w = leftMargin(pit, row.pos());
515
516         pos_type const body_pos = pit->beginOfBody();
517         pos_type i = row.pos();
518
519         if (i < end) {
520                 // We re-use the font resolution for the entire span when possible
521                 LyXFont font = getFont(pit, i);
522                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
523                 for ( ; i < end; ++i) {
524                         if (body_pos > 0 && i == body_pos) {
525                                 w += font_metrics::width(labelsep, getLabelFont(pit));
526                                 if (pit->isLineSeparator(i - 1))
527                                         w -= singleWidth(pit, i - 1);
528                                 w = max(w, labelEnd(pit));
529                         }
530                         char const c = pit->getChar(i);
531                         if (IsPrintable(c) && i > endPosOfFontSpan) {
532                                 // We need to get the next font
533                                 font = getFont(pit, i);
534                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
535                         }
536                         w += singleWidth(pit, i, c, font);
537                 }
538         }
539
540         if (body_pos > 0 && body_pos >= end) {
541                 w += font_metrics::width(labelsep, getLabelFont(pit));
542                 if (end > 0 && pit->isLineSeparator(end - 1))
543                         w -= singleWidth(pit, end - 1);
544                 w = max(w, labelEnd(pit));
545         }
546
547         int const fill = workwidth - w - rightMargin(*pit);
548         row.fill(fill);
549         row.width(workwidth - fill);
550 }
551
552
553 // returns the minimum space a manual label needs on the screen in pixel
554 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
555 {
556         pos_type last = pit->beginOfBody();
557
558         BOOST_ASSERT(last > 0);
559
560         // -1 because a label ends with a space that is in the label
561         --last;
562
563         // a separator at this end does not count
564         if (pit->isLineSeparator(last))
565                 --last;
566
567         int w = 0;
568         for (pos_type i = row.pos(); i <= last; ++i)
569                 w += singleWidth(pit, i);
570
571         string const & label = pit->params().labelWidthString();
572         if (label.empty())
573                 return 0;
574
575         return max(0, font_metrics::width(label, getLabelFont(pit)) - w);
576 }
577
578
579 LColor_color LyXText::backgroundColor() const
580 {
581         if (inset_owner)
582                 return inset_owner->backgroundColor();
583         return LColor::background;
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 != ownerParagraphs().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, ownerParagraphs())
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, ownerParagraphs(), 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 != ownerParagraphs().begin() || row.pos() != 0) {
697                         if (layout->topsep > 0)
698                                 layoutasc = layout->topsep * dh;
699                 }
700
701                 prev = outerHook(pit, ownerParagraphs());
702                 if (prev != ownerParagraphs().end()) {
703                         maxasc += int(prev->layout()->parsep * dh);
704                 } else if (pit != ownerParagraphs().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 != ownerParagraphs().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, ownerParagraphs(), 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 (selection.start.par() == selection.end.par()) {
1133                 LyXCursor & startc = selection.start;
1134                 LyXCursor & endc = selection.end;
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 (selection.start.par() == selection.end.par()) {
1152                 LyXCursor & startc = selection.start;
1153                 LyXCursor & endc = selection.end;
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                 // We can't store the row over a regular setCursor
1210                 // so we set it to 0 and reset it afterwards.
1211                 selection.set(true); // to avoid deletion
1212                 cursorEnd();
1213                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1214                 selection.cursor = cursor;
1215                 cursor = tmpcursor;
1216                 setSelection();
1217                 // What is this test for ??? (JMarc)
1218                 if (!selection.set())
1219                         deleteWordForward();
1220                 else
1221                         cutSelection(true, false);
1222         }
1223 }
1224
1225
1226 void LyXText::changeCase(LyXText::TextCase action)
1227 {
1228         LyXCursor from;
1229         LyXCursor to;
1230
1231         if (selection.set()) {
1232                 from = selection.start;
1233                 to = selection.end;
1234         } else {
1235                 from = cursor;
1236                 getWord(from, to, lyx::PARTIAL_WORD);
1237                 setCursor(to.par(), to.pos() + 1);
1238         }
1239
1240         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1241
1242         pos_type pos = from.pos();
1243         int par = from.par();
1244
1245         while (par != int(ownerParagraphs().size()) &&
1246                (pos != to.pos() || par != to.par())) {
1247                 ParagraphList::iterator pit = getPar(par);
1248                 if (pos == pit->size()) {
1249                         ++par;
1250                         pos = 0;
1251                         continue;
1252                 }
1253                 unsigned char c = pit->getChar(pos);
1254                 if (c != Paragraph::META_INSET) {
1255                         switch (action) {
1256                         case text_lowercase:
1257                                 c = lowercase(c);
1258                                 break;
1259                         case text_capitalization:
1260                                 c = uppercase(c);
1261                                 action = text_lowercase;
1262                                 break;
1263                         case text_uppercase:
1264                                 c = uppercase(c);
1265                                 break;
1266                         }
1267                 }
1268 #warning changes
1269                 pit->setChar(pos, c);
1270                 ++pos;
1271         }
1272 }
1273
1274
1275 void LyXText::Delete()
1276 {
1277         // this is a very easy implementation
1278         LyXCursor old_cursor = cursor;
1279
1280         // just move to the right
1281         cursorRight(true);
1282
1283         // if you had success make a backspace
1284         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1285                 recordUndo(Undo::DELETE, this, old_cursor.par());
1286                 backspace();
1287         }
1288 }
1289
1290
1291 void LyXText::backspace()
1292 {
1293         // Get the font that is used to calculate the baselineskip
1294         ParagraphList::iterator pit = cursorPar();
1295         pos_type lastpos = pit->size();
1296
1297         if (cursor.pos() == 0) {
1298                 // The cursor is at the beginning of a paragraph,
1299                 // so the the backspace will collapse two paragraphs into one.
1300
1301                 // but it's not allowed unless it's new
1302                 if (pit->isChangeEdited(0, pit->size()))
1303                         return;
1304
1305                 // we may paste some paragraphs
1306
1307                 // is it an empty paragraph?
1308
1309                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1310                         // This is an empty paragraph and we delete it just
1311                         // by moving the cursor one step
1312                         // left and let the DeleteEmptyParagraphMechanism
1313                         // handle the actual deletion of the paragraph.
1314
1315                         if (cursor.par()) {
1316                                 cursorLeft(bv());
1317                                 // the layout things can change the height of a row !
1318                                 redoParagraph();
1319                                 return;
1320                         }
1321                 }
1322
1323                 if (cursor.par() != 0)
1324                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1325
1326                 ParagraphList::iterator tmppit = cursorPar();
1327                 // We used to do cursorLeftIntern() here, but it is
1328                 // not a good idea since it triggers the auto-delete
1329                 // mechanism. So we do a cursorLeftIntern()-lite,
1330                 // without the dreaded mechanism. (JMarc)
1331                 if (cursor.par() != 0) {
1332                         // steps into the above paragraph.
1333                         setCursorIntern(cursor.par() - 1,
1334                                         getPar(cursor.par() - 1)->size(),
1335                                         false);
1336                 }
1337
1338                 // Pasting is not allowed, if the paragraphs have different
1339                 // layout. I think it is a real bug of all other
1340                 // word processors to allow it. It confuses the user.
1341                 // Correction: Pasting is always allowed with standard-layout
1342                 Buffer & buf = *bv()->buffer();
1343                 BufferParams const & bufparams = buf.params();
1344                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1345                 ParagraphList::iterator const cpit = cursorPar();
1346
1347                 if (cpit != tmppit
1348                     && (cpit->layout() == tmppit->layout()
1349                         || tmppit->layout() == tclass.defaultLayout())
1350                     && cpit->getAlign() == tmppit->getAlign()) {
1351                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1352
1353                         if (cursor.pos() && cpit->isSeparator(cursor.pos() - 1))
1354                                 cursor.pos(cursor.pos() - 1);
1355
1356                         // the counters may have changed
1357                         updateCounters();
1358                         setCursor(cursor.par(), cursor.pos(), false);
1359                 }
1360         } else {
1361                 // this is the code for a normal backspace, not pasting
1362                 // any paragraphs
1363                 recordUndo(Undo::DELETE, this, cursor.par());
1364                 // We used to do cursorLeftIntern() here, but it is
1365                 // not a good idea since it triggers the auto-delete
1366                 // mechanism. So we do a cursorLeftIntern()-lite,
1367                 // without the dreaded mechanism. (JMarc)
1368                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1369                                 false, cursor.boundary());
1370                 cursorPar()->erase(cursor.pos());
1371         }
1372
1373         lastpos = cursorPar()->size();
1374         if (cursor.pos() == lastpos)
1375                 setCurrentFont();
1376
1377         redoParagraph();
1378         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
1379 }
1380
1381
1382 ParagraphList::iterator LyXText::cursorPar() const
1383 {
1384         return getPar(cursor.par());
1385 }
1386
1387
1388 RowList::iterator LyXText::cursorRow() const
1389 {
1390         return cursorPar()->getRow(cursor.pos());
1391 }
1392
1393
1394 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1395 {
1396         return getPar(cur.par());
1397 }
1398
1399
1400 ParagraphList::iterator LyXText::getPar(int par) const
1401 {
1402         BOOST_ASSERT(par >= 0);
1403         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1404         ParagraphList::iterator pit = ownerParagraphs().begin();
1405         std::advance(pit, par);
1406         return pit;
1407 }
1408
1409
1410 RowList::iterator
1411 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1412 {
1413         //lyxerr << "getRowNearY: y " << y << endl;
1414 #if 1
1415         ParagraphList::iterator const
1416                 pend = boost::prior(ownerParagraphs().end());
1417         pit = ownerParagraphs().begin();
1418         while (int(pit->y + pit->height) < y && pit != pend)
1419                 ++pit;
1420
1421         RowList::iterator rit = pit->rows.end();
1422         RowList::iterator const rbegin = pit->rows.begin();
1423         do {
1424                 --rit;
1425         } while (rit != rbegin && int(pit->y + rit->y_offset()) > y);
1426
1427         return rit;
1428 #else
1429         pit = boost::prior(ownerParagraphs().end());
1430
1431         RowList::iterator rit = lastRow();
1432         RowList::iterator rbegin = firstRow();
1433
1434         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1435                 previousRow(pit, rit);
1436
1437         return rit;
1438 #endif
1439 }
1440
1441
1442 int LyXText::getDepth() const
1443 {
1444         return cursorPar()->getDepth();
1445 }
1446
1447
1448 RowList::iterator LyXText::firstRow() const
1449 {
1450         return ownerParagraphs().front().rows.begin();
1451 }
1452
1453
1454 ParagraphList::iterator LyXText::firstPar() const
1455 {
1456         return ownerParagraphs().begin();
1457 }
1458
1459
1460 RowList::iterator LyXText::lastRow() const
1461 {
1462         return boost::prior(endRow());
1463 }
1464
1465
1466 ParagraphList::iterator LyXText::lastPar() const
1467 {
1468         return boost::prior(endPar());
1469 }
1470
1471
1472 RowList::iterator LyXText::endRow() const
1473 {
1474         return ownerParagraphs().back().rows.end();
1475 }
1476
1477
1478 ParagraphList::iterator LyXText::endPar() const
1479 {
1480         return ownerParagraphs().end();
1481 }
1482
1483
1484 void LyXText::nextRow(ParagraphList::iterator & pit,
1485         RowList::iterator & rit) const
1486 {
1487         ++rit;
1488         if (rit == pit->rows.end()) {
1489                 ++pit;
1490                 if (pit == ownerParagraphs().end())
1491                         --pit;
1492                 else
1493                         rit = pit->rows.begin();
1494         }
1495 }
1496
1497
1498 void LyXText::previousRow(ParagraphList::iterator & pit,
1499         RowList::iterator & rit) const
1500 {
1501         if (rit != pit->rows.begin())
1502                 --rit;
1503         else {
1504                 BOOST_ASSERT(pit != ownerParagraphs().begin());
1505                 --pit;
1506                 rit = boost::prior(pit->rows.end());
1507         }
1508 }
1509
1510
1511 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1512 {
1513         if (!selection.set())
1514                 return string();
1515
1516         // should be const ...
1517         ParagraphList::iterator startpit = getPar(selection.start);
1518         ParagraphList::iterator endpit = getPar(selection.end);
1519         size_t const startpos = selection.start.pos();
1520         size_t const endpos = selection.end.pos();
1521
1522         if (startpit == endpit)
1523                 return startpit->asString(buffer, startpos, endpos, label);
1524
1525         // First paragraph in selection
1526         string result =
1527                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1528
1529         // The paragraphs in between (if any)
1530         ParagraphList::iterator pit = startpit;
1531         for (++pit; pit != endpit; ++pit)
1532                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1533
1534         // Last paragraph in selection
1535         result += endpit->asString(buffer, 0, endpos, label);
1536
1537         return result;
1538 }
1539
1540
1541 int LyXText::parOffset(ParagraphList::iterator pit) const
1542 {
1543         return std::distance(ownerParagraphs().begin(), pit);
1544 }
1545
1546
1547 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1548 {
1549         // remove rows of paragraph, keep track of height changes
1550         height -= pit->height;
1551
1552         // clear old data
1553         pit->rows.clear();
1554         pit->height = 0;
1555         pit->width = 0;
1556
1557         // redo insets
1558         InsetList::iterator ii = pit->insetlist.begin();
1559         InsetList::iterator iend = pit->insetlist.end();
1560         for (; ii != iend; ++ii) {
1561                 Dimension dim;
1562                 int const w = textWidth() - leftMargin(pit) - rightMargin(*pit);
1563                 MetricsInfo mi(bv(), getFont(pit, ii->pos), w);
1564                 ii->inset->metrics(mi, dim);
1565         }
1566
1567         // rebreak the paragraph
1568         pit->setBeginOfBody();
1569         pos_type z = 0;
1570         do {
1571                 Row row(z);
1572                 rowBreakPoint(pit, row);
1573                 z = row.endpos();
1574                 fill(pit, row, textwidth_);
1575                 prepareToPrint(pit, row);
1576                 setHeightOfRow(pit, row);
1577                 row.y_offset(pit->height);
1578                 pit->rows.push_back(row);
1579                 pit->width = std::max(pit->width, row.width());
1580                 pit->height += row.height();
1581         } while (z < pit->size());
1582
1583         height += pit->height;
1584         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1585 }
1586
1587
1588 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1589   ParagraphList::iterator end)
1590 {
1591         for ( ; pit != end; ++pit)
1592                 redoParagraphInternal(pit);
1593         updateParPositions();
1594 }
1595
1596
1597 void LyXText::redoParagraph(ParagraphList::iterator pit)
1598 {
1599         redoParagraphInternal(pit);
1600         updateParPositions();
1601 }
1602
1603
1604 void LyXText::fullRebreak()
1605 {
1606         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1607         redoCursor();
1608         selection.cursor = cursor;
1609 }
1610
1611
1612 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1613 {
1614         //BOOST_ASSERT(mi.base.textwidth);
1615         if (mi.base.textwidth)
1616                 textwidth_ = mi.base.textwidth;
1617         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1618         //      << " textWidth: " << textWidth() << "\nfont: " << mi.base.font << endl;
1619
1620         // Rebuild row cache. This recomputes height as well.
1621         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1622
1623         width = maxParagraphWidth(ownerParagraphs());
1624
1625         // final dimension
1626         dim.asc = firstRow()->ascent_of_text();
1627         dim.des = height - dim.asc;
1628         dim.wid = std::max(mi.base.textwidth, int(width));
1629 }
1630
1631
1632 // only used for inset right now. should also be used for main text
1633 void LyXText::draw(PainterInfo & pi, int x, int y) const
1634 {
1635         xo_ = x;
1636         yo_ = y;
1637         paintTextInset(*bv(), *this, x, y);
1638 }
1639
1640
1641 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
1642 {
1643         return row.endpos() >= pit->size()
1644                && boost::next(pit) == ownerParagraphs().end();
1645 }
1646
1647
1648 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
1649 {
1650         return row.pos() == 0 && pit == ownerParagraphs().begin();
1651 }
1652
1653
1654 void LyXText::cursorLeftOneWord(LyXCursor & cursor)
1655 {
1656         // treat HFills, floats and Insets as words
1657
1658         ParagraphList::iterator pit = cursorPar();
1659         size_t pos = cursor.pos();
1660
1661         while (pos &&
1662                (pit->isSeparator(pos - 1) ||
1663                 pit->isKomma(pos - 1) ||
1664                 pit->isNewline(pos - 1)) &&
1665                !(pit->isHfill(pos - 1) ||
1666                  pit->isInset(pos - 1)))
1667                 --pos;
1668
1669         if (pos &&
1670             (pit->isInset(pos - 1) ||
1671              pit->isHfill(pos - 1))) {
1672                 --pos;
1673         } else if (!pos) {
1674                 if (pit != ownerParagraphs().begin()) {
1675                         --pit;
1676                         pos = pit->size();
1677                 }
1678         } else {                // Here, cur != 0
1679                 while (pos > 0 && pit->isWord(pos - 1))
1680                         --pos;
1681         }
1682
1683         cursor.par(parOffset(pit));
1684         cursor.pos(pos);
1685 }
1686
1687
1688 void LyXText::cursorRightOneWord(LyXCursor & cursor)
1689 {
1690         // treat floats, HFills and Insets as words
1691         ParagraphList::iterator pit = cursorPar();
1692         pos_type pos = cursor.pos();
1693
1694         if (pos == pit->size() &&
1695                 boost::next(pit) != ownerParagraphs().end()) {
1696                 ++pit;
1697                 pos = 0;
1698         } else {
1699                 // Skip through initial nonword stuff.
1700                 while (pos < pit->size() && !pit->isWord(pos)) {
1701                         ++pos;
1702                 }
1703                 // Advance through word.
1704                 while (pos < pit->size() && pit->isWord(pos)) {
1705                         ++pos;
1706                 }
1707         }
1708
1709         cursor.par(parOffset(pit));
1710         cursor.pos(pos);
1711 }
1712
1713
1714 void LyXText::getWord(LyXCursor & from, LyXCursor & to, word_location const loc)
1715 {
1716         ParagraphList::iterator from_par = getPar(from);
1717         ParagraphList::iterator to_par = getPar(to);
1718         switch (loc) {
1719         case lyx::WHOLE_WORD_STRICT:
1720                 if (from.pos() == 0 || from.pos() == from_par->size()
1721                     || from_par->isSeparator(from.pos())
1722                     || from_par->isKomma(from.pos())
1723                     || from_par->isNewline(from.pos())
1724                     || from_par->isSeparator(from.pos() - 1)
1725                     || from_par->isKomma(from.pos() - 1)
1726                     || from_par->isNewline(from.pos() - 1)) {
1727                         to = from;
1728                         return;
1729                 }
1730                 // no break here, we go to the next
1731
1732         case lyx::WHOLE_WORD:
1733                 // Move cursor to the beginning, when not already there.
1734                 if (from.pos() && !from_par->isSeparator(from.pos() - 1)
1735                     && !(from_par->isKomma(from.pos() - 1)
1736                          || from_par->isNewline(from.pos() - 1)))
1737                         cursorLeftOneWord(from);
1738                 break;
1739         case lyx::PREVIOUS_WORD:
1740                 // always move the cursor to the beginning of previous word
1741                 cursorLeftOneWord(from);
1742                 break;
1743         case lyx::NEXT_WORD:
1744                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1745                        << endl;
1746                 break;
1747         case lyx::PARTIAL_WORD:
1748                 break;
1749         }
1750         to = from;
1751         while (to.pos() < to_par->size()
1752                && !to_par->isSeparator(to.pos())
1753                && !to_par->isKomma(to.pos())
1754                && !to_par->isNewline(to.pos())
1755                && !to_par->isHfill(to.pos())
1756                && !to_par->isInset(to.pos()))
1757         {
1758                 to.pos(to.pos() + 1);
1759         }
1760 }