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