]> git.lyx.org Git - lyx.git/blob - src/text.C
remove spurious call to repaint()
[lyx.git] / src / text.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "paragraph.h"
16 #include "gettext.h"
17 #include "bufferparams.h"
18 #include "buffer.h"
19 #include "debug.h"
20 #include "intl.h"
21 #include "lyxrc.h"
22 #include "encoding.h"
23 #include "frontends/LyXView.h"
24 #include "frontends/Painter.h"
25 #include "frontends/font_metrics.h"
26 #include "frontends/screen.h"
27 #include "frontends/WorkArea.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "text_funcs.h"
34 #include "WordLangTuple.h"
35 #include "paragraph_funcs.h"
36 #include "rowpainter.h"
37 #include "lyxrow_funcs.h"
38 #include "metricsinfo.h"
39
40 #include "insets/insettext.h"
41
42 #include "support/textutils.h"
43 #include "support/LAssert.h"
44 #include "support/lstrings.h"
45
46 #include <algorithm>
47
48 using namespace lyx::support;
49
50 using std::max;
51 using std::min;
52 using std::endl;
53 using std::pair;
54
55 using lyx::pos_type;
56 using lyx::word_location;
57
58 using namespace bv_funcs;
59
60 /// top, right, bottom pixel margin
61 extern int const PAPER_MARGIN = 20;
62 /// margin for changebar
63 extern int const CHANGEBAR_MARGIN = 10;
64 /// left margin
65 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
66
67 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
68
69
70 BufferView * LyXText::bv()
71 {
72         Assert(bv_owner != 0);
73         return bv_owner;
74 }
75
76
77 BufferView * LyXText::bv() const
78 {
79         Assert(bv_owner != 0);
80         return bv_owner;
81 }
82
83
84 void LyXText::updateRowPositions()
85 {
86         RowList::iterator rit = rows().begin();
87         RowList::iterator rend = rows().end();
88         for (int y = 0; rit != rend ; ++rit) {
89                 rit->y(y);
90                 y += rit->height();
91         }
92 }
93
94
95 int LyXText::top_y() const
96 {
97         if (anchor_row_ == rowlist_.end())
98                 return 0;
99
100         return anchor_row_->y() + anchor_row_offset_;
101 }
102
103
104 void LyXText::top_y(int newy)
105 {
106         if (rows().empty())
107                 return;
108
109         if (isInInset()) {
110                 anchor_row_ = rows().begin();
111                 anchor_row_offset_ = newy;
112                 return;
113         }
114
115         lyxerr[Debug::GUI] << "setting top y = " << newy << endl;
116
117         int y = newy;
118         RowList::iterator rit = getRowNearY(y);
119
120         if (rit == anchor_row_ && anchor_row_offset_ == newy - y) {
121                 lyxerr[Debug::GUI] << "top_y to same value, skipping update" << endl;
122                 return;
123         }
124
125         anchor_row_ = rit;
126         anchor_row_offset_ = newy - y;
127         lyxerr[Debug::GUI] << "changing reference to row: " << &*anchor_row_
128                << " offset: " << anchor_row_offset_ << endl;
129         postPaint();
130 }
131
132
133 void LyXText::anchor_row(RowList::iterator rit)
134 {
135         int old_y = top_y();
136         anchor_row_offset_ = 0;
137         anchor_row_ = rit;
138         anchor_row_offset_ = old_y - top_y();
139         lyxerr[Debug::GUI] << "anchor_row(): changing reference to row: "
140                            << &*anchor_row_ << " offset: "
141                            << anchor_row_offset_ << endl;
142 }
143
144
145 int LyXText::workWidth() const
146 {
147         if (inset_owner) {
148                 // FIXME: pass (const ?) ref
149                 return inset_owner->textWidth(bv());
150         }
151         return bv()->workWidth();
152 }
153
154
155 int LyXText::workWidth(Inset const * inset) const
156 {
157         ParagraphList::iterator par = std::find(ownerParagraphs().begin(),
158                                                 ownerParagraphs().end(),
159                                                 *inset->parOwner());
160         if (par == ownerParagraphs().end()) {
161                 lyxerr[Debug::GUI] << "LyXText::workWidth: unexpected\n";
162                 return -1;
163         }
164
165         pos_type pos = par->getPositionOfInset(inset);
166         Assert(pos != -1);
167
168         LyXLayout_ptr const & layout = par->layout();
169
170         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
171                 // Optimization here: in most cases, the real row is
172                 // not needed, but only the par/pos values. So we just
173                 // construct a dummy row for leftMargin. (JMarc)
174                 Row dummyrow;
175                 dummyrow.par(par);
176                 dummyrow.pos(pos);
177                 return workWidth() - leftMargin(dummyrow);
178         } else {
179                 int dummy_y;
180                 RowList::iterator row = getRow(par, pos, dummy_y);
181                 RowList::iterator frow = row;
182                 RowList::iterator beg = rowlist_.begin();
183
184                 while (frow != beg && frow->par() == boost::prior(frow)->par())
185                         --frow;
186
187                 // FIXME: I don't understand this code - jbl
188
189                 unsigned int maxw = 0;
190                 while (!isParEnd(*this, frow)) {
191                         if ((frow != row) && (maxw < frow->width()))
192                                 maxw = frow->width();
193                         ++frow;
194                 }
195                 if (maxw)
196                         return maxw;
197
198         }
199         return workWidth();
200 }
201
202
203 int LyXText::getRealCursorX() const
204 {
205         int x = cursor.x();
206         if (the_locking_inset && (the_locking_inset->getLyXText(bv())!= this))
207                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
208         return x;
209 }
210
211
212 #warning FIXME  This function seems to belong outside of LyxText.
213 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
214                                      pos_type pos) const
215 {
216         if (!Encodings::is_arabic(c))
217                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
218                         return c + (0xb0 - '0');
219                 else
220                         return c;
221
222         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
223         unsigned char next_char = ' ';
224
225         pos_type const par_size = par.size();
226
227         for (pos_type i = pos + 1; i < par_size; ++i) {
228                 unsigned char const par_char = par.getChar(i);
229                 if (!Encodings::IsComposeChar_arabic(par_char)) {
230                         next_char = par_char;
231                         break;
232                 }
233         }
234
235         if (Encodings::is_arabic(next_char)) {
236                 if (Encodings::is_arabic(prev_char) &&
237                         !Encodings::is_arabic_special(prev_char))
238                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
239                 else
240                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
241         } else {
242                 if (Encodings::is_arabic(prev_char) &&
243                         !Encodings::is_arabic_special(prev_char))
244                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
245                 else
246                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
247         }
248 }
249
250 // This is the comments that some of the warnings below refers to.
251 // There are some issues in this file and I don't think they are
252 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
253 // this is a problem that has been here almost from day one and that a
254 // larger userbase with differenct access patters triggers the bad
255 // behaviour. (segfaults.) What I think happen is: In several places
256 // we store the paragraph in the current cursor and then moves the
257 // cursor. This movement of the cursor will delete paragraph at the
258 // old position if it is now empty. This will make the temporary
259 // pointer to the old cursor paragraph invalid and dangerous to use.
260 // And is some cases this will trigger a segfault. I have marked some
261 // of the cases where this happens with a warning, but I am sure there
262 // are others in this file and in text2.C. There is also a note in
263 // Delete() that you should read. In Delete I store the paragraph->id
264 // instead of a pointer to the paragraph. I am pretty sure this faulty
265 // use of temporary pointers to paragraphs that might have gotten
266 // invalidated (through a cursor movement) before they are used, are
267 // the cause of the strange crashes we get reported often.
268 //
269 // It is very tiresom to change this code, especially when it is as
270 // hard to read as it is. Help to fix all the cases where this is done
271 // would be greately appreciated.
272 //
273 // Lgb
274
275 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
276 {
277         if (pos >= pit->size())
278                 return 0;
279
280         char const c = pit->getChar(pos);
281         return singleWidth(pit, pos, c);
282 }
283
284
285 int LyXText::singleWidth(ParagraphList::iterator pit,
286                          pos_type pos, char c) const
287 {
288         if (pos >= pit->size())
289                 return 0;
290
291         LyXFont const font = getFont(bv()->buffer(), pit, pos);
292
293         // The most common case is handled first (Asger)
294         if (IsPrintable(c)) {
295                 if (font.language()->RightToLeft()) {
296                         if (font.language()->lang() == "arabic" &&
297                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
298                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)) {
299                                 if (Encodings::IsComposeChar_arabic(c))
300                                         return 0;
301                                 else
302                                         c = transformChar(c, *pit, pos);
303                         } else if (font.language()->lang() == "hebrew" &&
304                                  Encodings::IsComposeChar_hebrew(c))
305                                 return 0;
306                 }
307                 return font_metrics::width(c, font);
308
309         }
310
311         if (c == Paragraph::META_INSET) {
312                 Inset * tmpinset = pit->getInset(pos);
313                 if (tmpinset) {
314                         if (tmpinset->lyxCode() == Inset::HFILL_CODE) {
315                                 // Because of the representation as vertical lines
316                                 return 3;
317                         }
318 #if 1
319 #warning inset->update FIXME
320                         // this IS needed otherwise on initialitation we don't get the fill
321                         // of the row right (ONLY on initialization if we read a file!)
322                         // should be changed! (Jug 20011204)
323                         //tmpinset->update(bv());
324                         Dimension dim;
325                         MetricsInfo mi;
326                         mi.base.bv = bv();
327                         mi.base.font = font;
328                         tmpinset->metrics(mi, dim);
329 #endif
330                         //return tmpinset->width(bv(), font);
331                         return dim.wid;
332                 }
333                 return 0;
334         }
335
336         if (IsSeparatorChar(c))
337                 c = ' ';
338         return font_metrics::width(c, font);
339 }
340
341
342 lyx::pos_type LyXText::log2vis(lyx::pos_type pos) const
343 {
344         if (bidi_start == -1)
345                 return pos;
346         else
347                 return log2vis_list[pos - bidi_start];
348 }
349
350
351 lyx::pos_type LyXText::vis2log(lyx::pos_type pos) const
352 {
353         if (bidi_start == -1)
354                 return pos;
355         else
356                 return vis2log_list[pos - bidi_start];
357 }
358
359
360 lyx::pos_type LyXText::bidi_level(lyx::pos_type pos) const
361 {
362         if (bidi_start == -1)
363                 return 0;
364         else
365                 return bidi_levels[pos - bidi_start];
366 }
367
368
369 bool LyXText::bidi_InRange(lyx::pos_type pos) const
370 {
371         return bidi_start == -1 ||
372                 (bidi_start <= pos && pos <= bidi_end);
373 }
374
375
376 void LyXText::computeBidiTables(Buffer const * buf,
377                                 RowList::iterator row) const
378 {
379         bidi_same_direction = true;
380         if (!lyxrc.rtl_support) {
381                 bidi_start = -1;
382                 return;
383         }
384
385         ParagraphList::iterator row_par = row->par();
386
387         Inset * inset = row_par->inInset();
388         if (inset && inset->owner() &&
389             inset->owner()->lyxCode() == Inset::ERT_CODE) {
390                 bidi_start = -1;
391                 return;
392         }
393
394         bidi_start = row->pos();
395         bidi_end = lastPrintablePos(*this, row);
396
397         if (bidi_start > bidi_end) {
398                 bidi_start = -1;
399                 return;
400         }
401
402         if (bidi_end + 2 - bidi_start >
403             static_cast<pos_type>(log2vis_list.size())) {
404                 pos_type new_size =
405                         (bidi_end + 2 - bidi_start < 500) ?
406                         500 : 2 * (bidi_end + 2 - bidi_start);
407                 log2vis_list.resize(new_size);
408                 vis2log_list.resize(new_size);
409                 bidi_levels.resize(new_size);
410         }
411
412         vis2log_list[bidi_end + 1 - bidi_start] = -1;
413         log2vis_list[bidi_end + 1 - bidi_start] = -1;
414
415         pos_type stack[2];
416         bool const rtl_par =
417                 row_par->isRightToLeftPar(buf->params);
418         int level = 0;
419         bool rtl = false;
420         bool rtl0 = false;
421         pos_type const body_pos = row_par->beginningOfBody();
422
423         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
424                 bool is_space = row_par->isLineSeparator(lpos);
425                 pos_type const pos =
426                         (is_space && lpos + 1 <= bidi_end &&
427                          !row_par->isLineSeparator(lpos + 1) &&
428                          !row_par->isNewline(lpos + 1))
429                         ? lpos + 1 : lpos;
430                 LyXFont font = row_par->getFontSettings(buf->params, pos);
431                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
432                     font.number() == LyXFont::ON &&
433                     row_par->getFontSettings(buf->params, lpos - 1).number()
434                     == LyXFont::ON) {
435                         font = row_par->getFontSettings(buf->params, lpos);
436                         is_space = false;
437                 }
438
439
440                 bool new_rtl = font.isVisibleRightToLeft();
441                 bool new_rtl0 = font.isRightToLeft();
442                 int new_level;
443
444                 if (lpos == body_pos - 1
445                     && row->pos() < body_pos - 1
446                     && is_space) {
447                         new_level = (rtl_par) ? 1 : 0;
448                         new_rtl = new_rtl0 = rtl_par;
449                 } else if (new_rtl0)
450                         new_level = (new_rtl) ? 1 : 2;
451                 else
452                         new_level = (rtl_par) ? 2 : 0;
453
454                 if (is_space && new_level >= level) {
455                         new_level = level;
456                         new_rtl = rtl;
457                         new_rtl0 = rtl0;
458                 }
459
460                 int new_level2 = new_level;
461
462                 if (level == new_level && rtl0 != new_rtl0) {
463                         --new_level2;
464                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
465                 } else if (level < new_level) {
466                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
467                         if (new_level > rtl_par)
468                                 bidi_same_direction = false;
469                 } else
470                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
471                 rtl = new_rtl;
472                 rtl0 = new_rtl0;
473                 bidi_levels[lpos - bidi_start] = new_level;
474
475                 while (level > new_level2) {
476                         pos_type old_lpos = stack[--level];
477                         int delta = lpos - old_lpos - 1;
478                         if (level % 2)
479                                 delta = -delta;
480                         log2vis_list[lpos - bidi_start] += delta;
481                         log2vis_list[old_lpos - bidi_start] += delta;
482                 }
483                 while (level < new_level)
484                         stack[level++] = lpos;
485         }
486
487         while (level > 0) {
488                 pos_type const old_lpos = stack[--level];
489                 int delta = bidi_end - old_lpos;
490                 if (level % 2)
491                         delta = -delta;
492                 log2vis_list[old_lpos - bidi_start] += delta;
493         }
494
495         pos_type vpos = bidi_start - 1;
496         for (pos_type lpos = bidi_start;
497              lpos <= bidi_end; ++lpos) {
498                 vpos += log2vis_list[lpos - bidi_start];
499                 vis2log_list[vpos - bidi_start] = lpos;
500                 log2vis_list[lpos - bidi_start] = vpos;
501         }
502 }
503
504
505 // This method requires a previous call to ComputeBidiTables()
506 bool LyXText::isBoundary(Buffer const * buf, Paragraph const & par,
507                          pos_type pos) const
508 {
509         if (!lyxrc.rtl_support || pos == 0)
510                 return false;
511
512         if (!bidi_InRange(pos - 1)) {
513                 /// This can happen if pos is the first char of a row.
514                 /// Returning false in this case is incorrect!
515                 return false;
516         }
517
518         bool const rtl = bidi_level(pos - 1) % 2;
519         bool const rtl2 = bidi_InRange(pos)
520                 ? bidi_level(pos) % 2
521                 : par.isRightToLeftPar(buf->params);
522         return rtl != rtl2;
523 }
524
525
526 bool LyXText::isBoundary(Buffer const * buf, Paragraph const & par,
527                          pos_type pos, LyXFont const & font) const
528 {
529         if (!lyxrc.rtl_support)
530                 return false;    // This is just for speedup
531
532         bool const rtl = font.isVisibleRightToLeft();
533         bool const rtl2 = bidi_InRange(pos)
534                 ? bidi_level(pos) % 2
535                 : par.isRightToLeftPar(buf->params);
536         return rtl != rtl2;
537 }
538
539
540 int LyXText::leftMargin(Row const & row) const
541 {
542         Inset * ins;
543
544         if (row.pos() < row.par()->size())
545                 if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
546                     (ins = row.par()->getInset(row.pos())) &&
547                     (ins->needFullRow() || ins->display()))
548                         return LEFT_MARGIN;
549
550         LyXTextClass const & tclass =
551                 bv()->buffer()->params.getLyXTextClass();
552         LyXLayout_ptr const & layout = row.par()->layout();
553
554         string parindent = layout->parindent;
555
556         int x = LEFT_MARGIN;
557
558         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
559
560         // this is the way, LyX handles the LaTeX-Environments.
561         // I have had this idea very late, so it seems to be a
562         // later added hack and this is true
563         if (!row.par()->getDepth()) {
564                 if (row.par()->layout() == tclass.defaultLayout()) {
565                         // find the previous same level paragraph
566                         if (row.par() != ownerParagraphs().begin()) {
567                                 ParagraphList::iterator newpit =
568                                         depthHook(row.par(), ownerParagraphs(),
569                                                   row.par()->getDepth());
570                                 if (newpit == row.par() &&
571                                     newpit->layout()->nextnoindent)
572                                         parindent.erase();
573                         }
574                 }
575         } else {
576                 // find the next level paragraph
577
578                 ParagraphList::iterator newpar = outerHook(row.par(),
579                                                            ownerParagraphs());
580
581                 // make a corresponding row. Needed to call leftMargin()
582
583                 // check wether it is a sufficent paragraph
584                 if (newpar != ownerParagraphs().end() &&
585                     newpar->layout()->isEnvironment()) {
586                         Row dummyrow;
587                         dummyrow.par(newpar);
588                         dummyrow.pos(newpar->size());
589                         x = leftMargin(dummyrow);
590                 }
591
592                 if (newpar != ownerParagraphs().end() &&
593                     row.par()->layout() == tclass.defaultLayout()) {
594                         if (newpar->params().noindent())
595                                 parindent.erase();
596                         else {
597                                 parindent = newpar->layout()->parindent;
598                         }
599
600                 }
601         }
602
603         LyXFont const labelfont = getLabelFont(bv()->buffer(), row.par());
604         switch (layout->margintype) {
605         case MARGIN_DYNAMIC:
606                 if (!layout->leftmargin.empty()) {
607                         x += font_metrics::signedWidth(layout->leftmargin,
608                                                   tclass.defaultfont());
609                 }
610                 if (!row.par()->getLabelstring().empty()) {
611                         x += font_metrics::signedWidth(layout->labelindent,
612                                                   labelfont);
613                         x += font_metrics::width(row.par()->getLabelstring(),
614                                             labelfont);
615                         x += font_metrics::width(layout->labelsep, labelfont);
616                 }
617                 break;
618         case MARGIN_MANUAL:
619                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
620                 // The width of an empty par, even with manual label, should be 0
621                 if (!row.par()->empty() && row.pos() >= row.par()->beginningOfBody()) {
622                         if (!row.par()->getLabelWidthString().empty()) {
623                                 x += font_metrics::width(row.par()->getLabelWidthString(),
624                                                labelfont);
625                                 x += font_metrics::width(layout->labelsep, labelfont);
626                         }
627                 }
628                 break;
629         case MARGIN_STATIC:
630                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
631                         / (row.par()->getDepth() + 4);
632                 break;
633         case MARGIN_FIRST_DYNAMIC:
634                 if (layout->labeltype == LABEL_MANUAL) {
635                         if (row.pos() >= row.par()->beginningOfBody()) {
636                                 x += font_metrics::signedWidth(layout->leftmargin,
637                                                           labelfont);
638                         } else {
639                                 x += font_metrics::signedWidth(layout->labelindent,
640                                                           labelfont);
641                         }
642                 } else if (row.pos()
643                            // Special case to fix problems with
644                            // theorems (JMarc)
645                            || (layout->labeltype == LABEL_STATIC
646                                && layout->latextype == LATEX_ENVIRONMENT
647                                && !isFirstInSequence(row.par(), ownerParagraphs()))) {
648                         x += font_metrics::signedWidth(layout->leftmargin,
649                                                   labelfont);
650                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
651                            && layout->labeltype != LABEL_BIBLIO
652                            && layout->labeltype !=
653                            LABEL_CENTERED_TOP_ENVIRONMENT) {
654                         x += font_metrics::signedWidth(layout->labelindent,
655                                                   labelfont);
656                         x += font_metrics::width(layout->labelsep, labelfont);
657                         x += font_metrics::width(row.par()->getLabelstring(),
658                                             labelfont);
659                 }
660                 break;
661
662         case MARGIN_RIGHT_ADDRESS_BOX:
663         {
664                 // ok, a terrible hack. The left margin depends on the widest
665                 // row in this paragraph. Do not care about footnotes, they
666                 // are *NOT* allowed in the LaTeX realisation of this layout.
667
668                 // find the first row of this paragraph
669                 RowList::iterator tmprit = rowlist_.begin();
670                 while (tmprit != rowlist_.end()
671                        && tmprit->par() != row.par())
672                         ++tmprit;
673
674                 int minfill = tmprit->fill();
675                 while (boost::next(tmprit) != rowlist_.end() &&
676                        boost::next(tmprit)->par() == row.par()) {
677                         ++tmprit;
678                         if (tmprit->fill() < minfill)
679                                 minfill = tmprit->fill();
680                 }
681
682                 x += font_metrics::signedWidth(layout->leftmargin,
683                         tclass.defaultfont());
684                 x += minfill;
685         }
686         break;
687         }
688
689         if ((workWidth() > 0) &&
690                 !row.par()->params().leftIndent().zero())
691         {
692                 LyXLength const len = row.par()->params().leftIndent();
693                 int const tw = inset_owner ?
694                         inset_owner->latexTextWidth(bv()) : workWidth();
695                 x += len.inPixels(tw);
696         }
697
698         LyXAlignment align;
699
700         if (row.par()->params().align() == LYX_ALIGN_LAYOUT)
701                 align = layout->align;
702         else
703                 align = row.par()->params().align();
704
705         // set the correct parindent
706         if (row.pos() == 0) {
707                 if ((layout->labeltype == LABEL_NO_LABEL
708                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
709                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
710                      || (layout->labeltype == LABEL_STATIC
711                          && layout->latextype == LATEX_ENVIRONMENT
712                          && !isFirstInSequence(row.par(), ownerParagraphs())))
713                     && align == LYX_ALIGN_BLOCK
714                     && !row.par()->params().noindent()
715                         // in tabulars and ert paragraphs are never indented!
716                         && (!row.par()->inInset() || !row.par()->inInset()->owner() ||
717                                 (row.par()->inInset()->owner()->lyxCode() != Inset::TABULAR_CODE &&
718                                  row.par()->inInset()->owner()->lyxCode() != Inset::ERT_CODE))
719                     && (row.par()->layout() != tclass.defaultLayout() ||
720                         bv()->buffer()->params.paragraph_separation ==
721                         BufferParams::PARSEP_INDENT)) {
722                         x += font_metrics::signedWidth(parindent,
723                                                   tclass.defaultfont());
724                 } else if (layout->labeltype == LABEL_BIBLIO) {
725                         // ale970405 Right width for bibitems
726                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
727                 }
728         }
729
730         return x;
731 }
732
733
734 int LyXText::rightMargin(Buffer const & buf, Row const & row) const
735 {
736         Inset * ins;
737
738         if (row.pos() < row.par()->size())
739                 if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
740                     (ins = row.par()->getInset(row.pos())) &&
741                     (ins->needFullRow() || ins->display()))
742                         return PAPER_MARGIN;
743
744         LyXTextClass const & tclass = buf.params.getLyXTextClass();
745         LyXLayout_ptr const & layout = row.par()->layout();
746
747         int x = PAPER_MARGIN
748                 + font_metrics::signedWidth(tclass.rightmargin(),
749                                        tclass.defaultfont());
750
751         x += font_metrics::signedWidth(layout->rightmargin,
752                                        tclass.defaultfont())
753                 * 4 / (row.par()->getDepth() + 4);
754         return x;
755 }
756
757
758 int LyXText::labelEnd(Row const & row) const
759 {
760         if (row.par()->layout()->margintype == MARGIN_MANUAL) {
761                 Row tmprow = row;
762                 tmprow.pos(row.par()->size());
763                 // return the beginning of the body
764                 return leftMargin(tmprow);
765         }
766
767         // LabelEnd is only needed if the layout
768         // fills a flushleft label.
769         return 0;
770 }
771
772
773 namespace {
774
775 // this needs special handling - only newlines count as a break point
776 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
777 {
778         for (; i < par.size(); ++i) {
779                 if (par.isNewline(i))
780                         return i;
781         }
782
783         return par.size();
784 }
785
786 };
787
788
789 pos_type LyXText::rowBreakPoint(Row const & row) const
790 {
791         ParagraphList::iterator pit = row.par();
792
793         // maximum pixel width of a row.
794         int width = workWidth() - rightMargin(*bv()->buffer(), row);
795
796         // inset->textWidth() returns -1 via workWidth(),
797         // but why ?
798         if (width < 0)
799                 return pit->size();
800
801         LyXLayout_ptr const & layout = pit->layout();
802
803         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
804                 return addressBreakPoint(row.pos(), *pit);
805
806         pos_type const pos = row.pos();
807         pos_type const body_pos = pit->beginningOfBody();
808         pos_type const last = pit->size();
809         pos_type point = last;
810
811         if (pos == last)
812                 return last;
813
814         // Now we iterate through until we reach the right margin
815         // or the end of the par, then choose the possible break
816         // nearest that.
817
818         int const left = leftMargin(row);
819         int x = left;
820
821         // pixel width since last breakpoint
822         int chunkwidth = 0;
823         bool fullrow = false;
824
825         pos_type i = pos;
826         for (; i < last; ++i) {
827                 if (pit->isNewline(i)) {
828                         point = i;
829                         break;
830                 }
831
832                 char const c = pit->getChar(i);
833
834                 int thiswidth;
835
836                 // add the auto-hfill from label end to the body
837                 if (body_pos && i == body_pos) {
838                         thiswidth = font_metrics::width(layout->labelsep,
839                                 getLabelFont(bv()->buffer(), pit));
840                         if (pit->isLineSeparator(i - 1))
841                                 thiswidth -= singleWidth(pit, i - 1);
842                         int left_margin = labelEnd(row);
843                         if (thiswidth + x < left_margin)
844                                 thiswidth = left_margin - x;
845                         thiswidth += singleWidth(pit, i, c);
846                 } else {
847                         thiswidth = singleWidth(pit, i, c);
848                 }
849
850                 x += thiswidth;
851                 chunkwidth += thiswidth;
852
853                 Inset * in = pit->isInset(i) ? pit->getInset(i) : 0;
854                 fullrow = (in && (in->display() || in->needFullRow()));
855
856                 // break before a character that will fall off
857                 // the right of the row
858                 if (x >= width) {
859                         // if no break before or we are at an inset
860                         // that will take up a row, break here
861                         if (point == last || fullrow || chunkwidth >= (width - left)) {
862                                 if (pos < i)
863                                         point = i - 1;
864                                 else
865                                         point = i;
866                         }
867                         break;
868                 }
869
870                 if (!in || in->isChar()) {
871                         // some insets are line separators too
872                         if (pit->isLineSeparator(i)) {
873                                 point = i;
874                                 chunkwidth = 0;
875                         }
876                         continue;
877                 }
878
879                 if (!fullrow)
880                         continue;
881
882                 // full row insets start at a new row
883                 if (i == pos) {
884                         if (pos < last - 1) {
885                                 point = i;
886                                 if (pit->isLineSeparator(i + 1))
887                                         ++point;
888                         } else {
889                                 // to avoid extra rows
890                                 point = last;
891                         }
892                 } else {
893                         point = i - 1;
894                 }
895
896                 return point;
897         }
898
899         if (point == last && x >= width) {
900                 // didn't find one, break at the point we reached the edge
901                 point = i;
902         } else if (i == last && x < width) {
903                 // found one, but we fell off the end of the par, so prefer
904                 // that.
905                 point = last;
906         }
907
908         // manual labels cannot be broken in LaTeX. But we
909         // want to make our on-screen rendering of footnotes
910         // etc. still break
911         if (!fullrow && body_pos && point < body_pos)
912                 point = body_pos - 1;
913
914         return point;
915 }
916
917
918 // returns the minimum space a row needs on the screen in pixel
919 int LyXText::fill(RowList::iterator row, int paper_width) const
920 {
921         if (paper_width < 0)
922                 return 0;
923
924         int w;
925         // get the pure distance
926         pos_type const last = lastPrintablePos(*this, row);
927
928         ParagraphList::iterator pit = row->par();
929         LyXLayout_ptr const & layout = pit->layout();
930
931         // special handling of the right address boxes
932         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
933                 int const tmpfill = row->fill();
934                 row->fill(0); // the minfill in MarginLeft()
935                 w = leftMargin(*row);
936                 row->fill(tmpfill);
937         } else
938                 w = leftMargin(*row);
939
940         pos_type const body_pos = pit->beginningOfBody();
941         pos_type i = row->pos();
942
943         while (i <= last) {
944                 if (body_pos > 0 && i == body_pos) {
945                         w += font_metrics::width(layout->labelsep, getLabelFont(bv()->buffer(), pit));
946                         if (pit->isLineSeparator(i - 1))
947                                 w -= singleWidth(pit, i - 1);
948                         int left_margin = labelEnd(*row);
949                         if (w < left_margin)
950                                 w = left_margin;
951                 }
952                 w += singleWidth(pit, i);
953                 ++i;
954         }
955         if (body_pos > 0 && body_pos > last) {
956                 w += font_metrics::width(layout->labelsep, getLabelFont(bv()->buffer(), pit));
957                 if (last >= 0 && pit->isLineSeparator(last))
958                         w -= singleWidth(pit, last);
959                 int const left_margin = labelEnd(*row);
960                 if (w < left_margin)
961                         w = left_margin;
962         }
963
964         int const fill = paper_width - w - rightMargin(*bv()->buffer(), *row);
965
966         // If this case happens, it means that our calculation
967         // of the widths of the chars when we do rowBreakPoint()
968         // went wrong for some reason. Typically in list bodies.
969         // Things just about hobble on anyway, though you'll end
970         // up with a "fill_separator" less than zero, which corresponds
971         // to inter-word spacing being too small. Hopefully this problem
972         // will die when the label hacks die.
973         if (lyxerr.debugging() && fill < 0) {
974                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
975                         << " w " << w << " paper_width " << paper_width
976                         << " right margin " << rightMargin(*bv()->buffer(), *row) << endl;
977         }
978
979         return fill;
980 }
981
982
983 // returns the minimum space a manual label needs on the screen in pixel
984 int LyXText::labelFill(Row const & row) const
985 {
986         ParagraphList::iterator pit = row.par();
987
988         pos_type last = pit->beginningOfBody();
989
990         Assert(last > 0);
991
992         // -1 because a label ends either with a space that is in the label,
993         // or with the beginning of a footnote that is outside the label.
994         --last;
995
996         // a separator at this end does not count
997         if (pit->isLineSeparator(last))
998                 --last;
999
1000         int w = 0;
1001         pos_type i = row.pos();
1002         while (i <= last) {
1003                 w += singleWidth(pit, i);
1004                 ++i;
1005         }
1006
1007         int fill = 0;
1008         string const & labwidstr = pit->params().labelWidthString();
1009         if (!labwidstr.empty()) {
1010                 LyXFont const labfont = getLabelFont(bv()->buffer(), pit);
1011                 int const labwidth = font_metrics::width(labwidstr, labfont);
1012                 fill = max(labwidth - w, 0);
1013         }
1014
1015         return fill;
1016 }
1017
1018
1019 LColor::color LyXText::backgroundColor() const
1020 {
1021         if (inset_owner)
1022                 return inset_owner->backgroundColor();
1023         else
1024                 return LColor::background;
1025 }
1026
1027
1028 void LyXText::setHeightOfRow(RowList::iterator rit)
1029 {
1030         Assert(rit != rows().end());
1031
1032         // get the maximum ascent and the maximum descent
1033         float layoutasc = 0;
1034         float layoutdesc = 0;
1035         float tmptop = 0;
1036         LyXFont tmpfont;
1037         Inset * tmpinset = 0;
1038
1039         // ok , let us initialize the maxasc and maxdesc value.
1040         // This depends in LaTeX of the font of the last character
1041         // in the paragraph. The hack below is necessary because
1042         // of the possibility of open footnotes
1043
1044         // Correction: only the fontsize count. The other properties
1045         //  are taken from the layoutfont. Nicer on the screen :)
1046         ParagraphList::iterator pit = rit->par();
1047
1048         LyXLayout_ptr const & layout = pit->layout();
1049
1050         // as max get the first character of this row then it can increase but not
1051         // decrease the height. Just some point to start with so we don't have to
1052         // do the assignment below too often.
1053         LyXFont font = getFont(bv()->buffer(), pit, rit->pos());
1054         LyXFont::FONT_SIZE const tmpsize = font.size();
1055         font = getLayoutFont(bv()->buffer(), pit);
1056         LyXFont::FONT_SIZE const size = font.size();
1057         font.setSize(tmpsize);
1058
1059         LyXFont labelfont = getLabelFont(bv()->buffer(), pit);
1060
1061         float spacing_val = 1.0;
1062         if (!pit->params().spacing().isDefault()) {
1063                 spacing_val = pit->params().spacing().getValue();
1064         } else {
1065                 spacing_val = bv()->buffer()->params.spacing.getValue();
1066         }
1067         //lyxerr << "spacing_val = " << spacing_val << endl;
1068
1069         int maxasc = int(font_metrics::maxAscent(font) *
1070                          layout->spacing.getValue() *
1071                          spacing_val);
1072         int maxdesc = int(font_metrics::maxDescent(font) *
1073                           layout->spacing.getValue() *
1074                           spacing_val);
1075
1076         pos_type const pos_end = lastPos(*this, rit);
1077         int labeladdon = 0;
1078         int maxwidth = 0;
1079
1080         if (!pit->empty()) {
1081                 // Check if any insets are larger
1082                 for (pos_type pos = rit->pos(); pos <= pos_end; ++pos) {
1083                         if (pit->isInset(pos)) {
1084                                 tmpfont = getFont(bv()->buffer(), pit, pos);
1085                                 tmpinset = pit->getInset(pos);
1086                                 if (tmpinset) {
1087 #if 1 // this is needed for deep update on initialitation
1088 #warning inset->update FIXME
1089                                         //tmpinset->update(bv());
1090                                         Dimension dim;
1091                                         MetricsInfo mi;
1092                                         mi.base.bv = bv();
1093                                         mi.base.font = tmpfont;
1094                                         tmpinset->metrics(mi, dim);
1095 #endif
1096                                         //maxwidth += tmpinset->width(bv(), tmpfont);
1097                                         //maxasc = max(maxasc,
1098                                         //           tmpinset->ascent(bv(), tmpfont));
1099                                         //maxdesc = max(maxdesc,
1100                                         //            tmpinset->descent(bv(), tmpfont));
1101                                         maxwidth += dim.wid;
1102                                         maxasc = max(maxasc, dim.asc);
1103                                         maxdesc = max(maxdesc, dim.des);
1104                                 }
1105                         } else {
1106                                 maxwidth += singleWidth(pit, pos);
1107                         }
1108                 }
1109         }
1110
1111         // Check if any custom fonts are larger (Asger)
1112         // This is not completely correct, but we can live with the small,
1113         // cosmetic error for now.
1114         LyXFont::FONT_SIZE maxsize =
1115                 pit->highestFontInRange(rit->pos(), pos_end, size);
1116         if (maxsize > font.size()) {
1117                 font.setSize(maxsize);
1118                 maxasc = max(maxasc, font_metrics::maxAscent(font));
1119                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
1120         }
1121
1122         // This is nicer with box insets:
1123         ++maxasc;
1124         ++maxdesc;
1125
1126         rit->ascent_of_text(maxasc);
1127
1128         // is it a top line?
1129         if (!rit->pos()) {
1130
1131                 // some parksips VERY EASY IMPLEMENTATION
1132                 if (bv()->buffer()->params.paragraph_separation ==
1133                         BufferParams::PARSEP_SKIP)
1134                 {
1135                         if (layout->isParagraph()
1136                                 && pit->getDepth() == 0
1137                                 && pit != ownerParagraphs().begin())
1138                         {
1139                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1140                         } else if (pit != ownerParagraphs().begin() &&
1141                                    boost::prior(pit)->layout()->isParagraph() &&
1142                                    boost::prior(pit)->getDepth() == 0)
1143                         {
1144                                 // is it right to use defskip here too? (AS)
1145                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1146                         }
1147                 }
1148
1149                 // the top margin
1150                 if (pit == ownerParagraphs().begin() && !isInInset())
1151                         maxasc += PAPER_MARGIN;
1152
1153                 // add the vertical spaces, that the user added
1154                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1155
1156                 // do not forget the DTP-lines!
1157                 // there height depends on the font of the nearest character
1158                 if (pit->params().lineTop())
1159
1160                         maxasc += 2 * font_metrics::ascent('x', getFont(bv()->buffer(),
1161                                         pit, 0));
1162                 // and now the pagebreaks
1163                 if (pit->params().pagebreakTop())
1164                         maxasc += 3 * defaultRowHeight();
1165
1166                 if (pit->params().startOfAppendix())
1167                         maxasc += 3 * defaultRowHeight();
1168
1169                 // This is special code for the chapter, since the label of this
1170                 // layout is printed in an extra row
1171                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1172                         && bv()->buffer()->params.secnumdepth >= 0)
1173                 {
1174                         float spacing_val = 1.0;
1175                         if (!pit->params().spacing().isDefault()) {
1176                                 spacing_val = pit->params().spacing().getValue();
1177                         } else {
1178                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1179                         }
1180
1181                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1182                                          layout->spacing.getValue() *
1183                                          spacing_val)
1184                                 + int(font_metrics::maxAscent(labelfont) *
1185                                       layout->spacing.getValue() *
1186                                       spacing_val);
1187                 }
1188
1189                 // special code for the top label
1190                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1191                      || layout->labeltype == LABEL_BIBLIO
1192                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1193                     && isFirstInSequence(pit, ownerParagraphs())
1194                     && !pit->getLabelstring().empty())
1195                 {
1196                         float spacing_val = 1.0;
1197                         if (!pit->params().spacing().isDefault()) {
1198                                 spacing_val = pit->params().spacing().getValue();
1199                         } else {
1200                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1201                         }
1202
1203                         labeladdon = int(
1204                                 (font_metrics::maxAscent(labelfont) *
1205                                  layout->spacing.getValue() *
1206                                  spacing_val)
1207                                 +(font_metrics::maxDescent(labelfont) *
1208                                   layout->spacing.getValue() *
1209                                   spacing_val)
1210                                 + layout->topsep * defaultRowHeight()
1211                                 + layout->labelbottomsep * defaultRowHeight());
1212                 }
1213
1214                 // And now the layout spaces, for example before and after
1215                 // a section, or between the items of a itemize or enumerate
1216                 // environment.
1217
1218                 if (!pit->params().pagebreakTop()) {
1219                         ParagraphList::iterator prev =
1220                                 depthHook(pit, ownerParagraphs(),
1221                                           pit->getDepth());
1222                         if (prev != pit && prev->layout() == layout &&
1223                                 prev->getDepth() == pit->getDepth() &&
1224                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1225                         {
1226                                 layoutasc = (layout->itemsep * defaultRowHeight());
1227                         } else if (rit != rows().begin()) {
1228                                 tmptop = layout->topsep;
1229
1230                                 if (boost::prior(pit)->getDepth() >= pit->getDepth())
1231                                         tmptop -= boost::prior(rit)->par()->layout()->bottomsep;
1232
1233                                 if (tmptop > 0)
1234                                         layoutasc = (tmptop * defaultRowHeight());
1235                         } else if (pit->params().lineTop()) {
1236                                 tmptop = layout->topsep;
1237
1238                                 if (tmptop > 0)
1239                                         layoutasc = (tmptop * defaultRowHeight());
1240                         }
1241
1242                         prev = outerHook(pit, ownerParagraphs());
1243                         if (prev != ownerParagraphs().end())  {
1244                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1245                         } else if (pit != ownerParagraphs().begin()) {
1246                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1247                                 if (prior_pit->getDepth() != 0 ||
1248                                     prior_pit->layout() == layout) {
1249                                         maxasc += int(layout->parsep * defaultRowHeight());
1250                                 }
1251                         }
1252                 }
1253         }
1254
1255         // is it a bottom line?
1256         RowList::iterator next_rit = boost::next(rit);
1257         if (next_rit == rows().end() || next_rit->par() != pit) {
1258                 // the bottom margin
1259                 ParagraphList::iterator nextpit = boost::next(pit);
1260                 if (nextpit == ownerParagraphs().end() &&
1261                     !isInInset())
1262                         maxdesc += PAPER_MARGIN;
1263
1264                 // add the vertical spaces, that the user added
1265                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1266
1267                 // do not forget the DTP-lines!
1268                 // there height depends on the font of the nearest character
1269                 if (pit->params().lineBottom())
1270                         maxdesc += 2 * font_metrics::ascent('x',
1271                                                        getFont(bv()->buffer(),
1272                                                                pit,
1273                                                                max(pos_type(0), pit->size() - 1)));
1274
1275                 // and now the pagebreaks
1276                 if (pit->params().pagebreakBottom())
1277                         maxdesc += 3 * defaultRowHeight();
1278
1279                 // and now the layout spaces, for example before and after
1280                 // a section, or between the items of a itemize or enumerate
1281                 // environment
1282                 if (!pit->params().pagebreakBottom()
1283                     && nextpit != ownerParagraphs().end()) {
1284                         ParagraphList::iterator comparepit = pit;
1285                         float usual = 0;
1286                         float unusual = 0;
1287
1288                         if (comparepit->getDepth() > nextpit->getDepth()) {
1289                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1290                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1291                                 if (comparepit->layout()!= nextpit->layout()
1292                                         || nextpit->getLabelWidthString() !=
1293                                         comparepit->getLabelWidthString())
1294                                 {
1295                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1296                                 }
1297                                 if (unusual > usual)
1298                                         layoutdesc = unusual;
1299                                 else
1300                                         layoutdesc = usual;
1301                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1302
1303                                 if (comparepit->layout() != nextpit->layout()
1304                                         || nextpit->getLabelWidthString() !=
1305                                         comparepit->getLabelWidthString())
1306                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1307                         }
1308                 }
1309         }
1310
1311         // incalculate the layout spaces
1312         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1313         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1314
1315         // calculate the new height of the text
1316         height -= rit->height();
1317
1318         rit->height(maxasc + maxdesc + labeladdon);
1319         rit->baseline(maxasc + labeladdon);
1320
1321         height += rit->height();
1322
1323         rit->top_of_text(rit->baseline() - font_metrics::maxAscent(font));
1324
1325         float x = 0;
1326         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1327                 float dummy;
1328                 // this IS needed
1329                 rit->width(maxwidth);
1330                 prepareToPrint(rit, x, dummy, dummy, dummy, false);
1331         }
1332         rit->width(int(maxwidth + x));
1333         if (inset_owner) {
1334                 width = max(0, workWidth());
1335                 RowList::iterator it = rows().begin();
1336                 RowList::iterator end = rows().end();
1337                 for (; it != end; ++it) {
1338                         if (it->width() > width)
1339                                 width = it->width();
1340                 }
1341         }
1342 }
1343
1344
1345 // Appends the implicit specified paragraph before the specified row,
1346 // start at the implicit given position
1347 void LyXText::appendParagraph(RowList::iterator rowit)
1348 {
1349         Assert(rowit != rowlist_.end());
1350
1351         pos_type const last = rowit->par()->size();
1352         bool done = false;
1353
1354         do {
1355                 pos_type z = rowBreakPoint(*rowit);
1356
1357                 RowList::iterator tmprow = rowit;
1358
1359                 if (z < last) {
1360                         ++z;
1361                         Row newrow(rowit->par(), z);
1362                         rowit = rowlist_.insert(boost::next(rowit), newrow);
1363                 } else {
1364                         done = true;
1365                 }
1366
1367                 // Set the dimensions of the row
1368                 // fixed fill setting now by calling inset->update() in
1369                 // SingleWidth when needed!
1370                 tmprow->fill(fill(tmprow, workWidth()));
1371                 setHeightOfRow(tmprow);
1372
1373         } while (!done);
1374 }
1375
1376
1377 void LyXText::breakAgain(RowList::iterator rit)
1378 {
1379         Assert(rit != rows().end());
1380
1381         bool not_ready = true;
1382
1383         do  {
1384                 pos_type z = rowBreakPoint(*rit);
1385                 RowList::iterator tmprit = rit;
1386                 RowList::iterator end = rows().end();
1387
1388                 if (z < rit->par()->size()) {
1389                         RowList::iterator next_rit = boost::next(rit);
1390
1391                         if (next_rit == end ||
1392                             (next_rit != end &&
1393                              next_rit->par() != rit->par())) {
1394                                 // insert a new row
1395                                 ++z;
1396                                 Row newrow(rit->par(), z);
1397                                 rit = rowlist_.insert(next_rit, newrow);
1398                         } else  {
1399                                 ++rit;
1400                                 ++z;
1401                                 if (rit->pos() == z)
1402                                         not_ready = false; // the rest will not change
1403                                 else {
1404                                         rit->pos(z);
1405                                 }
1406                         }
1407                 } else {
1408                         // if there are some rows too much, delete them
1409                         // only if you broke the whole paragraph!
1410                         RowList::iterator tmprit2 = rit;
1411                         while (boost::next(tmprit2) != end
1412                                && boost::next(tmprit2)->par() == rit->par()) {
1413                                 ++tmprit2;
1414                         }
1415                         while (tmprit2 != rit) {
1416                                 --tmprit2;
1417                                 removeRow(boost::next(tmprit2));
1418                         }
1419                         not_ready = false;
1420                 }
1421
1422                 // set the dimensions of the row
1423                 tmprit->fill(fill(tmprit, workWidth()));
1424                 setHeightOfRow(tmprit);
1425         } while (not_ready);
1426 }
1427
1428
1429 // this is just a little changed version of break again
1430 void LyXText::breakAgainOneRow(RowList::iterator rit)
1431 {
1432         Assert(rit != rows().end());
1433
1434         pos_type z = rowBreakPoint(*rit);
1435         RowList::iterator tmprit = rit;
1436         RowList::iterator end = rows().end();
1437
1438         if (z < rit->par()->size()) {
1439                 RowList::iterator next_rit = boost::next(rit);
1440
1441                 if (next_rit == end ||
1442                     (next_rit != end &&
1443                      next_rit->par() != rit->par())) {
1444                         // insert a new row
1445                         ++z;
1446                         Row newrow(rit->par(), z);
1447                         rit = rowlist_.insert(next_rit, newrow);
1448                 } else  {
1449                         ++rit;
1450                         ++z;
1451                         if (rit->pos() != z)
1452                                 rit->pos(z);
1453                 }
1454         } else {
1455                 // if there are some rows too much, delete them
1456                 // only if you broke the whole paragraph!
1457                 RowList::iterator tmprit2 = rit;
1458                 while (boost::next(tmprit2) != end
1459                        && boost::next(tmprit2)->par() == rit->par()) {
1460                         ++tmprit2;
1461                 }
1462                 while (tmprit2 != rit) {
1463                         --tmprit2;
1464                         removeRow(boost::next(tmprit2));
1465                 }
1466         }
1467
1468         // set the dimensions of the row
1469         tmprit->fill(fill(tmprit, workWidth()));
1470         setHeightOfRow(tmprit);
1471 }
1472
1473
1474 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1475 {
1476         // allow only if at start or end, or all previous is new text
1477         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1478                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1479                 return;
1480
1481         LyXTextClass const & tclass =
1482                 bv()->buffer()->params.getLyXTextClass();
1483         LyXLayout_ptr const & layout = cursor.par()->layout();
1484
1485         // this is only allowed, if the current paragraph is not empty or caption
1486         // and if it has not the keepempty flag active
1487         if (cursor.par()->empty() && !cursor.par()->allowEmpty()
1488            && layout->labeltype != LABEL_SENSITIVE)
1489                 return;
1490
1491         setUndo(bv(), Undo::FINISH, cursor.par());
1492
1493         // Always break behind a space
1494         //
1495         // It is better to erase the space (Dekel)
1496         if (cursor.pos() < cursor.par()->size()
1497              && cursor.par()->isLineSeparator(cursor.pos()))
1498            cursor.par()->erase(cursor.pos());
1499         // cursor.pos(cursor.pos() + 1);
1500
1501         // break the paragraph
1502         if (keep_layout)
1503                 keep_layout = 2;
1504         else
1505                 keep_layout = layout->isEnvironment();
1506
1507         // we need to set this before we insert the paragraph. IMO the
1508         // breakParagraph call should return a bool if it inserts the
1509         // paragraph before or behind and we should react on that one
1510         // but we can fix this in 1.3.0 (Jug 20020509)
1511         bool const isempty = (cursor.par()->allowEmpty() && cursor.par()->empty());
1512         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(), 
1513                          cursor.pos(), keep_layout);
1514
1515         // well this is the caption hack since one caption is really enough
1516         if (layout->labeltype == LABEL_SENSITIVE) {
1517                 if (!cursor.pos())
1518                         // set to standard-layout
1519                         cursor.par()->applyLayout(tclass.defaultLayout());
1520                 else
1521                         // set to standard-layout
1522                         boost::next(cursor.par())->applyLayout(tclass.defaultLayout());
1523         }
1524
1525         // if the cursor is at the beginning of a row without prior newline,
1526         // move one row up!
1527         // This touches only the screen-update. Otherwise we would may have
1528         // an empty row on the screen
1529         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1530             && !cursorRow()->par()->isNewline(cursor.pos() - 1))
1531         {
1532                 cursorLeft(bv());
1533         }
1534
1535         postPaint();
1536
1537         removeParagraph(cursorRow());
1538
1539         // set the dimensions of the cursor row
1540         cursorRow()->fill(fill(cursorRow(), workWidth()));
1541
1542         setHeightOfRow(cursorRow());
1543
1544 #warning Trouble Point! (Lgb)
1545         // When ::breakParagraph is called from within an inset we must
1546         // ensure that the correct ParagraphList is used. Today that is not
1547         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1548         ParagraphList::iterator next_par = boost::next(cursor.par());
1549
1550         while (!next_par->empty() && next_par->isNewline(0))
1551                 next_par->erase(0);
1552
1553         insertParagraph(next_par, boost::next(cursorRow()));
1554         updateCounters();
1555
1556         // This check is necessary. Otherwise the new empty paragraph will
1557         // be deleted automatically. And it is more friendly for the user!
1558         if (cursor.pos() || isempty)
1559                 setCursor(next_par, 0);
1560         else
1561                 setCursor(cursor.par(), 0);
1562
1563         if (boost::next(cursorRow()) != rows().end())
1564                 breakAgain(boost::next(cursorRow()));
1565
1566         need_break_row = rows().end();
1567 }
1568
1569
1570 // Just a macro to make some thing easier.
1571 void LyXText::redoParagraph()
1572 {
1573         clearSelection();
1574         redoParagraphs(cursor, boost::next(cursor.par()));
1575         setCursorIntern(cursor.par(), cursor.pos());
1576 }
1577
1578
1579 // insert a character, moves all the following breaks in the
1580 // same Paragraph one to the right and make a rebreak
1581 void LyXText::insertChar(char c)
1582 {
1583         setUndo(bv(), Undo::INSERT, cursor.par());
1584
1585         // When the free-spacing option is set for the current layout,
1586         // disable the double-space checking
1587
1588         bool const freeSpacing = cursorRow()->par()->layout()->free_spacing ||
1589                 cursorRow()->par()->isFreeSpacing();
1590
1591         if (lyxrc.auto_number) {
1592                 static string const number_operators = "+-/*";
1593                 static string const number_unary_operators = "+-";
1594                 static string const number_seperators = ".,:";
1595
1596                 if (current_font.number() == LyXFont::ON) {
1597                         if (!IsDigit(c) && !contains(number_operators, c) &&
1598                             !(contains(number_seperators, c) &&
1599                               cursor.pos() >= 1 &&
1600                               cursor.pos() < cursor.par()->size() &&
1601                               getFont(bv()->buffer(),
1602                                       cursor.par(),
1603                                       cursor.pos()).number() == LyXFont::ON &&
1604                               getFont(bv()->buffer(),
1605                                       cursor.par(),
1606                                       cursor.pos() - 1).number() == LyXFont::ON)
1607                            )
1608                                 number(bv()); // Set current_font.number to OFF
1609                 } else if (IsDigit(c) &&
1610                            real_current_font.isVisibleRightToLeft()) {
1611                         number(bv()); // Set current_font.number to ON
1612
1613                         if (cursor.pos() > 0) {
1614                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1615                                 if (contains(number_unary_operators, c) &&
1616                                     (cursor.pos() == 1 ||
1617                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1618                                      cursor.par()->isNewline(cursor.pos() - 2))
1619                                   ) {
1620                                         setCharFont(bv()->buffer(),
1621                                                     cursor.par(),
1622                                                     cursor.pos() - 1,
1623                                                     current_font);
1624                                 } else if (contains(number_seperators, c) &&
1625                                            cursor.pos() >= 2 &&
1626                                            getFont(bv()->buffer(),
1627                                                    cursor.par(),
1628                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1629                                         setCharFont(bv()->buffer(),
1630                                                     cursor.par(),
1631                                                     cursor.pos() - 1,
1632                                                     current_font);
1633                                 }
1634                         }
1635                 }
1636         }
1637
1638
1639         // First check, if there will be two blanks together or a blank at
1640         // the beginning of a paragraph.
1641         // I decided to handle blanks like normal characters, the main
1642         // difference are the special checks when calculating the row.fill
1643         // (blank does not count at the end of a row) and the check here
1644
1645         // The bug is triggered when we type in a description environment:
1646         // The current_font is not changed when we go from label to main text
1647         // and it should (along with realtmpfont) when we type the space.
1648         // CHECK There is a bug here! (Asger)
1649
1650         LyXFont realtmpfont = real_current_font;
1651         LyXFont rawtmpfont = current_font;
1652         // store the current font.  This is because of the use of cursor
1653         // movements. The moving cursor would refresh the current font
1654
1655         // Get the font that is used to calculate the baselineskip
1656         pos_type const lastpos = cursor.par()->size();
1657         LyXFont rawparfont =
1658                 cursor.par()->getFontSettings(bv()->buffer()->params,
1659                                               lastpos - 1);
1660
1661         bool jumped_over_space = false;
1662
1663         if (!freeSpacing && IsLineSeparatorChar(c)) {
1664                 if ((cursor.pos() > 0
1665                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1666                     || (cursor.pos() > 0
1667                         && cursor.par()->isNewline(cursor.pos() - 1))
1668                     || (cursor.pos() == 0)) {
1669                         static bool sent_space_message = false;
1670                         if (!sent_space_message) {
1671                                 if (cursor.pos() == 0)
1672                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1673                                 else
1674                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1675                                 sent_space_message = true;
1676                         }
1677                         charInserted();
1678                         return;
1679                 }
1680         }
1681
1682         // the display inset stuff
1683         if (cursorRow()->pos() < cursorRow()->par()->size()
1684             && cursorRow()->par()->isInset(cursorRow()->pos())) {
1685                 Inset * inset = cursorRow()->par()->getInset(cursorRow()->pos());
1686                 if (inset && (inset->display() || inset->needFullRow())) {
1687                         // force a new break
1688                         cursorRow()->fill(-1); // to force a new break
1689                 }
1690         }
1691
1692         // get the cursor row fist
1693         RowList::iterator row = cursorRow();
1694         if (c != Paragraph::META_INSET) {
1695                 // Here case LyXText::InsertInset  already inserted the character
1696                 cursor.par()->insertChar(cursor.pos(), c);
1697         }
1698         setCharFont(bv()->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1699
1700         if (!jumped_over_space) {
1701                 // refresh the positions
1702                 RowList::iterator tmprow = row;
1703                 while (boost::next(tmprow) != rows().end() &&
1704                        boost::next(tmprow)->par() == row->par()) {
1705                         ++tmprow;
1706                         tmprow->pos(tmprow->pos() + 1);
1707                 }
1708         }
1709
1710         // Is there a break one row above
1711         if (row != rows().begin() &&
1712             boost::prior(row)->par() == row->par()
1713             && (cursor.par()->isLineSeparator(cursor.pos())
1714                 || cursor.par()->isNewline(cursor.pos())
1715                 || ((cursor.pos() + 1 < cursor.par()->size()) &&
1716                     cursor.par()->isInset(cursor.pos() + 1))
1717                 || cursorRow()->fill() == -1))
1718         {
1719                 pos_type z = rowBreakPoint(*boost::prior(row));
1720
1721                 if (z >= row->pos()) {
1722                         row->pos(z + 1);
1723
1724                         // set the dimensions of the row above
1725                         boost::prior(row)->fill(fill(
1726                                                    boost::prior(row),
1727                                                    workWidth()));
1728
1729                         setHeightOfRow(boost::prior(row));
1730
1731                         postPaint();
1732
1733                         breakAgainOneRow(row);
1734
1735                         current_font = rawtmpfont;
1736                         real_current_font = realtmpfont;
1737                         setCursor(cursor.par(), cursor.pos() + 1,
1738                                   false, cursor.boundary());
1739                         // cursor MUST be in row now.
1740
1741                         RowList::iterator next_row = boost::next(row);
1742                         if (next_row != rows().end() &&
1743                             next_row->par() == row->par())
1744                                 need_break_row = next_row;
1745                         else
1746                                 need_break_row = rows().end();
1747
1748                         // check, wether the last characters font has changed.
1749                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1750                             && rawparfont != rawtmpfont)
1751                                 redoHeightOfParagraph();
1752
1753                         charInserted();
1754                         return;
1755                 }
1756         }
1757
1758         // recalculate the fill of the row
1759         if (row->fill() >= 0) {
1760                 // needed because a newline will set fill to -1. Otherwise
1761                 // we would not get a rebreak!
1762                 row->fill(fill(row, workWidth()));
1763         }
1764
1765         if (c == Paragraph::META_INSET || row->fill() < 0) {
1766                 postPaint();
1767                 breakAgainOneRow(row);
1768
1769                 RowList::iterator next_row = boost::next(row);
1770
1771                 // will the cursor be in another row now?
1772                 if (lastPos(*this, row) <= cursor.pos() + 1 &&
1773                     next_row != rows().end()) {
1774                         if (next_row != rows().end() &&
1775                             next_row->par() == row->par()) {
1776                                 // this should always be true
1777                                 ++row;
1778                         }
1779
1780                         breakAgainOneRow(row);
1781                 }
1782                 current_font = rawtmpfont;
1783                 real_current_font = realtmpfont;
1784
1785                 setCursor(cursor.par(), cursor.pos() + 1, false,
1786                           cursor.boundary());
1787                 if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
1788                     != cursor.boundary())
1789                         setCursor(cursor.par(), cursor.pos(), false,
1790                           !cursor.boundary());
1791
1792                 next_row = boost::next(row);
1793
1794                 if (next_row != rows().end() &&
1795                     next_row->par() == row->par())
1796                         need_break_row = next_row;
1797                 else
1798                         need_break_row = rows().end();
1799         } else {
1800                 // FIXME: similar code is duplicated all over - make resetHeightOfRow
1801                 setHeightOfRow(row);
1802                 postPaint();
1803
1804                 current_font = rawtmpfont;
1805                 real_current_font = realtmpfont;
1806                 setCursor(cursor.par(), cursor.pos() + 1, false,
1807                           cursor.boundary());
1808         }
1809
1810         // check, wether the last characters font has changed.
1811         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1812             && rawparfont != rawtmpfont) {
1813                 redoHeightOfParagraph();
1814         }
1815
1816         charInserted();
1817 }
1818
1819
1820 void LyXText::charInserted()
1821 {
1822         // Here we could call FinishUndo for every 20 characters inserted.
1823         // This is from my experience how emacs does it. (Lgb)
1824         static unsigned int counter;
1825         if (counter < 20) {
1826                 ++counter;
1827         } else {
1828                 finishUndo();
1829                 counter = 0;
1830         }
1831 }
1832
1833
1834 void LyXText::prepareToPrint(RowList::iterator rit, float & x,
1835                              float & fill_separator,
1836                              float & fill_hfill,
1837                              float & fill_label_hfill,
1838                              bool bidi) const
1839 {
1840         float w = rit->fill();
1841         fill_hfill = 0;
1842         fill_label_hfill = 0;
1843         fill_separator = 0;
1844         fill_label_hfill = 0;
1845
1846         ParagraphList::iterator pit = rit->par();
1847
1848         bool const is_rtl =
1849                 pit->isRightToLeftPar(bv()->buffer()->params);
1850         if (is_rtl) {
1851                 x = (workWidth() > 0)
1852                         ? rightMargin(*bv()->buffer(), *rit) : 0;
1853         } else
1854                 x = (workWidth() > 0)
1855                         ? leftMargin(*rit) : 0;
1856
1857         // is there a manual margin with a manual label
1858         LyXLayout_ptr const & layout = pit->layout();
1859
1860         if (layout->margintype == MARGIN_MANUAL
1861             && layout->labeltype == LABEL_MANUAL) {
1862                 /// We might have real hfills in the label part
1863                 float nlh = numberOfLabelHfills(*this, rit);
1864
1865                 // A manual label par (e.g. List) has an auto-hfill
1866                 // between the label text and the body of the
1867                 // paragraph too.
1868                 // But we don't want to do this auto hfill if the par
1869                 // is empty.
1870                 if (!pit->empty())
1871                         ++nlh;
1872
1873                 if (nlh && !pit->getLabelWidthString().empty()) {
1874                         fill_label_hfill = labelFill(*rit) / nlh;
1875                 }
1876         }
1877
1878         // are there any hfills in the row?
1879         float const nh = numberOfHfills(*this, rit);
1880
1881         if (nh) {
1882                 if (w > 0)
1883                         fill_hfill = w / nh;
1884         // we don't have to look at the alignment if it is ALIGN_LEFT and
1885         // if the row is already larger then the permitted width as then
1886         // we force the LEFT_ALIGN'edness!
1887         } else if (static_cast<int>(rit->width()) < workWidth()) {
1888                 // is it block, flushleft or flushright?
1889                 // set x how you need it
1890                 int align;
1891                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1892                         align = layout->align;
1893                 } else {
1894                         align = pit->params().align();
1895                 }
1896
1897                 // center displayed insets
1898                 Inset * inset = 0;
1899                 if (rit->pos() < pit->size()
1900                     && pit->isInset(rit->pos())
1901                     && (inset = pit->getInset(rit->pos()))
1902                     && (inset->display())) // || (inset->scroll() < 0)))
1903                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1904                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1905                 // ERT insets should always be LEFT ALIGNED on screen
1906                 inset = pit->inInset();
1907                 if (inset && inset->owner() &&
1908                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1909                 {
1910                         align = LYX_ALIGN_LEFT;
1911                 }
1912
1913                 switch (align) {
1914             case LYX_ALIGN_BLOCK:
1915             {
1916                         float const ns = numberOfSeparators(*this, rit);
1917                         RowList::iterator next_row = boost::next(rit);
1918                         ParagraphList::iterator next_pit = next_row->par();
1919
1920                         if (ns && next_row != rowlist_.end() &&
1921                             next_pit == pit &&
1922                             !(next_pit->isNewline(next_row->pos() - 1))
1923                             && !(next_pit->isInset(next_row->pos()) &&
1924                                  next_pit->getInset(next_row->pos()) &&
1925                                  next_pit->getInset(next_row->pos())->display())
1926                                 ) {
1927                                 fill_separator = w / ns;
1928                         } else if (is_rtl) {
1929                                 x += w;
1930                         }
1931                         break;
1932             }
1933             case LYX_ALIGN_RIGHT:
1934                         x += w;
1935                         break;
1936             case LYX_ALIGN_CENTER:
1937                         x += w / 2;
1938                         break;
1939                 }
1940         }
1941         if (!bidi)
1942                 return;
1943
1944         computeBidiTables(bv()->buffer(), rit);
1945         if (is_rtl) {
1946                 pos_type body_pos = pit->beginningOfBody();
1947                 pos_type last = lastPos(*this, rit);
1948
1949                 if (body_pos > 0 &&
1950                     (body_pos - 1 > last ||
1951                      !pit->isLineSeparator(body_pos - 1))) {
1952                         x += font_metrics::width(layout->labelsep,
1953                                             getLabelFont(bv()->buffer(),
1954                                                          pit));
1955                         if (body_pos - 1 <= last)
1956                                 x += fill_label_hfill;
1957                 }
1958         }
1959 }
1960
1961
1962 // important for the screen
1963
1964
1965 // the cursor set functions have a special mechanism. When they
1966 // realize, that you left an empty paragraph, they will delete it.
1967 // They also delete the corresponding row
1968
1969 void LyXText::cursorRightOneWord()
1970 {
1971         ::cursorRightOneWord(cursor, ownerParagraphs());
1972         setCursor(cursor.par(), cursor.pos());
1973 }
1974
1975
1976 // Skip initial whitespace at end of word and move cursor to *start*
1977 // of prior word, not to end of next prior word.
1978 void LyXText::cursorLeftOneWord()
1979 {
1980         LyXCursor tmpcursor = cursor;
1981         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
1982         setCursor(tmpcursor.par(), tmpcursor.pos());
1983 }
1984
1985
1986 void LyXText::selectWord(word_location loc)
1987 {
1988         LyXCursor from = cursor;
1989         LyXCursor to;
1990         ::getWord(from, to, loc, ownerParagraphs());
1991         if (cursor != from)
1992                 setCursor(from.par(), from.pos());
1993         if (to == from)
1994                 return;
1995         selection.cursor = cursor;
1996         setCursor(to.par(), to.pos());
1997         setSelection();
1998 }
1999
2000
2001 // Select the word currently under the cursor when no
2002 // selection is currently set
2003 bool LyXText::selectWordWhenUnderCursor(word_location loc)
2004 {
2005         if (!selection.set()) {
2006                 selectWord(loc);
2007                 return selection.set();
2008         }
2009         return false;
2010 }
2011
2012
2013 void LyXText::acceptChange()
2014 {
2015         if (!selection.set() && cursor.par()->size())
2016                 return;
2017
2018         if (selection.start.par() == selection.end.par()) {
2019                 LyXCursor & startc = selection.start;
2020                 LyXCursor & endc = selection.end;
2021                 setUndo(bv(), Undo::INSERT, startc.par());
2022                 startc.par()->acceptChange(startc.pos(), endc.pos());
2023                 finishUndo();
2024                 clearSelection();
2025                 redoParagraphs(startc, boost::next(startc.par()));
2026                 setCursorIntern(startc.par(), 0);
2027         }
2028 #warning handle multi par selection
2029 }
2030
2031
2032 void LyXText::rejectChange()
2033 {
2034         if (!selection.set() && cursor.par()->size())
2035                 return;
2036
2037         if (selection.start.par() == selection.end.par()) {
2038                 LyXCursor & startc = selection.start;
2039                 LyXCursor & endc = selection.end;
2040                 setUndo(bv(), Undo::INSERT, startc.par());
2041                 startc.par()->rejectChange(startc.pos(), endc.pos());
2042                 finishUndo();
2043                 clearSelection();
2044                 redoParagraphs(startc, boost::next(startc.par()));
2045                 setCursorIntern(startc.par(), 0);
2046         }
2047 #warning handle multi par selection
2048 }
2049
2050
2051 // This function is only used by the spellchecker for NextWord().
2052 // It doesn't handle LYX_ACCENTs and probably never will.
2053 WordLangTuple const
2054 LyXText::selectNextWordToSpellcheck(float & value)
2055 {
2056         if (the_locking_inset) {
2057                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
2058                 if (!word.word().empty()) {
2059                         value += float(cursor.y());
2060                         value /= float(height);
2061                         return word;
2062                 }
2063                 // we have to go on checking so move cursor to the next char
2064                 if (cursor.pos() == cursor.par()->size()) {
2065                         if (boost::next(cursor.par()) == ownerParagraphs().end())
2066                                 return word;
2067                         cursor.par(boost::next(cursor.par()));
2068                         cursor.pos(0);
2069                 } else
2070                         cursor.pos(cursor.pos() + 1);
2071         }
2072         ParagraphList::iterator tmppit = cursor.par();
2073
2074         // If this is not the very first word, skip rest of
2075         // current word because we are probably in the middle
2076         // of a word if there is text here.
2077         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
2078                 while (cursor.pos() < cursor.par()->size()
2079                        && cursor.par()->isLetter(cursor.pos()))
2080                         cursor.pos(cursor.pos() + 1);
2081         }
2082
2083         // Now, skip until we have real text (will jump paragraphs)
2084         while (true) {
2085                 ParagraphList::iterator cpit = cursor.par();
2086                 pos_type const cpos(cursor.pos());
2087
2088                 if (cpos == cpit->size()) {
2089                         if (boost::next(cpit) != ownerParagraphs().end()) {
2090                                 cursor.par(boost::next(cpit));
2091                                 cursor.pos(0);
2092                                 continue;
2093                         }
2094                         break;
2095                 }
2096
2097                 bool const is_good_inset = cpit->isInset(cpos)
2098                         && cpit->getInset(cpos)->allowSpellcheck();
2099
2100                 if (!isDeletedText(*cpit, cpos)
2101                     && (is_good_inset || cpit->isLetter(cpos)))
2102                         break;
2103
2104                 cursor.pos(cpos + 1);
2105         }
2106
2107         // now check if we hit an inset so it has to be a inset containing text!
2108         if (cursor.pos() < cursor.par()->size() &&
2109             cursor.par()->isInset(cursor.pos())) {
2110                 // lock the inset!
2111                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
2112                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
2113                 // now call us again to do the above trick
2114                 // but obviously we have to start from down below ;)
2115                 return bv()->text->selectNextWordToSpellcheck(value);
2116         }
2117
2118         // Update the value if we changed paragraphs
2119         if (cursor.par() != tmppit) {
2120                 setCursor(cursor.par(), cursor.pos());
2121                 value = float(cursor.y())/float(height);
2122         }
2123
2124         // Start the selection from here
2125         selection.cursor = cursor;
2126
2127         string lang_code(
2128                 getFont(bv()->buffer(), cursor.par(), cursor.pos())
2129                         .language()->code());
2130         // and find the end of the word (insets like optional hyphens
2131         // and ligature break are part of a word)
2132         while (cursor.pos() < cursor.par()->size()
2133                && cursor.par()->isLetter(cursor.pos())
2134                && !isDeletedText(*cursor.par(), cursor.pos()))
2135                 cursor.pos(cursor.pos() + 1);
2136
2137         // Finally, we copy the word to a string and return it
2138         string str;
2139         if (selection.cursor.pos() < cursor.pos()) {
2140                 pos_type i;
2141                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2142                         if (!cursor.par()->isInset(i))
2143                                 str += cursor.par()->getChar(i);
2144                 }
2145         }
2146         return WordLangTuple(str, lang_code);
2147 }
2148
2149
2150 // This one is also only for the spellchecker
2151 void LyXText::selectSelectedWord()
2152 {
2153         if (the_locking_inset) {
2154                 the_locking_inset->selectSelectedWord(bv());
2155                 return;
2156         }
2157         // move cursor to the beginning
2158         setCursor(selection.cursor.par(), selection.cursor.pos());
2159
2160         // set the sel cursor
2161         selection.cursor = cursor;
2162
2163         // now find the end of the word
2164         while (cursor.pos() < cursor.par()->size()
2165                && (cursor.par()->isLetter(cursor.pos())))
2166                 cursor.pos(cursor.pos() + 1);
2167
2168         setCursor(cursor.par(), cursor.pos());
2169
2170         // finally set the selection
2171         setSelection();
2172 }
2173
2174
2175 // Delete from cursor up to the end of the current or next word.
2176 void LyXText::deleteWordForward()
2177 {
2178         if (cursor.par()->empty())
2179                 cursorRight(bv());
2180         else {
2181                 LyXCursor tmpcursor = cursor;
2182                 selection.set(true); // to avoid deletion
2183                 cursorRightOneWord();
2184                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2185                 selection.cursor = cursor;
2186                 cursor = tmpcursor;
2187                 setSelection();
2188
2189                 // Great, CutSelection() gets rid of multiple spaces.
2190                 cutSelection(true, false);
2191         }
2192 }
2193
2194
2195 // Delete from cursor to start of current or prior word.
2196 void LyXText::deleteWordBackward()
2197 {
2198         if (cursor.par()->empty())
2199                 cursorLeft(bv());
2200         else {
2201                 LyXCursor tmpcursor = cursor;
2202                 selection.set(true); // to avoid deletion
2203                 cursorLeftOneWord();
2204                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2205                 selection.cursor = cursor;
2206                 cursor = tmpcursor;
2207                 setSelection();
2208                 cutSelection(true, false);
2209         }
2210 }
2211
2212
2213 // Kill to end of line.
2214 void LyXText::deleteLineForward()
2215 {
2216         if (cursor.par()->empty())
2217                 // Paragraph is empty, so we just go to the right
2218                 cursorRight(bv());
2219         else {
2220                 LyXCursor tmpcursor = cursor;
2221                 // We can't store the row over a regular setCursor
2222                 // so we set it to 0 and reset it afterwards.
2223                 selection.set(true); // to avoid deletion
2224                 cursorEnd();
2225                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2226                 selection.cursor = cursor;
2227                 cursor = tmpcursor;
2228                 setSelection();
2229                 // What is this test for ??? (JMarc)
2230                 if (!selection.set()) {
2231                         deleteWordForward();
2232                 } else {
2233                         cutSelection(true, false);
2234                 }
2235         }
2236 }
2237
2238
2239 void LyXText::changeCase(LyXText::TextCase action)
2240 {
2241         LyXCursor from;
2242         LyXCursor to;
2243
2244         if (selection.set()) {
2245                 from = selection.start;
2246                 to = selection.end;
2247         } else {
2248                 from = cursor;
2249                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
2250                 setCursor(to.par(), to.pos() + 1);
2251         }
2252
2253         setUndo(bv(), Undo::FINISH, from.par(), to.par());
2254
2255         pos_type pos = from.pos();
2256         ParagraphList::iterator pit = from.par();
2257
2258         while (pit != ownerParagraphs().end() &&
2259                (pos != to.pos() || pit != to.par())) {
2260                 if (pos == pit->size()) {
2261                         ++pit;
2262                         pos = 0;
2263                         continue;
2264                 }
2265                 unsigned char c = pit->getChar(pos);
2266                 if (!IsInsetChar(c)) {
2267                         switch (action) {
2268                         case text_lowercase:
2269                                 c = lowercase(c);
2270                                 break;
2271                         case text_capitalization:
2272                                 c = uppercase(c);
2273                                 action = text_lowercase;
2274                                 break;
2275                         case text_uppercase:
2276                                 c = uppercase(c);
2277                                 break;
2278                         }
2279                 }
2280 #warning changes
2281                 pit->setChar(pos, c);
2282                 checkParagraph(pit, pos);
2283
2284                 ++pos;
2285         }
2286
2287         if (getRow(to) != getRow(from))
2288                 postPaint();
2289 }
2290
2291
2292 void LyXText::Delete()
2293 {
2294         // this is a very easy implementation
2295
2296         LyXCursor old_cursor = cursor;
2297         int const old_cur_par_id = old_cursor.par()->id();
2298         int const old_cur_par_prev_id =
2299                 (old_cursor.par() != ownerParagraphs().begin() ?
2300                  boost::prior(old_cursor.par())->id() : -1);
2301
2302         // just move to the right
2303         cursorRight(bv());
2304
2305         // CHECK Look at the comment here.
2306         // This check is not very good...
2307         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2308         // and that can very well delete the par or par->previous in
2309         // old_cursor. Will a solution where we compare paragraph id's
2310         //work better?
2311         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
2312             == old_cur_par_prev_id
2313             && cursor.par()->id() != old_cur_par_id) {
2314                 // delete-empty-paragraph-mechanism has done it
2315                 return;
2316         }
2317
2318         // if you had success make a backspace
2319         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2320                 LyXCursor tmpcursor = cursor;
2321                 // to make sure undo gets the right cursor position
2322                 cursor = old_cursor;
2323                 setUndo(bv(), Undo::DELETE, cursor.par());
2324                 cursor = tmpcursor;
2325                 backspace();
2326         }
2327 }
2328
2329
2330 void LyXText::backspace()
2331 {
2332         // Get the font that is used to calculate the baselineskip
2333         pos_type lastpos = cursor.par()->size();
2334         LyXFont rawparfont =
2335                 cursor.par()->getFontSettings(bv()->buffer()->params,
2336                                               lastpos - 1);
2337
2338         if (cursor.pos() == 0) {
2339                 // The cursor is at the beginning of a paragraph,
2340                 // so the the backspace will collapse two paragraphs into one.
2341
2342                 // but it's not allowed unless it's new
2343                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2344                         return;
2345
2346                 // we may paste some paragraphs
2347
2348                 // is it an empty paragraph?
2349
2350                 if ((lastpos == 0
2351                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2352                         // This is an empty paragraph and we delete it just by moving the cursor one step
2353                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2354                         // of the paragraph.
2355
2356                         if (cursor.par() != ownerParagraphs().begin()) {
2357                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
2358                                 if (cursor.par()->layout() == tmppit->layout()
2359                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2360                                         // Inherit bottom DTD from the paragraph below.
2361                                         // (the one we are deleting)
2362                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
2363                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
2364                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2365                                 }
2366
2367                                 cursorLeft(bv());
2368
2369                                 // the layout things can change the height of a row !
2370                                 int const tmpheight = cursorRow()->height();
2371                                 setHeightOfRow(cursorRow());
2372                                 if (cursorRow()->height() != tmpheight)
2373                                         postPaint();
2374                                 return;
2375                         }
2376                 }
2377
2378                 if (cursor.par() != ownerParagraphs().begin()) {
2379                         setUndo(bv(), Undo::DELETE,
2380                                 boost::prior(cursor.par()),
2381                                 cursor.par());
2382                 }
2383
2384                 ParagraphList::iterator tmppit = cursor.par();
2385                 RowList::iterator tmprow = cursorRow();
2386
2387                 // We used to do cursorLeftIntern() here, but it is
2388                 // not a good idea since it triggers the auto-delete
2389                 // mechanism. So we do a cursorLeftIntern()-lite,
2390                 // without the dreaded mechanism. (JMarc)
2391                 if (cursor.par() != ownerParagraphs().begin()) {
2392                         // steps into the above paragraph.
2393                         setCursorIntern(boost::prior(cursor.par()),
2394                                         boost::prior(cursor.par())->size(),
2395                                         false);
2396                 }
2397
2398                 // Pasting is not allowed, if the paragraphs have different
2399                 // layout. I think it is a real bug of all other
2400                 // word processors to allow it. It confuses the user.
2401                 // Even so with a footnote paragraph and a non-footnote
2402                 // paragraph. I will not allow pasting in this case,
2403                 // because the user would be confused if the footnote behaves
2404                 // different wether it is open or closed.
2405
2406                 //      Correction: Pasting is always allowed with standard-layout
2407                 LyXTextClass const & tclass =
2408                         bv()->buffer()->params.getLyXTextClass();
2409
2410                 if (cursor.par() != tmppit
2411                     && (cursor.par()->layout() == tmppit->layout()
2412                         || tmppit->layout() == tclass.defaultLayout())
2413                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2414                         removeParagraph(tmprow);
2415                         removeRow(tmprow);
2416                         mergeParagraph(bv()->buffer()->params, bv()->buffer()->paragraphs, cursor.par());
2417
2418                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2419                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2420                         // strangely enough it seems that commenting out the line above removes
2421                         // most or all of the segfaults. I will however also try to move the
2422                         // two Remove... lines in front of the PasteParagraph too.
2423                         else
2424                                 if (cursor.pos())
2425                                         cursor.pos(cursor.pos() - 1);
2426
2427                         postPaint();
2428
2429                         // remove the lost paragraph
2430                         // This one is not safe, since the paragraph that the tmprow and the
2431                         // following rows belong to has been deleted by the PasteParagraph
2432                         // above. The question is... could this be moved in front of the
2433                         // PasteParagraph?
2434                         //RemoveParagraph(tmprow);
2435                         //RemoveRow(tmprow);
2436
2437                         // This rebuilds the rows.
2438                         appendParagraph(cursorRow());
2439                         updateCounters();
2440
2441                         // the row may have changed, block, hfills etc.
2442                         setCursor(cursor.par(), cursor.pos(), false);
2443                 }
2444         } else {
2445                 // this is the code for a normal backspace, not pasting
2446                 // any paragraphs
2447                 setUndo(bv(), Undo::DELETE, cursor.par());
2448                 // We used to do cursorLeftIntern() here, but it is
2449                 // not a good idea since it triggers the auto-delete
2450                 // mechanism. So we do a cursorLeftIntern()-lite,
2451                 // without the dreaded mechanism. (JMarc)
2452                 setCursorIntern(cursor.par(), cursor.pos()- 1,
2453                                 false, cursor.boundary());
2454
2455                 if (cursor.par()->isInset(cursor.pos())) {
2456                         // force complete redo when erasing display insets
2457                         // this is a cruel method but safe..... Matthias
2458                         if (cursor.par()->getInset(cursor.pos())->display() ||
2459                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2460                                 cursor.par()->erase(cursor.pos());
2461                                 redoParagraph();
2462                                 return;
2463                         }
2464                 }
2465
2466                 RowList::iterator row = cursorRow();
2467                 int y = cursor.y() - row->baseline();
2468                 pos_type z;
2469                 // remember that a space at the end of a row doesnt count
2470                 // when calculating the fill
2471                 if (cursor.pos() < lastPos(*this, row) ||
2472                     !cursor.par()->isLineSeparator(cursor.pos())) {
2473                         row->fill(row->fill() + singleWidth(
2474                                                             cursor.par(),
2475                                                             cursor.pos()));
2476                 }
2477
2478                 // some special code when deleting a newline. This is similar
2479                 // to the behavior when pasting paragraphs
2480                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2481                         cursor.par()->erase(cursor.pos());
2482                         // refresh the positions
2483                         RowList::iterator tmprow = row;
2484                         while (boost::next(tmprow) != rows().end() &&
2485                                boost::next(tmprow)->par() == row->par()) {
2486                                 ++tmprow;
2487                                 tmprow->pos(tmprow->pos() - 1);
2488                         }
2489                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2490                                 cursor.pos(cursor.pos() - 1);
2491
2492                         if (cursor.pos() < cursor.par()->size()
2493                             && !cursor.par()->isSeparator(cursor.pos())) {
2494                                 cursor.par()->insertChar(cursor.pos(), ' ');
2495                                 setCharFont(bv()->buffer(), cursor.par(),
2496                                             cursor.pos(), current_font);
2497                                 // refresh the positions
2498                                 tmprow = row;
2499                                 while (boost::next(tmprow) != rows().end() &&
2500                                        boost::next(tmprow)->par() == row->par()) {
2501                                         ++tmprow;
2502                                         tmprow->pos(tmprow->pos() + 1);
2503                                 }
2504                         }
2505                 } else {
2506                         cursor.par()->erase(cursor.pos());
2507
2508                         // refresh the positions
2509                         RowList::iterator tmprow = row;
2510                         while (boost::next(tmprow) != rows().end() &&
2511                                boost::next(tmprow)->par() == row->par()) {
2512                                 ++tmprow;
2513                                 tmprow->pos(tmprow->pos() - 1);
2514                         }
2515
2516                         // delete newlines at the beginning of paragraphs
2517                         while (!cursor.par()->empty() &&
2518                                cursor.pos() < cursor.par()->size() &&
2519                                cursor.par()->isNewline(cursor.pos()) &&
2520                                cursor.pos() == cursor.par()->beginningOfBody()) {
2521                                 cursor.par()->erase(cursor.pos());
2522                                 // refresh the positions
2523                                 tmprow = row;
2524                                 while (boost::next(tmprow) != rows().end() &&
2525                                        boost::next(tmprow)->par() == row->par()) {
2526                                         ++tmprow;
2527                                         tmprow->pos(tmprow->pos() - 1);
2528                                 }
2529                         }
2530                 }
2531
2532                 // is there a break one row above
2533                 if (row != rows().begin() && boost::prior(row)->par() == row->par()) {
2534                         z = rowBreakPoint(*boost::prior(row));
2535                         if (z >= row->pos()) {
2536                                 row->pos(z + 1);
2537
2538                                 RowList::iterator tmprow = boost::prior(row);
2539
2540                                 // maybe the current row is now empty
2541                                 if (row->pos() >= row->par()->size()) {
2542                                         // remove it
2543                                         removeRow(row);
2544                                         need_break_row = rows().end();
2545                                 } else {
2546                                         breakAgainOneRow(row);
2547                                         if (boost::next(row) != rows().end() &&
2548                                             boost::next(row)->par() == row->par())
2549                                                 need_break_row = boost::next(row);
2550                                         else
2551                                                 need_break_row = rows().end();
2552                                 }
2553
2554                                 // set the dimensions of the row above
2555                                 y -= tmprow->height();
2556                                 tmprow->fill(fill(tmprow, workWidth()));
2557                                 setHeightOfRow(tmprow);
2558                                 postPaint();
2559
2560                                 setCursor(cursor.par(), cursor.pos(),
2561                                           false, cursor.boundary());
2562                                 //current_font = rawtmpfont;
2563                                 //real_current_font = realtmpfont;
2564                                 // check, whether the last character's font has changed.
2565                                 if (rawparfont !=
2566                                     cursor.par()->getFontSettings(bv()->buffer()->params,
2567                                                                   cursor.par()->size() - 1))
2568                                         redoHeightOfParagraph();
2569                                 return;
2570                         }
2571                 }
2572
2573                 // break the cursor row again
2574                 if (boost::next(row) != rows().end() &&
2575                     boost::next(row)->par() == row->par() &&
2576                     (lastPos(*this, row) == row->par()->size() - 1 ||
2577                      rowBreakPoint(*row) != lastPos(*this, row))) {
2578
2579                         // it can happen that a paragraph loses one row
2580                         // without a real breakup. This is when a word
2581                         // is to long to be broken. Well, I don t care this
2582                         // hack ;-)
2583                         if (lastPos(*this, row) == row->par()->size() - 1)
2584                                 removeRow(boost::next(row));
2585
2586                         postPaint();
2587
2588                         breakAgainOneRow(row);
2589                         // will the cursor be in another row now?
2590                         if (boost::next(row) != rows().end() &&
2591                             boost::next(row)->par() == row->par() &&
2592                             lastPos(*this, row) <= cursor.pos()) {
2593                                 ++row;
2594                                 breakAgainOneRow(row);
2595                         }
2596
2597                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2598
2599                         if (boost::next(row) != rows().end() &&
2600                             boost::next(row)->par() == row->par())
2601                                 need_break_row = boost::next(row);
2602                         else
2603                                 need_break_row = rows().end();
2604                 } else  {
2605                         // set the dimensions of the row
2606                         row->fill(fill(row, workWidth()));
2607                         setHeightOfRow(row);
2608                         postPaint();
2609                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2610                 }
2611         }
2612
2613         // current_font = rawtmpfont;
2614         // real_current_font = realtmpfont;
2615
2616         if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
2617             != cursor.boundary())
2618                 setCursor(cursor.par(), cursor.pos(), false,
2619                           !cursor.boundary());
2620
2621         lastpos = cursor.par()->size();
2622         if (cursor.pos() == lastpos)
2623                 setCurrentFont();
2624
2625         // check, whether the last characters font has changed.
2626         if (rawparfont !=
2627             cursor.par()->getFontSettings(bv()->buffer()->params, lastpos - 1)) {
2628                 redoHeightOfParagraph();
2629         }
2630 }
2631
2632
2633 RowList::iterator LyXText::cursorRow() const
2634 {
2635         return getRow(cursor.par(), cursor.pos());
2636 }
2637
2638
2639 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2640 {
2641         return getRow(cur.par(), cur.pos());
2642 }
2643
2644
2645 RowList::iterator
2646 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
2647 {
2648         if (rows().empty())
2649                 return rowlist_.end();
2650
2651         // find the first row of the specified paragraph
2652         RowList::iterator rit = rowlist_.begin();
2653         RowList::iterator end = rowlist_.end();
2654         while (boost::next(rit) != end && rit->par() != pit) {
2655                 ++rit;
2656         }
2657
2658         // now find the wanted row
2659         while (rit->pos() < pos
2660                && boost::next(rit) != end
2661                && boost::next(rit)->par() == pit
2662                && boost::next(rit)->pos() <= pos) {
2663                 ++rit;
2664         }
2665
2666         return rit;
2667 }
2668
2669 // returns pointer to a specified row
2670 RowList::iterator
2671 LyXText::getRow(ParagraphList::iterator pit, pos_type pos, int & y) const
2672 {
2673         y = 0;
2674
2675         if (rows().empty())
2676                 return rowlist_.end();
2677
2678         // find the first row of the specified paragraph
2679         RowList::iterator rit = rowlist_.begin();
2680         RowList::iterator end = rowlist_.end();
2681         while (boost::next(rit) != end && rit->par() != pit) {
2682                 y += rit->height();
2683                 ++rit;
2684         }
2685
2686         // now find the wanted row
2687         while (rit->pos() < pos
2688                && boost::next(rit) != end
2689                && boost::next(rit)->par() == pit
2690                && boost::next(rit)->pos() <= pos) {
2691                 y += rit->height();
2692                 ++rit;
2693         }
2694
2695         return rit;
2696 }
2697
2698 // returns pointer to some fancy row 'below' specified row
2699 RowList::iterator LyXText::cursorIRow() const
2700 {
2701         int y = 0;
2702         return getRow(cursor.par(), cursor.pos(), y);
2703 }
2704
2705
2706 RowList::iterator LyXText::getRowNearY(int & y) const
2707 {
2708         RowList::iterator rit = anchor_row_;
2709         RowList::iterator const beg = rows().begin();
2710         RowList::iterator const end = rows().end();
2711
2712         if (rows().empty()) {
2713                 y = 0;
2714                 return end;
2715         }
2716         if (rit == end)
2717                 rit = beg;
2718
2719         int tmpy = rit->y();
2720
2721         if (tmpy <= y) {
2722                 while (rit != end && tmpy <= y) {
2723                         tmpy += rit->height();
2724                         ++rit;
2725                 }
2726                 if (rit != beg) {
2727                         --rit;
2728                         tmpy -= rit->height();
2729                 }
2730         } else {
2731                 while (rit != beg && tmpy > y) {
2732                         --rit;
2733                         tmpy -= rit->height();
2734                 }
2735         }
2736         if (tmpy < 0 || rit == end) {
2737                 tmpy = 0;
2738                 rit = beg;
2739         }
2740
2741         // return the rel y
2742         y = tmpy;
2743
2744         return rit;
2745 }
2746
2747
2748 int LyXText::getDepth() const
2749 {
2750         return cursor.par()->getDepth();
2751 }