]> git.lyx.org Git - lyx.git/blob - src/text.C
move the LyXText member
[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                 // add user added vertical space
661                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
662
663                 if (pit->params().startOfAppendix())
664                         maxasc += int(3 * dh);
665
666                 // This is special code for the chapter, since the label of this
667                 // layout is printed in an extra row
668                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
669                         labeladdon = int(font_metrics::maxHeight(labelfont)
670                                      * layout->spacing.getValue() * spacing(*pit));
671                 }
672
673                 // special code for the top label
674                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
675                      || layout->labeltype == LABEL_BIBLIO
676                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
677                     && isFirstInSequence(pit, ownerParagraphs())
678                     && !pit->getLabelstring().empty())
679                 {
680                         labeladdon = int(
681                                   font_metrics::maxHeight(labelfont)
682                                         * layout->spacing.getValue()
683                                         * spacing(*pit)
684                                 + (layout->topsep + layout->labelbottomsep) * dh);
685                 }
686
687                 // And now the layout spaces, for example before and after
688                 // a section, or between the items of a itemize or enumerate
689                 // environment.
690
691                 ParagraphList::iterator prev =
692                         depthHook(pit, ownerParagraphs(), pit->getDepth());
693                 if (prev != pit
694                     && prev->layout() == layout
695                     && prev->getDepth() == pit->getDepth()
696                     && prev->getLabelWidthString() == pit->getLabelWidthString())
697                 {
698                         layoutasc = layout->itemsep * dh;
699                 } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
700                         if (layout->topsep > 0)
701                                 layoutasc = layout->topsep * dh;
702                 }
703
704                 prev = outerHook(pit, ownerParagraphs());
705                 if (prev != ownerParagraphs().end()) {
706                         maxasc += int(prev->layout()->parsep * dh);
707                 } else if (pit != ownerParagraphs().begin()) {
708                         ParagraphList::iterator prior_pit = boost::prior(pit);
709                         if (prior_pit->getDepth() != 0 ||
710                                         prior_pit->layout() == layout) {
711                                 maxasc += int(layout->parsep * dh);
712                         }
713                 }
714         }
715
716         // is it a bottom line?
717         if (row.endpos() >= pit->size()) {
718                 // add the vertical spaces, that the user added
719                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
720
721                 // and now the layout spaces, for example before and after
722                 // a section, or between the items of a itemize or enumerate
723                 // environment
724                 ParagraphList::iterator nextpit = boost::next(pit);
725                 if (nextpit != ownerParagraphs().end()) {
726                         ParagraphList::iterator cpit = pit;
727                         double usual = 0;
728                         double unusual = 0;
729
730                         if (cpit->getDepth() > nextpit->getDepth()) {
731                                 usual = cpit->layout()->bottomsep * dh;
732                                 cpit = depthHook(cpit, ownerParagraphs(), nextpit->getDepth());
733                                 if (cpit->layout() != nextpit->layout()
734                                         || nextpit->getLabelWidthString() != cpit->getLabelWidthString())
735                                 {
736                                         unusual = cpit->layout()->bottomsep * dh;
737                                 }
738                                 layoutdesc = max(unusual, usual);
739                         } else if (cpit->getDepth() == nextpit->getDepth()) {
740                                 if (cpit->layout() != nextpit->layout()
741                                         || nextpit->getLabelWidthString() != cpit->getLabelWidthString())
742                                         layoutdesc = int(cpit->layout()->bottomsep * dh);
743                         }
744                 }
745         }
746
747         // incalculate the layout spaces
748         maxasc  += int(layoutasc  * 2 / (2 + pit->getDepth()));
749         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
750
751         row.height(maxasc + maxdesc + labeladdon);
752         row.baseline(maxasc + labeladdon);
753         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
754 }
755
756
757 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
758 {
759         // allow only if at start or end, or all previous is new text
760         ParagraphList::iterator cpit = cursorPar();
761         if (cursor.pos() && cursor.pos() != cpit->size()
762             && cpit->isChangeEdited(0, cursor.pos()))
763                 return;
764
765         LyXTextClass const & tclass =
766                 bv()->buffer()->params().getLyXTextClass();
767         LyXLayout_ptr const & layout = cpit->layout();
768
769         // this is only allowed, if the current paragraph is not empty or caption
770         // and if it has not the keepempty flag active
771         if (cpit->empty() && !cpit->allowEmpty()
772            && layout->labeltype != LABEL_SENSITIVE)
773                 return;
774
775         recUndo(cursor.par());
776
777         // Always break behind a space
778         //
779         // It is better to erase the space (Dekel)
780         if (cursor.pos() < cpit->size() && cpit->isLineSeparator(cursor.pos()))
781            cpit->erase(cursor.pos());
782
783         // break the paragraph
784         if (keep_layout)
785                 keep_layout = 2;
786         else
787                 keep_layout = layout->isEnvironment();
788
789         // we need to set this before we insert the paragraph. IMO the
790         // breakParagraph call should return a bool if it inserts the
791         // paragraph before or behind and we should react on that one
792         // but we can fix this in 1.3.0 (Jug 20020509)
793         bool const isempty = cpit->allowEmpty() && cpit->empty();
794         ::breakParagraph(bv()->buffer()->params(), paragraphs, cpit,
795                          cursor.pos(), keep_layout);
796
797 #warning Trouble Point! (Lgb)
798         // When ::breakParagraph is called from within an inset we must
799         // ensure that the correct ParagraphList is used. Today that is not
800         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
801         cpit = cursorPar();
802         ParagraphList::iterator next_par = boost::next(cpit);
803
804         // well this is the caption hack since one caption is really enough
805         if (layout->labeltype == LABEL_SENSITIVE) {
806                 if (!cursor.pos())
807                         // set to standard-layout
808                         cpit->applyLayout(tclass.defaultLayout());
809                 else
810                         // set to standard-layout
811                         next_par->applyLayout(tclass.defaultLayout());
812         }
813
814         // if the cursor is at the beginning of a row without prior newline,
815         // move one row up!
816         // This touches only the screen-update. Otherwise we would may have
817         // an empty row on the screen
818         RowList::iterator crit = cpit->getRow(cursor.pos());
819         if (cursor.pos() && crit->pos() == cursor.pos()
820             && !cpit->isNewline(cursor.pos() - 1))
821         {
822                 cursorLeft(bv());
823         }
824
825         while (!next_par->empty() && next_par->isNewline(0))
826                 next_par->erase(0);
827
828         updateCounters();
829         redoParagraph(cpit);
830         redoParagraph(next_par);
831
832         // This check is necessary. Otherwise the new empty paragraph will
833         // be deleted automatically. And it is more friendly for the user!
834         if (cursor.pos() || isempty)
835                 setCursor(next_par, 0);
836         else
837                 setCursor(cpit, 0);
838 }
839
840
841 // convenience function
842 void LyXText::redoParagraph()
843 {
844         clearSelection();
845         redoParagraph(cursorPar());
846         setCursorIntern(cursor.par(), cursor.pos());
847 }
848
849
850 // insert a character, moves all the following breaks in the
851 // same Paragraph one to the right and make a rebreak
852 void LyXText::insertChar(char c)
853 {
854         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
855
856         // When the free-spacing option is set for the current layout,
857         // disable the double-space checking
858
859         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
860                 cursorPar()->isFreeSpacing();
861
862         if (lyxrc.auto_number) {
863                 static string const number_operators = "+-/*";
864                 static string const number_unary_operators = "+-";
865                 static string const number_seperators = ".,:";
866
867                 if (current_font.number() == LyXFont::ON) {
868                         if (!IsDigit(c) && !contains(number_operators, c) &&
869                             !(contains(number_seperators, c) &&
870                               cursor.pos() >= 1 &&
871                               cursor.pos() < cursorPar()->size() &&
872                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
873                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
874                            )
875                                 number(); // Set current_font.number to OFF
876                 } else if (IsDigit(c) &&
877                            real_current_font.isVisibleRightToLeft()) {
878                         number(); // Set current_font.number to ON
879
880                         if (cursor.pos() > 0) {
881                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
882                                 if (contains(number_unary_operators, c) &&
883                                     (cursor.pos() == 1 ||
884                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
885                                      cursorPar()->isNewline(cursor.pos() - 2))
886                                   ) {
887                                         setCharFont(
888                                                     cursorPar(),
889                                                     cursor.pos() - 1,
890                                                     current_font);
891                                 } else if (contains(number_seperators, c) &&
892                                            cursor.pos() >= 2 &&
893                                            getFont(
894                                                    cursorPar(),
895                                                    cursor.pos() - 2).number() == LyXFont::ON) {
896                                         setCharFont(
897                                                     cursorPar(),
898                                                     cursor.pos() - 1,
899                                                     current_font);
900                                 }
901                         }
902                 }
903         }
904
905         // First check, if there will be two blanks together or a blank at
906         // the beginning of a paragraph.
907         // I decided to handle blanks like normal characters, the main
908         // difference are the special checks when calculating the row.fill
909         // (blank does not count at the end of a row) and the check here
910
911         // The bug is triggered when we type in a description environment:
912         // The current_font is not changed when we go from label to main text
913         // and it should (along with realtmpfont) when we type the space.
914         // CHECK There is a bug here! (Asger)
915
916         // store the current font.  This is because of the use of cursor
917         // movements. The moving cursor would refresh the current font
918         LyXFont realtmpfont = real_current_font;
919         LyXFont rawtmpfont = current_font;
920
921         if (!freeSpacing && IsLineSeparatorChar(c)) {
922                 if ((cursor.pos() > 0
923                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
924                     || (cursor.pos() > 0
925                         && cursorPar()->isNewline(cursor.pos() - 1))
926                     || (cursor.pos() == 0)) {
927                         static bool sent_space_message = false;
928                         if (!sent_space_message) {
929                                 if (cursor.pos() == 0)
930                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
931                                 else
932                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
933                                 sent_space_message = true;
934                         }
935                         charInserted();
936                         return;
937                 }
938         }
939
940         // Here case LyXText::InsertInset already inserted the character
941         if (c != Paragraph::META_INSET)
942                 cursorPar()->insertChar(cursor.pos(), c);
943
944         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
945
946         current_font = rawtmpfont;
947         real_current_font = realtmpfont;
948         redoParagraph(cursorPar());
949         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
950
951         charInserted();
952 }
953
954
955 void LyXText::charInserted()
956 {
957         // Here we call finishUndo for every 20 characters inserted.
958         // This is from my experience how emacs does it. (Lgb)
959         static unsigned int counter;
960         if (counter < 20) {
961                 ++counter;
962         } else {
963                 finishUndo();
964                 counter = 0;
965         }
966 }
967
968
969 void LyXText::prepareToPrint(ParagraphList::iterator pit, Row & row) const
970 {
971         double w = row.fill();
972         double fill_hfill = 0;
973         double fill_label_hfill = 0;
974         double fill_separator = 0;
975         double x = 0;
976
977         bool const is_rtl =
978                 pit->isRightToLeftPar(bv()->buffer()->params());
979         if (is_rtl)
980                 x = rightMargin(*pit);
981         else
982                 x = leftMargin(pit, row.pos());
983
984         // is there a manual margin with a manual label
985         LyXLayout_ptr const & layout = pit->layout();
986
987         if (layout->margintype == MARGIN_MANUAL
988             && layout->labeltype == LABEL_MANUAL) {
989                 /// We might have real hfills in the label part
990                 int nlh = numberOfLabelHfills(*pit, row);
991
992                 // A manual label par (e.g. List) has an auto-hfill
993                 // between the label text and the body of the
994                 // paragraph too.
995                 // But we don't want to do this auto hfill if the par
996                 // is empty.
997                 if (!pit->empty())
998                         ++nlh;
999
1000                 if (nlh && !pit->getLabelWidthString().empty())
1001                         fill_label_hfill = labelFill(pit, row) / double(nlh);
1002         }
1003
1004         // are there any hfills in the row?
1005         int const nh = numberOfHfills(*pit, row);
1006
1007         if (nh) {
1008                 if (w > 0)
1009                         fill_hfill = w / nh;
1010         // we don't have to look at the alignment if it is ALIGN_LEFT and
1011         // if the row is already larger then the permitted width as then
1012         // we force the LEFT_ALIGN'edness!
1013         } else if (int(row.width()) < textWidth()) {
1014                 // is it block, flushleft or flushright?
1015                 // set x how you need it
1016                 int align;
1017                 if (pit->params().align() == LYX_ALIGN_LAYOUT)
1018                         align = layout->align;
1019                 else
1020                         align = pit->params().align();
1021
1022                 // Display-style insets should always be on a centred row
1023                 // The test on pit->size() is to catch zero-size pars, which
1024                 // would trigger the assert in Paragraph::getInset().
1025                 //inset = pit->size() ? pit->getInset(row.pos()) : 0;
1026                 if (!pit->empty()
1027                     && pit->isInset(row.pos())
1028                     && pit->getInset(row.pos())->display())
1029                 {
1030                         align = LYX_ALIGN_CENTER;
1031                 }
1032
1033                 switch (align) {
1034     case LYX_ALIGN_BLOCK: {
1035                                 int const ns = numberOfSeparators(*pit, row);
1036                                 bool disp_inset = false;
1037                                 if (row.endpos() < pit->size()) {
1038                                         InsetOld * in = pit->getInset(row.endpos());
1039                                         if (in)
1040                                                 disp_inset = in->display();
1041                                 }
1042                                 // If we have separators, this is not the last row of a
1043                                 // par, does not end in newline, and is not row above a
1044                                 // display inset... then stretch it
1045                                 if (ns
1046                                         && row.endpos() < pit->size()
1047                                         && !pit->isNewline(row.endpos() - 1)
1048                                         && !disp_inset
1049                                         ) {
1050                                                 fill_separator = w / ns;
1051                                 } else if (is_rtl) {
1052                                         x += w;
1053                                 }
1054                                 break;
1055                         }
1056     case LYX_ALIGN_RIGHT:
1057                         x += w;
1058                         break;
1059     case LYX_ALIGN_CENTER:
1060                         x += w / 2;
1061                         break;
1062                 }
1063         }
1064
1065         bidi.computeTables(*pit, *bv()->buffer(), row);
1066         if (is_rtl) {
1067                 pos_type body_pos = pit->beginOfBody();
1068                 pos_type end = row.endpos();
1069
1070                 if (body_pos > 0
1071                     && (body_pos > end || !pit->isLineSeparator(body_pos - 1)))
1072                 {
1073                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1074                         if (body_pos <= end)
1075                                 x += fill_label_hfill;
1076                 }
1077         }
1078
1079         row.fill_hfill(fill_hfill);
1080         row.fill_label_hfill(fill_label_hfill);
1081         row.fill_separator(fill_separator);
1082         row.x(x);
1083 }
1084
1085
1086 // the cursor set functions have a special mechanism. When they
1087 // realize, that you left an empty paragraph, they will delete it.
1088
1089 void LyXText::cursorRightOneWord()
1090 {
1091         cursorRightOneWord(cursor);
1092         setCursor(cursorPar(), cursor.pos());
1093 }
1094
1095
1096 // Skip initial whitespace at end of word and move cursor to *start*
1097 // of prior word, not to end of next prior word.
1098 void LyXText::cursorLeftOneWord()
1099 {
1100         LyXCursor tmpcursor = cursor;
1101         cursorLeftOneWord(tmpcursor);
1102         setCursor(getPar(tmpcursor), tmpcursor.pos());
1103 }
1104
1105
1106 void LyXText::selectWord(word_location loc)
1107 {
1108         LyXCursor from = cursor;
1109         LyXCursor to = cursor;
1110         getWord(from, to, loc);
1111         if (cursor != from)
1112                 setCursor(from.par(), from.pos());
1113         if (to == from)
1114                 return;
1115         selection.cursor = cursor;
1116         setCursor(to.par(), to.pos());
1117         setSelection();
1118 }
1119
1120
1121 // Select the word currently under the cursor when no
1122 // selection is currently set
1123 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1124 {
1125         if (!selection.set()) {
1126                 selectWord(loc);
1127                 return selection.set();
1128         }
1129         return false;
1130 }
1131
1132
1133 void LyXText::acceptChange()
1134 {
1135         if (!selection.set() && cursorPar()->size())
1136                 return;
1137
1138         if (selection.start.par() == selection.end.par()) {
1139                 LyXCursor & startc = selection.start;
1140                 LyXCursor & endc = selection.end;
1141                 recordUndo(Undo::INSERT, this, startc.par());
1142                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1143                 finishUndo();
1144                 clearSelection();
1145                 redoParagraph(getPar(startc));
1146                 setCursorIntern(startc.par(), 0);
1147         }
1148 #warning handle multi par selection
1149 }
1150
1151
1152 void LyXText::rejectChange()
1153 {
1154         if (!selection.set() && cursorPar()->size())
1155                 return;
1156
1157         if (selection.start.par() == selection.end.par()) {
1158                 LyXCursor & startc = selection.start;
1159                 LyXCursor & endc = selection.end;
1160                 recordUndo(Undo::INSERT, this, startc.par());
1161                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1162                 finishUndo();
1163                 clearSelection();
1164                 redoParagraph(getPar(startc));
1165                 setCursorIntern(startc.par(), 0);
1166         }
1167 #warning handle multi par selection
1168 }
1169
1170
1171 // Delete from cursor up to the end of the current or next word.
1172 void LyXText::deleteWordForward()
1173 {
1174         if (cursorPar()->empty())
1175                 cursorRight(bv());
1176         else {
1177                 LyXCursor tmpcursor = cursor;
1178                 selection.set(true); // to avoid deletion
1179                 cursorRightOneWord();
1180                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1181                 selection.cursor = cursor;
1182                 cursor = tmpcursor;
1183                 setSelection();
1184                 cutSelection(true, false);
1185         }
1186 }
1187
1188
1189 // Delete from cursor to start of current or prior word.
1190 void LyXText::deleteWordBackward()
1191 {
1192         if (cursorPar()->empty())
1193                 cursorLeft(bv());
1194         else {
1195                 LyXCursor tmpcursor = cursor;
1196                 selection.set(true); // to avoid deletion
1197                 cursorLeftOneWord();
1198                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1199                 selection.cursor = cursor;
1200                 cursor = tmpcursor;
1201                 setSelection();
1202                 cutSelection(true, false);
1203         }
1204 }
1205
1206
1207 // Kill to end of line.
1208 void LyXText::deleteLineForward()
1209 {
1210         if (cursorPar()->empty()) {
1211                 // Paragraph is empty, so we just go to the right
1212                 cursorRight(bv());
1213         } else {
1214                 LyXCursor tmpcursor = cursor;
1215                 // We can't store the row over a regular setCursor
1216                 // so we set it to 0 and reset it afterwards.
1217                 selection.set(true); // to avoid deletion
1218                 cursorEnd();
1219                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1220                 selection.cursor = cursor;
1221                 cursor = tmpcursor;
1222                 setSelection();
1223                 // What is this test for ??? (JMarc)
1224                 if (!selection.set())
1225                         deleteWordForward();
1226                 else
1227                         cutSelection(true, false);
1228         }
1229 }
1230
1231
1232 void LyXText::changeCase(LyXText::TextCase action)
1233 {
1234         LyXCursor from;
1235         LyXCursor to;
1236
1237         if (selection.set()) {
1238                 from = selection.start;
1239                 to = selection.end;
1240         } else {
1241                 from = cursor;
1242                 getWord(from, to, lyx::PARTIAL_WORD);
1243                 setCursor(to.par(), to.pos() + 1);
1244         }
1245
1246         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1247
1248         pos_type pos = from.pos();
1249         int par = from.par();
1250
1251         while (par != int(ownerParagraphs().size()) &&
1252                (pos != to.pos() || par != to.par())) {
1253                 ParagraphList::iterator pit = getPar(par);
1254                 if (pos == pit->size()) {
1255                         ++par;
1256                         pos = 0;
1257                         continue;
1258                 }
1259                 unsigned char c = pit->getChar(pos);
1260                 if (c != Paragraph::META_INSET) {
1261                         switch (action) {
1262                         case text_lowercase:
1263                                 c = lowercase(c);
1264                                 break;
1265                         case text_capitalization:
1266                                 c = uppercase(c);
1267                                 action = text_lowercase;
1268                                 break;
1269                         case text_uppercase:
1270                                 c = uppercase(c);
1271                                 break;
1272                         }
1273                 }
1274 #warning changes
1275                 pit->setChar(pos, c);
1276                 ++pos;
1277         }
1278 }
1279
1280
1281 void LyXText::Delete()
1282 {
1283         // this is a very easy implementation
1284         LyXCursor old_cursor = cursor;
1285
1286         // just move to the right
1287         cursorRight(true);
1288
1289         // if you had success make a backspace
1290         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1291                 recordUndo(Undo::DELETE, this, old_cursor.par());
1292                 backspace();
1293         }
1294 }
1295
1296
1297 void LyXText::backspace()
1298 {
1299         // Get the font that is used to calculate the baselineskip
1300         ParagraphList::iterator pit = cursorPar();
1301         pos_type lastpos = pit->size();
1302
1303         if (cursor.pos() == 0) {
1304                 // The cursor is at the beginning of a paragraph,
1305                 // so the the backspace will collapse two paragraphs into one.
1306
1307                 // but it's not allowed unless it's new
1308                 if (pit->isChangeEdited(0, pit->size()))
1309                         return;
1310
1311                 // we may paste some paragraphs
1312
1313                 // is it an empty paragraph?
1314
1315                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1316                         // This is an empty paragraph and we delete it just
1317                         // by moving the cursor one step
1318                         // left and let the DeleteEmptyParagraphMechanism
1319                         // handle the actual deletion of the paragraph.
1320
1321                         if (cursor.par()) {
1322                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1323                                 if (cursorPar()->layout() == tmppit->layout()
1324                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1325                                         // Inherit bottom DTD from the paragraph below.
1326                                         // (the one we are deleting)
1327                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1328                                 }
1329
1330                                 cursorLeft(bv());
1331
1332                                 // the layout things can change the height of a row !
1333                                 redoParagraph();
1334                                 return;
1335                         }
1336                 }
1337
1338                 if (cursor.par() != 0)
1339                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1340
1341                 ParagraphList::iterator tmppit = cursorPar();
1342                 // We used to do cursorLeftIntern() here, but it is
1343                 // not a good idea since it triggers the auto-delete
1344                 // mechanism. So we do a cursorLeftIntern()-lite,
1345                 // without the dreaded mechanism. (JMarc)
1346                 if (cursor.par() != 0) {
1347                         // steps into the above paragraph.
1348                         setCursorIntern(cursor.par() - 1,
1349                                         getPar(cursor.par() - 1)->size(),
1350                                         false);
1351                 }
1352
1353                 // Pasting is not allowed, if the paragraphs have different
1354                 // layout. I think it is a real bug of all other
1355                 // word processors to allow it. It confuses the user.
1356                 // Correction: Pasting is always allowed with standard-layout
1357                 Buffer & buf = *bv()->buffer();
1358                 BufferParams const & bufparams = buf.params();
1359                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1360                 ParagraphList::iterator const cpit = cursorPar();
1361
1362                 if (cpit != tmppit
1363                     && (cpit->layout() == tmppit->layout()
1364                         || tmppit->layout() == tclass.defaultLayout())
1365                     && cpit->getAlign() == tmppit->getAlign()) {
1366                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1367
1368                         if (cursor.pos() && cpit->isSeparator(cursor.pos() - 1))
1369                                 cursor.pos(cursor.pos() - 1);
1370
1371                         // the counters may have changed
1372                         updateCounters();
1373                         setCursor(cursor.par(), cursor.pos(), false);
1374                 }
1375         } else {
1376                 // this is the code for a normal backspace, not pasting
1377                 // any paragraphs
1378                 recordUndo(Undo::DELETE, this, cursor.par());
1379                 // We used to do cursorLeftIntern() here, but it is
1380                 // not a good idea since it triggers the auto-delete
1381                 // mechanism. So we do a cursorLeftIntern()-lite,
1382                 // without the dreaded mechanism. (JMarc)
1383                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1384                                 false, cursor.boundary());
1385                 cursorPar()->erase(cursor.pos());
1386         }
1387
1388         lastpos = cursorPar()->size();
1389         if (cursor.pos() == lastpos)
1390                 setCurrentFont();
1391
1392         redoParagraph();
1393         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
1394 }
1395
1396
1397 ParagraphList::iterator LyXText::cursorPar() const
1398 {
1399         return getPar(cursor.par());
1400 }
1401
1402
1403 RowList::iterator LyXText::cursorRow() const
1404 {
1405         return cursorPar()->getRow(cursor.pos());
1406 }
1407
1408
1409 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1410 {
1411         return getPar(cur.par());
1412 }
1413
1414
1415 ParagraphList::iterator LyXText::getPar(int par) const
1416 {
1417         BOOST_ASSERT(par >= 0);
1418         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1419         ParagraphList::iterator pit = ownerParagraphs().begin();
1420         std::advance(pit, par);
1421         return pit;
1422 }
1423
1424
1425 RowList::iterator
1426 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1427 {
1428         //lyxerr << "getRowNearY: y " << y << endl;
1429 #if 1
1430         ParagraphList::iterator const
1431                 pend = boost::prior(ownerParagraphs().end());
1432         pit = ownerParagraphs().begin();
1433         while (int(pit->y + pit->height) < y && pit != pend)
1434                 ++pit;
1435
1436         RowList::iterator rit = pit->rows.end();
1437         RowList::iterator const rbegin = pit->rows.begin();
1438         do {
1439                 --rit;
1440         } while (rit != rbegin && int(pit->y + rit->y_offset()) > y);
1441
1442         return rit;
1443 #else
1444         pit = boost::prior(ownerParagraphs().end());
1445
1446         RowList::iterator rit = lastRow();
1447         RowList::iterator rbegin = firstRow();
1448
1449         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1450                 previousRow(pit, rit);
1451
1452         return rit;
1453 #endif
1454 }
1455
1456
1457 int LyXText::getDepth() const
1458 {
1459         return cursorPar()->getDepth();
1460 }
1461
1462
1463 RowList::iterator LyXText::firstRow() const
1464 {
1465         return ownerParagraphs().front().rows.begin();
1466 }
1467
1468
1469 ParagraphList::iterator LyXText::firstPar() const
1470 {
1471         return ownerParagraphs().begin();
1472 }
1473
1474
1475 RowList::iterator LyXText::lastRow() const
1476 {
1477         return boost::prior(endRow());
1478 }
1479
1480
1481 ParagraphList::iterator LyXText::lastPar() const
1482 {
1483         return boost::prior(endPar());
1484 }
1485
1486
1487 RowList::iterator LyXText::endRow() const
1488 {
1489         return ownerParagraphs().back().rows.end();
1490 }
1491
1492
1493 ParagraphList::iterator LyXText::endPar() const
1494 {
1495         return ownerParagraphs().end();
1496 }
1497
1498
1499 void LyXText::nextRow(ParagraphList::iterator & pit,
1500         RowList::iterator & rit) const
1501 {
1502         ++rit;
1503         if (rit == pit->rows.end()) {
1504                 ++pit;
1505                 if (pit == ownerParagraphs().end())
1506                         --pit;
1507                 else
1508                         rit = pit->rows.begin();
1509         }
1510 }
1511
1512
1513 void LyXText::previousRow(ParagraphList::iterator & pit,
1514         RowList::iterator & rit) const
1515 {
1516         if (rit != pit->rows.begin())
1517                 --rit;
1518         else {
1519                 BOOST_ASSERT(pit != ownerParagraphs().begin());
1520                 --pit;
1521                 rit = boost::prior(pit->rows.end());
1522         }
1523 }
1524
1525
1526 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1527 {
1528         if (!selection.set())
1529                 return string();
1530
1531         // should be const ...
1532         ParagraphList::iterator startpit = getPar(selection.start);
1533         ParagraphList::iterator endpit = getPar(selection.end);
1534         size_t const startpos = selection.start.pos();
1535         size_t const endpos = selection.end.pos();
1536
1537         if (startpit == endpit)
1538                 return startpit->asString(buffer, startpos, endpos, label);
1539
1540         // First paragraph in selection
1541         string result =
1542                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1543
1544         // The paragraphs in between (if any)
1545         ParagraphList::iterator pit = startpit;
1546         for (++pit; pit != endpit; ++pit)
1547                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1548
1549         // Last paragraph in selection
1550         result += endpit->asString(buffer, 0, endpos, label);
1551
1552         return result;
1553 }
1554
1555
1556 int LyXText::parOffset(ParagraphList::iterator pit) const
1557 {
1558         return std::distance(ownerParagraphs().begin(), pit);
1559 }
1560
1561
1562 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1563 {
1564         // remove rows of paragraph, keep track of height changes
1565         height -= pit->height;
1566
1567         // clear old data
1568         pit->rows.clear();
1569         pit->height = 0;
1570         pit->width = 0;
1571
1572         // redo insets
1573         InsetList::iterator ii = pit->insetlist.begin();
1574         InsetList::iterator iend = pit->insetlist.end();
1575         for (; ii != iend; ++ii) {
1576                 Dimension dim;
1577                 int const w = textWidth() - leftMargin(pit) - rightMargin(*pit);
1578                 MetricsInfo mi(bv(), getFont(pit, ii->pos), w);
1579                 ii->inset->metrics(mi, dim);
1580         }
1581
1582         // rebreak the paragraph
1583         pit->setBeginOfBody();
1584         pos_type z = 0;
1585         do {
1586                 Row row(z);
1587                 rowBreakPoint(pit, row);
1588                 z = row.endpos();
1589                 fill(pit, row, textwidth_);
1590                 prepareToPrint(pit, row);
1591                 setHeightOfRow(pit, row);
1592                 row.y_offset(pit->height);
1593                 pit->rows.push_back(row);
1594                 pit->width = std::max(pit->width, row.width());
1595                 pit->height += row.height();
1596         } while (z < pit->size());
1597
1598         height += pit->height;
1599         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1600 }
1601
1602
1603 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1604   ParagraphList::iterator end)
1605 {
1606         for ( ; pit != end; ++pit)
1607                 redoParagraphInternal(pit);
1608         updateParPositions();
1609 }
1610
1611
1612 void LyXText::redoParagraph(ParagraphList::iterator pit)
1613 {
1614         redoParagraphInternal(pit);
1615         updateParPositions();
1616 }
1617
1618
1619 void LyXText::fullRebreak()
1620 {
1621         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1622         redoCursor();
1623         selection.cursor = cursor;
1624 }
1625
1626
1627 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1628 {
1629         //BOOST_ASSERT(mi.base.textwidth);
1630         if (mi.base.textwidth)
1631                 textwidth_ = mi.base.textwidth;
1632         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1633         //      << " textWidth: " << textWidth() << "\nfont: " << mi.base.font << endl;
1634
1635         // Rebuild row cache. This recomputes height as well.
1636         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1637
1638         width = maxParagraphWidth(ownerParagraphs());
1639
1640         // final dimension
1641         dim.asc = firstRow()->ascent_of_text();
1642         dim.des = height - dim.asc;
1643         dim.wid = std::max(mi.base.textwidth, int(width));
1644 }
1645
1646
1647 // only used for inset right now. should also be used for main text
1648 void LyXText::draw(PainterInfo & pi, int x, int y) const
1649 {
1650         xo_ = x;
1651         yo_ = y;
1652         paintTextInset(*bv(), *this, x, y);
1653 }
1654
1655
1656 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
1657 {
1658         return row.endpos() >= pit->size()
1659                && boost::next(pit) == ownerParagraphs().end();
1660 }
1661
1662
1663 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
1664 {
1665         return row.pos() == 0 && pit == ownerParagraphs().begin();
1666 }
1667
1668
1669 void LyXText::cursorLeftOneWord(LyXCursor & cursor)
1670 {
1671         // treat HFills, floats and Insets as words
1672
1673         ParagraphList::iterator pit = cursorPar();
1674         size_t pos = cursor.pos();
1675
1676         while (pos &&
1677                (pit->isSeparator(pos - 1) ||
1678                 pit->isKomma(pos - 1) ||
1679                 pit->isNewline(pos - 1)) &&
1680                !(pit->isHfill(pos - 1) ||
1681                  pit->isInset(pos - 1)))
1682                 --pos;
1683
1684         if (pos &&
1685             (pit->isInset(pos - 1) ||
1686              pit->isHfill(pos - 1))) {
1687                 --pos;
1688         } else if (!pos) {
1689                 if (pit != ownerParagraphs().begin()) {
1690                         --pit;
1691                         pos = pit->size();
1692                 }
1693         } else {                // Here, cur != 0
1694                 while (pos > 0 && pit->isWord(pos - 1))
1695                         --pos;
1696         }
1697
1698         cursor.par(parOffset(pit));
1699         cursor.pos(pos);
1700 }
1701
1702
1703 void LyXText::cursorRightOneWord(LyXCursor & cursor)
1704 {
1705         // treat floats, HFills and Insets as words
1706         ParagraphList::iterator pit = cursorPar();
1707         pos_type pos = cursor.pos();
1708
1709         if (pos == pit->size() &&
1710                 boost::next(pit) != ownerParagraphs().end()) {
1711                 ++pit;
1712                 pos = 0;
1713         } else {
1714                 // Skip through initial nonword stuff.
1715                 while (pos < pit->size() && !pit->isWord(pos)) {
1716                         ++pos;
1717                 }
1718                 // Advance through word.
1719                 while (pos < pit->size() && pit->isWord(pos)) {
1720                         ++pos;
1721                 }
1722         }
1723
1724         cursor.par(parOffset(pit));
1725         cursor.pos(pos);
1726 }
1727
1728
1729 void LyXText::getWord(LyXCursor & from, LyXCursor & to, word_location const loc)
1730 {
1731         ParagraphList::iterator from_par = getPar(from);
1732         ParagraphList::iterator to_par = getPar(to);
1733         switch (loc) {
1734         case lyx::WHOLE_WORD_STRICT:
1735                 if (from.pos() == 0 || from.pos() == from_par->size()
1736                     || from_par->isSeparator(from.pos())
1737                     || from_par->isKomma(from.pos())
1738                     || from_par->isNewline(from.pos())
1739                     || from_par->isSeparator(from.pos() - 1)
1740                     || from_par->isKomma(from.pos() - 1)
1741                     || from_par->isNewline(from.pos() - 1)) {
1742                         to = from;
1743                         return;
1744                 }
1745                 // no break here, we go to the next
1746
1747         case lyx::WHOLE_WORD:
1748                 // Move cursor to the beginning, when not already there.
1749                 if (from.pos() && !from_par->isSeparator(from.pos() - 1)
1750                     && !(from_par->isKomma(from.pos() - 1)
1751                          || from_par->isNewline(from.pos() - 1)))
1752                         cursorLeftOneWord(from);
1753                 break;
1754         case lyx::PREVIOUS_WORD:
1755                 // always move the cursor to the beginning of previous word
1756                 cursorLeftOneWord(from);
1757                 break;
1758         case lyx::NEXT_WORD:
1759                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1760                        << endl;
1761                 break;
1762         case lyx::PARTIAL_WORD:
1763                 break;
1764         }
1765         to = from;
1766         while (to.pos() < to_par->size()
1767                && !to_par->isSeparator(to.pos())
1768                && !to_par->isKomma(to.pos())
1769                && !to_par->isNewline(to.pos())
1770                && !to_par->isHfill(to.pos())
1771                && !to_par->isInset(to.pos()))
1772         {
1773                 to.pos(to.pos() + 1);
1774         }
1775 }