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