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