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