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