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