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