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