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