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