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