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