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