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