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