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