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