]> git.lyx.org Git - lyx.git/blob - src/text.C
Point fix, earlier forgotten
[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 #include "paragraph.h"
21 #include "gettext.h"
22 #include "bufferparams.h"
23 #include "buffer.h"
24 #include "debug.h"
25 #include "intl.h"
26 #include "lyxrc.h"
27 #include "encoding.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Painter.h"
30 #include "frontends/font_metrics.h"
31 #include "frontends/screen.h"
32 #include "frontends/WorkArea.h"
33 #include "bufferview_funcs.h"
34 #include "BufferView.h"
35 #include "language.h"
36 #include "ParagraphParameters.h"
37 #include "undo_funcs.h"
38 #include "text_funcs.h"
39 #include "WordLangTuple.h"
40 #include "paragraph_funcs.h"
41 #include "rowpainter.h"
42 #include "lyxrow_funcs.h"
43 #include "metricsinfo.h"
44
45 #include "insets/insettext.h"
46
47 #include "support/textutils.h"
48 #include "support/LAssert.h"
49 #include "support/lstrings.h"
50
51 #include <algorithm>
52
53 using namespace lyx::support;
54
55 using std::max;
56 using std::min;
57 using std::endl;
58 using std::pair;
59
60 using lyx::pos_type;
61 using lyx::word_location;
62
63 using namespace bv_funcs;
64
65 /// top, right, bottom pixel margin
66 extern int const PAPER_MARGIN = 20;
67 /// margin for changebar
68 extern int const CHANGEBAR_MARGIN = 10;
69 /// left margin
70 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
71
72
73
74 int bibitemMaxWidth(BufferView *, LyXFont const &);
75
76
77 BufferView * LyXText::bv()
78 {
79         Assert(bv_owner != 0);
80         return bv_owner;
81 }
82
83
84 BufferView * LyXText::bv() const
85 {
86         Assert(bv_owner != 0);
87         return bv_owner;
88 }
89
90
91 void LyXText::updateRowPositions()
92 {
93         ParagraphList::iterator pit = ownerParagraphs().begin();
94         ParagraphList::iterator end = ownerParagraphs().end();
95         for (height = 0; pit != end; ++pit) {
96                 RowList::iterator rit = pit->rows.begin();
97                 RowList::iterator rend = pit->rows.end();
98                 for ( ; rit != rend ; rit = ++rit) {
99                         rit->y(height);
100                         height += rit->height();
101                 }
102         }
103 }
104
105
106 int LyXText::workWidth() const
107 {
108         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
109 }
110
111
112 int LyXText::getRealCursorX() const
113 {
114         int x = cursor.x();
115         if (the_locking_inset && (the_locking_inset->getLyXText(bv())!= this))
116                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
117         return x;
118 }
119
120
121 #warning FIXME  This function seems to belong outside of LyxText.
122 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
123                                      pos_type pos) const
124 {
125         if (!Encodings::is_arabic(c))
126                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
127                         return c + (0xb0 - '0');
128                 else
129                         return c;
130
131         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
132         unsigned char next_char = ' ';
133
134         pos_type const par_size = par.size();
135
136         for (pos_type i = pos + 1; i < par_size; ++i) {
137                 unsigned char const par_char = par.getChar(i);
138                 if (!Encodings::IsComposeChar_arabic(par_char)) {
139                         next_char = par_char;
140                         break;
141                 }
142         }
143
144         if (Encodings::is_arabic(next_char)) {
145                 if (Encodings::is_arabic(prev_char) &&
146                         !Encodings::is_arabic_special(prev_char))
147                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
148                 else
149                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
150         } else {
151                 if (Encodings::is_arabic(prev_char) &&
152                         !Encodings::is_arabic_special(prev_char))
153                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
154                 else
155                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
156         }
157 }
158
159 // This is the comments that some of the warnings below refers to.
160 // There are some issues in this file and I don't think they are
161 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
162 // this is a problem that has been here almost from day one and that a
163 // larger userbase with differenct access patters triggers the bad
164 // behaviour. (segfaults.) What I think happen is: In several places
165 // we store the paragraph in the current cursor and then moves the
166 // cursor. This movement of the cursor will delete paragraph at the
167 // old position if it is now empty. This will make the temporary
168 // pointer to the old cursor paragraph invalid and dangerous to use.
169 // And is some cases this will trigger a segfault. I have marked some
170 // of the cases where this happens with a warning, but I am sure there
171 // are others in this file and in text2.C. There is also a note in
172 // Delete() that you should read. In Delete I store the paragraph->id
173 // instead of a pointer to the paragraph. I am pretty sure this faulty
174 // use of temporary pointers to paragraphs that might have gotten
175 // invalidated (through a cursor movement) before they are used, are
176 // the cause of the strange crashes we get reported often.
177 //
178 // It is very tiresom to change this code, especially when it is as
179 // hard to read as it is. Help to fix all the cases where this is done
180 // would be greately appreciated.
181 //
182 // Lgb
183
184 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
185 {
186         if (pos >= pit->size())
187                 return 0;
188
189         char const c = pit->getChar(pos);
190         LyXFont const & font = getFont(pit, pos);
191         return singleWidth(pit, pos, c, font);
192 }
193
194
195 int LyXText::singleWidth(ParagraphList::iterator pit,
196                          pos_type pos, char c, LyXFont const & font) const
197 {
198         if (pos >= pit->size()) {
199                 lyxerr << "in singleWidth(), pos: " << pos << endl;
200                 Assert(false);
201                 return 0;
202         }
203
204
205         // The most common case is handled first (Asger)
206         if (IsPrintable(c)) {
207                 if (font.language()->RightToLeft()) {
208                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
209                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
210                             && font.language()->lang() == "arabic") {
211                                 if (Encodings::IsComposeChar_arabic(c))
212                                         return 0;
213                                 else
214                                         c = transformChar(c, *pit, pos);
215                         } else if (font.language()->lang() == "hebrew" &&
216                                  Encodings::IsComposeChar_hebrew(c))
217                                 return 0;
218                 }
219                 return font_metrics::width(c, font);
220         }
221
222         if (c == Paragraph::META_INSET) {
223                 InsetOld * tmpinset = pit->getInset(pos);
224                 Assert(tmpinset);
225                 if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
226                         // Because of the representation as vertical lines
227                         return 3;
228                 }
229                 return tmpinset->width();
230         }
231
232         if (IsSeparatorChar(c))
233                 c = ' ';
234         return font_metrics::width(c, font);
235 }
236
237
238 lyx::pos_type LyXText::log2vis(lyx::pos_type pos) const
239 {
240         if (bidi_start == -1)
241                 return pos;
242         else
243                 return log2vis_list[pos - bidi_start];
244 }
245
246
247 lyx::pos_type LyXText::vis2log(lyx::pos_type pos) const
248 {
249         if (bidi_start == -1)
250                 return pos;
251         else
252                 return vis2log_list[pos - bidi_start];
253 }
254
255
256 lyx::pos_type LyXText::bidi_level(lyx::pos_type pos) const
257 {
258         if (bidi_start == -1)
259                 return 0;
260         else
261                 return bidi_levels[pos - bidi_start];
262 }
263
264
265 bool LyXText::bidi_InRange(lyx::pos_type pos) const
266 {
267         return bidi_start == -1 ||
268                 (bidi_start <= pos && pos <= bidi_end);
269 }
270
271
272 void LyXText::computeBidiTables(ParagraphList::iterator pit,
273    Buffer const & buf, RowList::iterator row) const
274 {
275         bidi_same_direction = true;
276         if (!lyxrc.rtl_support) {
277                 bidi_start = -1;
278                 return;
279         }
280
281         InsetOld * inset = pit->inInset();
282         if (inset && inset->owner() &&
283             inset->owner()->lyxCode() == InsetOld::ERT_CODE) {
284                 bidi_start = -1;
285                 return;
286         }
287
288         bidi_start = row->pos();
289         bidi_end = lastPrintablePos(*pit, row);
290
291         if (bidi_start > bidi_end) {
292                 bidi_start = -1;
293                 return;
294         }
295
296         if (bidi_end + 2 - bidi_start >
297             static_cast<pos_type>(log2vis_list.size())) {
298                 pos_type new_size =
299                         (bidi_end + 2 - bidi_start < 500) ?
300                         500 : 2 * (bidi_end + 2 - bidi_start);
301                 log2vis_list.resize(new_size);
302                 vis2log_list.resize(new_size);
303                 bidi_levels.resize(new_size);
304         }
305
306         vis2log_list[bidi_end + 1 - bidi_start] = -1;
307         log2vis_list[bidi_end + 1 - bidi_start] = -1;
308
309         pos_type stack[2];
310         bool const rtl_par =
311                 pit->isRightToLeftPar(buf.params);
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(buf.params, pos);
325                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
326                     font.number() == LyXFont::ON &&
327                     pit->getFontSettings(buf.params, lpos - 1).number()
328                     == LyXFont::ON) {
329                         font = pit->getFontSettings(buf.params, 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 = lastPrintablePos(*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         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
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 += bv()->buffer()->params.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 += bv()->buffer()->params.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->labeltype == LABEL_COUNTER_CHAPTER
1036                         && bv()->buffer()->params.secnumdepth >= 0)
1037                 {
1038                         float spacing_val = 1.0;
1039                         if (!pit->params().spacing().isDefault()) {
1040                                 spacing_val = pit->params().spacing().getValue();
1041                         } else {
1042                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1043                         }
1044
1045                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1046                                          layout->spacing.getValue() *
1047                                          spacing_val)
1048                                 + int(font_metrics::maxAscent(labelfont) *
1049                                       layout->spacing.getValue() *
1050                                       spacing_val);
1051                 }
1052
1053                 // special code for the top label
1054                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1055                      || layout->labeltype == LABEL_BIBLIO
1056                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1057                     && isFirstInSequence(pit, ownerParagraphs())
1058                     && !pit->getLabelstring().empty())
1059                 {
1060                         float spacing_val = 1.0;
1061                         if (!pit->params().spacing().isDefault()) {
1062                                 spacing_val = pit->params().spacing().getValue();
1063                         } else {
1064                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1065                         }
1066
1067                         labeladdon = int(
1068                                 (font_metrics::maxAscent(labelfont) +
1069                                  font_metrics::maxDescent(labelfont)) *
1070                                   layout->spacing.getValue() *
1071                                   spacing_val
1072                                 + layout->topsep * defaultRowHeight()
1073                                 + layout->labelbottomsep * defaultRowHeight());
1074                 }
1075
1076                 // And now the layout spaces, for example before and after
1077                 // a section, or between the items of a itemize or enumerate
1078                 // environment.
1079
1080                 if (!pit->params().pagebreakTop()) {
1081                         ParagraphList::iterator prev =
1082                                 depthHook(pit, ownerParagraphs(),
1083                                           pit->getDepth());
1084                         if (prev != pit && prev->layout() == layout &&
1085                                 prev->getDepth() == pit->getDepth() &&
1086                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1087                         {
1088                                 layoutasc = (layout->itemsep * defaultRowHeight());
1089                         } else if (rit != firstRow()) {
1090                                 tmptop = layout->topsep;
1091
1092                                 //if (boost::prior(pit)->getDepth() >= pit->getDepth())
1093                                 //      tmptop -= getPar(previousRow(rit))->layout()->bottomsep;
1094
1095                                 if (tmptop > 0)
1096                                         layoutasc = (tmptop * defaultRowHeight());
1097                         } else if (pit->params().lineTop()) {
1098                                 tmptop = layout->topsep;
1099
1100                                 if (tmptop > 0)
1101                                         layoutasc = (tmptop * defaultRowHeight());
1102                         }
1103
1104                         prev = outerHook(pit, ownerParagraphs());
1105                         if (prev != ownerParagraphs().end())  {
1106                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1107                         } else if (pit != ownerParagraphs().begin()) {
1108                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1109                                 if (prior_pit->getDepth() != 0 ||
1110                                     prior_pit->layout() == layout) {
1111                                         maxasc += int(layout->parsep * defaultRowHeight());
1112                                 }
1113                         }
1114                 }
1115         }
1116
1117         // is it a bottom line?
1118         if (boost::next(rit) == pit->rows.end()) {
1119                 // the bottom margin
1120                 ParagraphList::iterator nextpit = boost::next(pit);
1121                 if (nextpit == ownerParagraphs().end() && !isInInset())
1122                         maxdesc += PAPER_MARGIN;
1123
1124                 // add the vertical spaces, that the user added
1125                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1126
1127                 // do not forget the DTP-lines!
1128                 // there height depends on the font of the nearest character
1129                 if (pit->params().lineBottom())
1130                         maxdesc += 2 * font_metrics::ascent('x',
1131                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1132
1133                 // and now the pagebreaks
1134                 if (pit->params().pagebreakBottom())
1135                         maxdesc += 3 * defaultRowHeight();
1136
1137                 // and now the layout spaces, for example before and after
1138                 // a section, or between the items of a itemize or enumerate
1139                 // environment
1140                 if (!pit->params().pagebreakBottom()
1141                     && nextpit != ownerParagraphs().end()) {
1142                         ParagraphList::iterator comparepit = pit;
1143                         float usual = 0;
1144                         float unusual = 0;
1145
1146                         if (comparepit->getDepth() > nextpit->getDepth()) {
1147                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1148                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1149                                 if (comparepit->layout()!= nextpit->layout()
1150                                         || nextpit->getLabelWidthString() !=
1151                                         comparepit->getLabelWidthString())
1152                                 {
1153                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1154                                 }
1155                                 if (unusual > usual)
1156                                         layoutdesc = unusual;
1157                                 else
1158                                         layoutdesc = usual;
1159                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1160
1161                                 if (comparepit->layout() != nextpit->layout()
1162                                         || nextpit->getLabelWidthString() !=
1163                                         comparepit->getLabelWidthString())
1164                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1165                         }
1166                 }
1167         }
1168
1169         // incalculate the layout spaces
1170         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1171         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1172
1173         rit->height(maxasc + maxdesc + labeladdon);
1174         rit->baseline(maxasc + labeladdon);
1175         rit->top_of_text(rit->baseline() - font_metrics::maxAscent(font));
1176
1177         double x = 0;
1178         rit->width(int(maxwidth + x));
1179         if (inset_owner) {
1180                 width = max(0, workWidth());
1181                 RowList::iterator rit = firstRow();
1182                 RowList::iterator end = endRow();
1183                 ParagraphList::iterator it = ownerParagraphs().begin();
1184                 while (rit != end) {
1185                         if (rit->width() > width)
1186                                 width = rit->width();
1187                         nextRow(it, rit);
1188                 }
1189         }
1190 }
1191
1192
1193 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1194 {
1195         // allow only if at start or end, or all previous is new text
1196         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1197                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1198                 return;
1199
1200         LyXTextClass const & tclass =
1201                 bv()->buffer()->params.getLyXTextClass();
1202         LyXLayout_ptr const & layout = cursor.par()->layout();
1203
1204         // this is only allowed, if the current paragraph is not empty or caption
1205         // and if it has not the keepempty flag active
1206         if (cursor.par()->empty() && !cursor.par()->allowEmpty()
1207            && layout->labeltype != LABEL_SENSITIVE)
1208                 return;
1209
1210         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1211
1212         // Always break behind a space
1213         //
1214         // It is better to erase the space (Dekel)
1215         if (cursor.pos() < cursor.par()->size()
1216              && cursor.par()->isLineSeparator(cursor.pos()))
1217            cursor.par()->erase(cursor.pos());
1218
1219         // break the paragraph
1220         if (keep_layout)
1221                 keep_layout = 2;
1222         else
1223                 keep_layout = layout->isEnvironment();
1224
1225         // we need to set this before we insert the paragraph. IMO the
1226         // breakParagraph call should return a bool if it inserts the
1227         // paragraph before or behind and we should react on that one
1228         // but we can fix this in 1.3.0 (Jug 20020509)
1229         bool const isempty = (cursor.par()->allowEmpty() && cursor.par()->empty());
1230         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(),
1231                          cursor.pos(), keep_layout);
1232
1233 #warning Trouble Point! (Lgb)
1234         // When ::breakParagraph is called from within an inset we must
1235         // ensure that the correct ParagraphList is used. Today that is not
1236         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1237         ParagraphList::iterator next_par = boost::next(cursor.par());
1238
1239         // well this is the caption hack since one caption is really enough
1240         if (layout->labeltype == LABEL_SENSITIVE) {
1241                 if (!cursor.pos())
1242                         // set to standard-layout
1243                         cursor.par()->applyLayout(tclass.defaultLayout());
1244                 else
1245                         // set to standard-layout
1246                         next_par->applyLayout(tclass.defaultLayout());
1247         }
1248
1249         // if the cursor is at the beginning of a row without prior newline,
1250         // move one row up!
1251         // This touches only the screen-update. Otherwise we would may have
1252         // an empty row on the screen
1253         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1254             && !cursor.par()->isNewline(cursor.pos() - 1))
1255         {
1256                 cursorLeft(bv());
1257         }
1258
1259         while (!next_par->empty() && next_par->isNewline(0))
1260                 next_par->erase(0);
1261
1262         updateCounters();
1263         redoParagraph(cursor.par());
1264         redoParagraph(next_par);
1265
1266         // This check is necessary. Otherwise the new empty paragraph will
1267         // be deleted automatically. And it is more friendly for the user!
1268         if (cursor.pos() || isempty)
1269                 setCursor(next_par, 0);
1270         else
1271                 setCursor(cursor.par(), 0);
1272 }
1273
1274
1275 // convenience function
1276 void LyXText::redoParagraph()
1277 {
1278         clearSelection();
1279         redoParagraph(cursor.par());
1280         setCursorIntern(cursor.par(), cursor.pos());
1281 }
1282
1283
1284 // insert a character, moves all the following breaks in the
1285 // same Paragraph one to the right and make a rebreak
1286 void LyXText::insertChar(char c)
1287 {
1288         recordUndo(bv(), Undo::INSERT, cursor.par());
1289
1290         // When the free-spacing option is set for the current layout,
1291         // disable the double-space checking
1292
1293         bool const freeSpacing = cursor.par()->layout()->free_spacing ||
1294                 cursor.par()->isFreeSpacing();
1295
1296         if (lyxrc.auto_number) {
1297                 static string const number_operators = "+-/*";
1298                 static string const number_unary_operators = "+-";
1299                 static string const number_seperators = ".,:";
1300
1301                 if (current_font.number() == LyXFont::ON) {
1302                         if (!IsDigit(c) && !contains(number_operators, c) &&
1303                             !(contains(number_seperators, c) &&
1304                               cursor.pos() >= 1 &&
1305                               cursor.pos() < cursor.par()->size() &&
1306                               getFont(cursor.par(), cursor.pos()).number() == LyXFont::ON &&
1307                               getFont(cursor.par(), cursor.pos() - 1).number() == LyXFont::ON)
1308                            )
1309                                 number(bv()); // Set current_font.number to OFF
1310                 } else if (IsDigit(c) &&
1311                            real_current_font.isVisibleRightToLeft()) {
1312                         number(bv()); // Set current_font.number to ON
1313
1314                         if (cursor.pos() > 0) {
1315                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1316                                 if (contains(number_unary_operators, c) &&
1317                                     (cursor.pos() == 1 ||
1318                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1319                                      cursor.par()->isNewline(cursor.pos() - 2))
1320                                   ) {
1321                                         setCharFont(
1322                                                     cursor.par(),
1323                                                     cursor.pos() - 1,
1324                                                     current_font);
1325                                 } else if (contains(number_seperators, c) &&
1326                                            cursor.pos() >= 2 &&
1327                                            getFont(
1328                                                    cursor.par(),
1329                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1330                                         setCharFont(
1331                                                     cursor.par(),
1332                                                     cursor.pos() - 1,
1333                                                     current_font);
1334                                 }
1335                         }
1336                 }
1337         }
1338
1339
1340         // First check, if there will be two blanks together or a blank at
1341         // the beginning of a paragraph.
1342         // I decided to handle blanks like normal characters, the main
1343         // difference are the special checks when calculating the row.fill
1344         // (blank does not count at the end of a row) and the check here
1345
1346         // The bug is triggered when we type in a description environment:
1347         // The current_font is not changed when we go from label to main text
1348         // and it should (along with realtmpfont) when we type the space.
1349         // CHECK There is a bug here! (Asger)
1350
1351         // store the current font.  This is because of the use of cursor
1352         // movements. The moving cursor would refresh the current font
1353         LyXFont realtmpfont = real_current_font;
1354         LyXFont rawtmpfont = current_font;
1355
1356         if (!freeSpacing && IsLineSeparatorChar(c)) {
1357                 if ((cursor.pos() > 0
1358                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1359                     || (cursor.pos() > 0
1360                         && cursor.par()->isNewline(cursor.pos() - 1))
1361                     || (cursor.pos() == 0)) {
1362                         static bool sent_space_message = false;
1363                         if (!sent_space_message) {
1364                                 if (cursor.pos() == 0)
1365                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1366                                 else
1367                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1368                                 sent_space_message = true;
1369                         }
1370                         charInserted();
1371                         return;
1372                 }
1373         }
1374
1375         // Here case LyXText::InsertInset already inserted the character
1376         if (c != Paragraph::META_INSET)
1377                 cursor.par()->insertChar(cursor.pos(), c);
1378
1379         setCharFont(cursor.par(), cursor.pos(), rawtmpfont);
1380
1381         current_font = rawtmpfont;
1382         real_current_font = realtmpfont;
1383         redoParagraph(cursor.par());
1384         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1385
1386         charInserted();
1387 }
1388
1389
1390 void LyXText::charInserted()
1391 {
1392         // Here we could call finishUndo for every 20 characters inserted.
1393         // This is from my experience how emacs does it. (Lgb)
1394         static unsigned int counter;
1395         if (counter < 20) {
1396                 ++counter;
1397         } else {
1398                 finishUndo();
1399                 counter = 0;
1400         }
1401 }
1402
1403
1404 void LyXText::prepareToPrint(ParagraphList::iterator pit,
1405            RowList::iterator const rit) const
1406 {
1407         double w = rit->fill();
1408         double fill_hfill = 0;
1409         double fill_label_hfill = 0;
1410         double fill_separator = 0;
1411         double x = 0;
1412
1413         bool const is_rtl =
1414                 pit->isRightToLeftPar(bv()->buffer()->params);
1415         if (is_rtl)
1416                 x = workWidth() > 0 ? rightMargin(pit, *bv()->buffer(), *rit) : 0;
1417         else
1418                 x = workWidth() > 0 ? leftMargin(pit, *rit) : 0;
1419
1420         // is there a manual margin with a manual label
1421         LyXLayout_ptr const & layout = pit->layout();
1422
1423         if (layout->margintype == MARGIN_MANUAL
1424             && layout->labeltype == LABEL_MANUAL) {
1425                 /// We might have real hfills in the label part
1426                 int nlh = numberOfLabelHfills(*pit, rit);
1427
1428                 // A manual label par (e.g. List) has an auto-hfill
1429                 // between the label text and the body of the
1430                 // paragraph too.
1431                 // But we don't want to do this auto hfill if the par
1432                 // is empty.
1433                 if (!pit->empty())
1434                         ++nlh;
1435
1436                 if (nlh && !pit->getLabelWidthString().empty()) {
1437                         fill_label_hfill = labelFill(pit, *rit) / double(nlh);
1438                 }
1439         }
1440
1441         // are there any hfills in the row?
1442         int const nh = numberOfHfills(*pit, rit);
1443
1444         if (nh) {
1445                 if (w > 0)
1446                         fill_hfill = w / nh;
1447         // we don't have to look at the alignment if it is ALIGN_LEFT and
1448         // if the row is already larger then the permitted width as then
1449         // we force the LEFT_ALIGN'edness!
1450         } else if (int(rit->width()) < workWidth()) {
1451                 // is it block, flushleft or flushright?
1452                 // set x how you need it
1453                 int align;
1454                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1455                         align = layout->align;
1456                 } else {
1457                         align = pit->params().align();
1458                 }
1459                 InsetOld * inset = 0;
1460                 // ERT insets should always be LEFT ALIGNED on screen
1461                 inset = pit->inInset();
1462                 if (inset && inset->owner() &&
1463                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1464                 {
1465                         align = LYX_ALIGN_LEFT;
1466                 }
1467
1468                 switch (align) {
1469             case LYX_ALIGN_BLOCK:
1470                 {
1471                         int const ns = numberOfSeparators(*pit, rit);
1472                         RowList::iterator next_row = boost::next(rit);
1473                         if (ns
1474                                 && next_row != pit->rows.end()
1475                                 && !pit->isNewline(next_row->pos() - 1)
1476                                 ) {
1477                                         fill_separator = w / ns;
1478                         } else if (is_rtl) {
1479                                 x += w;
1480                         }
1481                         break;
1482             }
1483             case LYX_ALIGN_RIGHT:
1484                         x += w;
1485                         break;
1486             case LYX_ALIGN_CENTER:
1487                         x += w / 2;
1488                         break;
1489                 }
1490         }
1491
1492         computeBidiTables(pit, *bv()->buffer(), rit);
1493         if (is_rtl) {
1494                 pos_type body_pos = pit->beginningOfBody();
1495                 pos_type last = lastPos(*pit, rit);
1496
1497                 if (body_pos > 0 &&
1498                                 (body_pos - 1 > last ||
1499                                  !pit->isLineSeparator(body_pos - 1))) {
1500                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1501                         if (body_pos - 1 <= last)
1502                                 x += fill_label_hfill;
1503                 }
1504         }
1505
1506         rit->fill_hfill(fill_hfill);
1507         rit->fill_label_hfill(fill_label_hfill);
1508         rit->fill_separator(fill_separator);
1509         rit->x(x);
1510 }
1511
1512
1513 // important for the screen
1514
1515
1516 // the cursor set functions have a special mechanism. When they
1517 // realize, that you left an empty paragraph, they will delete it.
1518 // They also delete the corresponding row
1519
1520 void LyXText::cursorRightOneWord()
1521 {
1522         ::cursorRightOneWord(cursor, ownerParagraphs());
1523         setCursor(cursor.par(), cursor.pos());
1524 }
1525
1526
1527 // Skip initial whitespace at end of word and move cursor to *start*
1528 // of prior word, not to end of next prior word.
1529 void LyXText::cursorLeftOneWord()
1530 {
1531         LyXCursor tmpcursor = cursor;
1532         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
1533         setCursor(tmpcursor.par(), tmpcursor.pos());
1534 }
1535
1536
1537 void LyXText::selectWord(word_location loc)
1538 {
1539         LyXCursor from = cursor;
1540         LyXCursor to;
1541         ::getWord(from, to, loc, ownerParagraphs());
1542         if (cursor != from)
1543                 setCursor(from.par(), from.pos());
1544         if (to == from)
1545                 return;
1546         selection.cursor = cursor;
1547         setCursor(to.par(), to.pos());
1548         setSelection();
1549 }
1550
1551
1552 // Select the word currently under the cursor when no
1553 // selection is currently set
1554 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1555 {
1556         if (!selection.set()) {
1557                 selectWord(loc);
1558                 return selection.set();
1559         }
1560         return false;
1561 }
1562
1563
1564 void LyXText::acceptChange()
1565 {
1566         if (!selection.set() && cursor.par()->size())
1567                 return;
1568
1569         if (selection.start.par() == selection.end.par()) {
1570                 LyXCursor & startc = selection.start;
1571                 LyXCursor & endc = selection.end;
1572                 recordUndo(bv(), Undo::INSERT, startc.par());
1573                 startc.par()->acceptChange(startc.pos(), endc.pos());
1574                 finishUndo();
1575                 clearSelection();
1576                 redoParagraph(startc.par());
1577                 setCursorIntern(startc.par(), 0);
1578         }
1579 #warning handle multi par selection
1580 }
1581
1582
1583 void LyXText::rejectChange()
1584 {
1585         if (!selection.set() && cursor.par()->size())
1586                 return;
1587
1588         if (selection.start.par() == selection.end.par()) {
1589                 LyXCursor & startc = selection.start;
1590                 LyXCursor & endc = selection.end;
1591                 recordUndo(bv(), Undo::INSERT, startc.par());
1592                 startc.par()->rejectChange(startc.pos(), endc.pos());
1593                 finishUndo();
1594                 clearSelection();
1595                 redoParagraph(startc.par());
1596                 setCursorIntern(startc.par(), 0);
1597         }
1598 #warning handle multi par selection
1599 }
1600
1601
1602 // This function is only used by the spellchecker for NextWord().
1603 // It doesn't handle LYX_ACCENTs and probably never will.
1604 WordLangTuple const
1605 LyXText::selectNextWordToSpellcheck(float & value)
1606 {
1607         if (the_locking_inset) {
1608                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1609                 if (!word.word().empty()) {
1610                         value += float(cursor.y());
1611                         value /= float(height);
1612                         return word;
1613                 }
1614                 // we have to go on checking so move cursor to the next char
1615                 if (cursor.pos() == cursor.par()->size()) {
1616                         if (boost::next(cursor.par()) == ownerParagraphs().end())
1617                                 return word;
1618                         cursor.par(boost::next(cursor.par()));
1619                         cursor.pos(0);
1620                 } else
1621                         cursor.pos(cursor.pos() + 1);
1622         }
1623         ParagraphList::iterator tmppit = cursor.par();
1624
1625         // If this is not the very first word, skip rest of
1626         // current word because we are probably in the middle
1627         // of a word if there is text here.
1628         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
1629                 while (cursor.pos() < cursor.par()->size()
1630                        && cursor.par()->isLetter(cursor.pos()))
1631                         cursor.pos(cursor.pos() + 1);
1632         }
1633
1634         // Now, skip until we have real text (will jump paragraphs)
1635         while (true) {
1636                 ParagraphList::iterator cpit = cursor.par();
1637                 pos_type const cpos(cursor.pos());
1638
1639                 if (cpos == cpit->size()) {
1640                         if (boost::next(cpit) != ownerParagraphs().end()) {
1641                                 cursor.par(boost::next(cpit));
1642                                 cursor.pos(0);
1643                                 continue;
1644                         }
1645                         break;
1646                 }
1647
1648                 bool const is_good_inset = cpit->isInset(cpos)
1649                         && cpit->getInset(cpos)->allowSpellcheck();
1650
1651                 if (!isDeletedText(*cpit, cpos)
1652                     && (is_good_inset || cpit->isLetter(cpos)))
1653                         break;
1654
1655                 cursor.pos(cpos + 1);
1656         }
1657
1658         // now check if we hit an inset so it has to be a inset containing text!
1659         if (cursor.pos() < cursor.par()->size() &&
1660             cursor.par()->isInset(cursor.pos())) {
1661                 // lock the inset!
1662                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1663                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
1664                 // now call us again to do the above trick
1665                 // but obviously we have to start from down below ;)
1666                 return bv()->text->selectNextWordToSpellcheck(value);
1667         }
1668
1669         // Update the value if we changed paragraphs
1670         if (cursor.par() != tmppit) {
1671                 setCursor(cursor.par(), cursor.pos());
1672                 value = float(cursor.y())/float(height);
1673         }
1674
1675         // Start the selection from here
1676         selection.cursor = cursor;
1677
1678         string lang_code = getFont(cursor.par(), cursor.pos()).language()->code();
1679         // and find the end of the word (insets like optional hyphens
1680         // and ligature break are part of a word)
1681         while (cursor.pos() < cursor.par()->size()
1682                && cursor.par()->isLetter(cursor.pos())
1683                && !isDeletedText(*cursor.par(), cursor.pos()))
1684                 cursor.pos(cursor.pos() + 1);
1685
1686         // Finally, we copy the word to a string and return it
1687         string str;
1688         if (selection.cursor.pos() < cursor.pos()) {
1689                 pos_type i;
1690                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1691                         if (!cursor.par()->isInset(i))
1692                                 str += cursor.par()->getChar(i);
1693                 }
1694         }
1695         return WordLangTuple(str, lang_code);
1696 }
1697
1698
1699 // This one is also only for the spellchecker
1700 void LyXText::selectSelectedWord()
1701 {
1702         if (the_locking_inset) {
1703                 the_locking_inset->selectSelectedWord(bv());
1704                 return;
1705         }
1706         // move cursor to the beginning
1707         setCursor(selection.cursor.par(), selection.cursor.pos());
1708
1709         // set the sel cursor
1710         selection.cursor = cursor;
1711
1712         // now find the end of the word
1713         while (cursor.pos() < cursor.par()->size()
1714                && cursor.par()->isLetter(cursor.pos()))
1715                 cursor.pos(cursor.pos() + 1);
1716
1717         setCursor(cursor.par(), cursor.pos());
1718
1719         // finally set the selection
1720         setSelection();
1721 }
1722
1723
1724 // Delete from cursor up to the end of the current or next word.
1725 void LyXText::deleteWordForward()
1726 {
1727         if (cursor.par()->empty())
1728                 cursorRight(bv());
1729         else {
1730                 LyXCursor tmpcursor = cursor;
1731                 selection.set(true); // to avoid deletion
1732                 cursorRightOneWord();
1733                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1734                 selection.cursor = cursor;
1735                 cursor = tmpcursor;
1736                 setSelection();
1737
1738                 // Great, CutSelection() gets rid of multiple spaces.
1739                 cutSelection(true, false);
1740         }
1741 }
1742
1743
1744 // Delete from cursor to start of current or prior word.
1745 void LyXText::deleteWordBackward()
1746 {
1747         if (cursor.par()->empty())
1748                 cursorLeft(bv());
1749         else {
1750                 LyXCursor tmpcursor = cursor;
1751                 selection.set(true); // to avoid deletion
1752                 cursorLeftOneWord();
1753                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1754                 selection.cursor = cursor;
1755                 cursor = tmpcursor;
1756                 setSelection();
1757                 cutSelection(true, false);
1758         }
1759 }
1760
1761
1762 // Kill to end of line.
1763 void LyXText::deleteLineForward()
1764 {
1765         if (cursor.par()->empty())
1766                 // Paragraph is empty, so we just go to the right
1767                 cursorRight(bv());
1768         else {
1769                 LyXCursor tmpcursor = cursor;
1770                 // We can't store the row over a regular setCursor
1771                 // so we set it to 0 and reset it afterwards.
1772                 selection.set(true); // to avoid deletion
1773                 cursorEnd();
1774                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1775                 selection.cursor = cursor;
1776                 cursor = tmpcursor;
1777                 setSelection();
1778                 // What is this test for ??? (JMarc)
1779                 if (!selection.set()) {
1780                         deleteWordForward();
1781                 } else {
1782                         cutSelection(true, false);
1783                 }
1784         }
1785 }
1786
1787
1788 void LyXText::changeCase(LyXText::TextCase action)
1789 {
1790         LyXCursor from;
1791         LyXCursor to;
1792
1793         if (selection.set()) {
1794                 from = selection.start;
1795                 to = selection.end;
1796         } else {
1797                 from = cursor;
1798                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1799                 setCursor(to.par(), to.pos() + 1);
1800         }
1801
1802         recordUndo(bv(), Undo::ATOMIC, from.par(), to.par());
1803
1804         pos_type pos = from.pos();
1805         ParagraphList::iterator pit = from.par();
1806
1807         while (pit != ownerParagraphs().end() &&
1808                (pos != to.pos() || pit != to.par())) {
1809                 if (pos == pit->size()) {
1810                         ++pit;
1811                         pos = 0;
1812                         continue;
1813                 }
1814                 unsigned char c = pit->getChar(pos);
1815                 if (!IsInsetChar(c)) {
1816                         switch (action) {
1817                         case text_lowercase:
1818                                 c = lowercase(c);
1819                                 break;
1820                         case text_capitalization:
1821                                 c = uppercase(c);
1822                                 action = text_lowercase;
1823                                 break;
1824                         case text_uppercase:
1825                                 c = uppercase(c);
1826                                 break;
1827                         }
1828                 }
1829 #warning changes
1830                 pit->setChar(pos, c);
1831                 ++pos;
1832         }
1833 }
1834
1835
1836 void LyXText::Delete()
1837 {
1838         // this is a very easy implementation
1839
1840         LyXCursor old_cursor = cursor;
1841         int const old_cur_par_id = old_cursor.par()->id();
1842         int const old_cur_par_prev_id =
1843                 (old_cursor.par() != ownerParagraphs().begin() ?
1844                  boost::prior(old_cursor.par())->id() : -1);
1845
1846         // just move to the right
1847         cursorRight(bv());
1848
1849         // CHECK Look at the comment here.
1850         // This check is not very good...
1851         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
1852         // and that can very well delete the par or par->previous in
1853         // old_cursor. Will a solution where we compare paragraph id's
1854         //work better?
1855         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
1856             == old_cur_par_prev_id
1857             && cursor.par()->id() != old_cur_par_id) {
1858                 // delete-empty-paragraph-mechanism has done it
1859                 return;
1860         }
1861
1862         // if you had success make a backspace
1863         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1864                 LyXCursor tmpcursor = cursor;
1865                 // to make sure undo gets the right cursor position
1866                 cursor = old_cursor;
1867                 recordUndo(bv(), Undo::DELETE, cursor.par());
1868                 cursor = tmpcursor;
1869                 backspace();
1870         }
1871 }
1872
1873
1874 void LyXText::backspace()
1875 {
1876         // Get the font that is used to calculate the baselineskip
1877         pos_type lastpos = cursor.par()->size();
1878
1879         if (cursor.pos() == 0) {
1880                 // The cursor is at the beginning of a paragraph,
1881                 // so the the backspace will collapse two paragraphs into one.
1882
1883                 // but it's not allowed unless it's new
1884                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
1885                         return;
1886
1887                 // we may paste some paragraphs
1888
1889                 // is it an empty paragraph?
1890
1891                 if (lastpos == 0
1892                      || (lastpos == 1 && cursor.par()->isSeparator(0))) {
1893                         // This is an empty paragraph and we delete it just
1894                         // by moving the cursor one step
1895                         // left and let the DeleteEmptyParagraphMechanism
1896                         // handle the actual deletion of the paragraph.
1897
1898                         if (cursor.par() != ownerParagraphs().begin()) {
1899                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
1900                                 if (cursor.par()->layout() == tmppit->layout()
1901                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
1902                                         // Inherit bottom DTD from the paragraph below.
1903                                         // (the one we are deleting)
1904                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
1905                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
1906                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
1907                                 }
1908
1909                                 cursorLeft(bv());
1910
1911                                 // the layout things can change the height of a row !
1912                                 redoParagraph();
1913                                 return;
1914                         }
1915                 }
1916
1917                 if (cursor.par() != ownerParagraphs().begin()) {
1918                         recordUndo(bv(), Undo::DELETE,
1919                                 boost::prior(cursor.par()),
1920                                 cursor.par());
1921                 }
1922
1923                 ParagraphList::iterator tmppit = cursor.par();
1924                 // We used to do cursorLeftIntern() here, but it is
1925                 // not a good idea since it triggers the auto-delete
1926                 // mechanism. So we do a cursorLeftIntern()-lite,
1927                 // without the dreaded mechanism. (JMarc)
1928                 if (cursor.par() != ownerParagraphs().begin()) {
1929                         // steps into the above paragraph.
1930                         setCursorIntern(boost::prior(cursor.par()),
1931                                         boost::prior(cursor.par())->size(),
1932                                         false);
1933                 }
1934
1935                 // Pasting is not allowed, if the paragraphs have different
1936                 // layout. I think it is a real bug of all other
1937                 // word processors to allow it. It confuses the user.
1938                 // Correction: Pasting is always allowed with standard-layout
1939                 LyXTextClass const & tclass =
1940                         bv()->buffer()->params.getLyXTextClass();
1941
1942                 if (cursor.par() != tmppit
1943                     && (cursor.par()->layout() == tmppit->layout()
1944                         || tmppit->layout() == tclass.defaultLayout())
1945                     && cursor.par()->getAlign() == tmppit->getAlign()) {
1946                         mergeParagraph(bv()->buffer()->params,
1947                                 bv()->buffer()->paragraphs, cursor.par());
1948
1949                         if (cursor.pos() && cursor.par()->isSeparator(cursor.pos() - 1))
1950                                 cursor.pos(cursor.pos() - 1);
1951
1952                         // the row may have changed, block, hfills etc.
1953                         updateCounters();
1954                         setCursor(cursor.par(), cursor.pos(), false);
1955                 }
1956         } else {
1957                 // this is the code for a normal backspace, not pasting
1958                 // any paragraphs
1959                 recordUndo(bv(), Undo::DELETE, cursor.par());
1960                 // We used to do cursorLeftIntern() here, but it is
1961                 // not a good idea since it triggers the auto-delete
1962                 // mechanism. So we do a cursorLeftIntern()-lite,
1963                 // without the dreaded mechanism. (JMarc)
1964                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1965                                 false, cursor.boundary());
1966                 cursor.par()->erase(cursor.pos());
1967         }
1968
1969         lastpos = cursor.par()->size();
1970         if (cursor.pos() == lastpos)
1971                 setCurrentFont();
1972
1973         redoParagraph();
1974         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1975 }
1976
1977
1978 RowList::iterator LyXText::cursorRow() const
1979 {
1980         return getRow(cursor.par(), cursor.pos());
1981 }
1982
1983
1984 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
1985 {
1986         return getRow(cur.par(), cur.pos());
1987 }
1988
1989
1990 RowList::iterator
1991 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
1992 {
1993         RowList::iterator rit = boost::prior(pit->rows.end());
1994         RowList::iterator const begin = pit->rows.begin();
1995
1996         while (rit != begin && rit->pos() > pos)
1997                 --rit;
1998
1999         return rit;
2000 }
2001
2002
2003 // returns pointer to some fancy row 'below' specified row
2004 RowList::iterator LyXText::cursorIRow() const
2005 {
2006         return getRow(cursor.par(), cursor.pos());
2007 }
2008
2009
2010 RowList::iterator LyXText::getRowNearY(int y,
2011         ParagraphList::iterator & pit) const
2012 {
2013         //lyxerr << "getRowNearY: y " << y << endl;
2014
2015         pit = boost::prior(ownerParagraphs().end());
2016
2017         RowList::iterator rit = lastRow();
2018         RowList::iterator rbegin = firstRow();
2019
2020         while (rit != rbegin && static_cast<int>(rit->y()) > y)
2021                 previousRow(pit, rit);
2022
2023         return rit;
2024 }
2025
2026
2027 int LyXText::getDepth() const
2028 {
2029         return cursor.par()->getDepth();
2030 }
2031
2032
2033 RowList::iterator LyXText::firstRow() const
2034 {
2035         return ownerParagraphs().front().rows.begin();
2036 }
2037
2038
2039 RowList::iterator LyXText::lastRow() const
2040 {
2041         return boost::prior(endRow());
2042 }
2043
2044
2045 RowList::iterator LyXText::endRow() const
2046 {
2047         return ownerParagraphs().back().rows.end();
2048 }
2049
2050
2051 void LyXText::nextRow(ParagraphList::iterator & pit,
2052         RowList::iterator & rit) const
2053 {
2054         ++rit;
2055         if (rit == pit->rows.end()) {
2056                 ++pit;
2057                 if (pit == ownerParagraphs().end())
2058                         --pit;
2059                 else
2060                         rit = pit->rows.begin();
2061         }
2062 }
2063
2064
2065 void LyXText::previousRow(ParagraphList::iterator & pit,
2066         RowList::iterator & rit) const
2067 {
2068         if (rit != pit->rows.begin())
2069                 --rit;
2070         else {
2071                 Assert(pit != ownerParagraphs().begin());
2072                 --pit;
2073                 rit = boost::prior(pit->rows.end());
2074         }
2075 }
2076
2077
2078 bool LyXText::noRows() const
2079 {
2080         return ownerParagraphs().begin()->rows.empty();
2081 }