]> git.lyx.org Git - lyx.git/blob - src/text.C
moved some converter/format functions to more appropriate places
[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                 int const tmpheight = row->height();
1802
1803                 setHeightOfRow(row);
1804                 postPaint();
1805
1806                 current_font = rawtmpfont;
1807                 real_current_font = realtmpfont;
1808                 setCursor(cursor.par(), cursor.pos() + 1, false,
1809                           cursor.boundary());
1810         }
1811
1812         // check, wether the last characters font has changed.
1813         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1814             && rawparfont != rawtmpfont) {
1815                 redoHeightOfParagraph();
1816         }
1817
1818         charInserted();
1819 }
1820
1821
1822 void LyXText::charInserted()
1823 {
1824         // Here we could call FinishUndo for every 20 characters inserted.
1825         // This is from my experience how emacs does it. (Lgb)
1826         static unsigned int counter;
1827         if (counter < 20) {
1828                 ++counter;
1829         } else {
1830                 finishUndo();
1831                 counter = 0;
1832         }
1833 }
1834
1835
1836 void LyXText::prepareToPrint(RowList::iterator rit, float & x,
1837                              float & fill_separator,
1838                              float & fill_hfill,
1839                              float & fill_label_hfill,
1840                              bool bidi) const
1841 {
1842         float w = rit->fill();
1843         fill_hfill = 0;
1844         fill_label_hfill = 0;
1845         fill_separator = 0;
1846         fill_label_hfill = 0;
1847
1848         ParagraphList::iterator pit = rit->par();
1849
1850         bool const is_rtl =
1851                 pit->isRightToLeftPar(bv()->buffer()->params);
1852         if (is_rtl) {
1853                 x = (workWidth() > 0)
1854                         ? rightMargin(*bv()->buffer(), *rit) : 0;
1855         } else
1856                 x = (workWidth() > 0)
1857                         ? leftMargin(*rit) : 0;
1858
1859         // is there a manual margin with a manual label
1860         LyXLayout_ptr const & layout = pit->layout();
1861
1862         if (layout->margintype == MARGIN_MANUAL
1863             && layout->labeltype == LABEL_MANUAL) {
1864                 /// We might have real hfills in the label part
1865                 float nlh = numberOfLabelHfills(*this, rit);
1866
1867                 // A manual label par (e.g. List) has an auto-hfill
1868                 // between the label text and the body of the
1869                 // paragraph too.
1870                 // But we don't want to do this auto hfill if the par
1871                 // is empty.
1872                 if (!pit->empty())
1873                         ++nlh;
1874
1875                 if (nlh && !pit->getLabelWidthString().empty()) {
1876                         fill_label_hfill = labelFill(*rit) / nlh;
1877                 }
1878         }
1879
1880         // are there any hfills in the row?
1881         float const nh = numberOfHfills(*this, rit);
1882
1883         if (nh) {
1884                 if (w > 0)
1885                         fill_hfill = w / nh;
1886         // we don't have to look at the alignment if it is ALIGN_LEFT and
1887         // if the row is already larger then the permitted width as then
1888         // we force the LEFT_ALIGN'edness!
1889         } else if (static_cast<int>(rit->width()) < workWidth()) {
1890                 // is it block, flushleft or flushright?
1891                 // set x how you need it
1892                 int align;
1893                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1894                         align = layout->align;
1895                 } else {
1896                         align = pit->params().align();
1897                 }
1898
1899                 // center displayed insets
1900                 Inset * inset = 0;
1901                 if (rit->pos() < pit->size()
1902                     && pit->isInset(rit->pos())
1903                     && (inset = pit->getInset(rit->pos()))
1904                     && (inset->display())) // || (inset->scroll() < 0)))
1905                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1906                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1907                 // ERT insets should always be LEFT ALIGNED on screen
1908                 inset = pit->inInset();
1909                 if (inset && inset->owner() &&
1910                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1911                 {
1912                         align = LYX_ALIGN_LEFT;
1913                 }
1914
1915                 switch (align) {
1916             case LYX_ALIGN_BLOCK:
1917             {
1918                         float const ns = numberOfSeparators(*this, rit);
1919                         RowList::iterator next_row = boost::next(rit);
1920                         ParagraphList::iterator next_pit = next_row->par();
1921
1922                         if (ns && next_row != rowlist_.end() &&
1923                             next_pit == pit &&
1924                             !(next_pit->isNewline(next_row->pos() - 1))
1925                             && !(next_pit->isInset(next_row->pos()) &&
1926                                  next_pit->getInset(next_row->pos()) &&
1927                                  next_pit->getInset(next_row->pos())->display())
1928                                 ) {
1929                                 fill_separator = w / ns;
1930                         } else if (is_rtl) {
1931                                 x += w;
1932                         }
1933                         break;
1934             }
1935             case LYX_ALIGN_RIGHT:
1936                         x += w;
1937                         break;
1938             case LYX_ALIGN_CENTER:
1939                         x += w / 2;
1940                         break;
1941                 }
1942         }
1943         if (!bidi)
1944                 return;
1945
1946         computeBidiTables(bv()->buffer(), rit);
1947         if (is_rtl) {
1948                 pos_type body_pos = pit->beginningOfBody();
1949                 pos_type last = lastPos(*this, rit);
1950
1951                 if (body_pos > 0 &&
1952                     (body_pos - 1 > last ||
1953                      !pit->isLineSeparator(body_pos - 1))) {
1954                         x += font_metrics::width(layout->labelsep,
1955                                             getLabelFont(bv()->buffer(),
1956                                                          pit));
1957                         if (body_pos - 1 <= last)
1958                                 x += fill_label_hfill;
1959                 }
1960         }
1961 }
1962
1963
1964 // important for the screen
1965
1966
1967 // the cursor set functions have a special mechanism. When they
1968 // realize, that you left an empty paragraph, they will delete it.
1969 // They also delete the corresponding row
1970
1971 void LyXText::cursorRightOneWord()
1972 {
1973         ::cursorRightOneWord(cursor, ownerParagraphs());
1974         setCursor(cursor.par(), cursor.pos());
1975 }
1976
1977
1978 // Skip initial whitespace at end of word and move cursor to *start*
1979 // of prior word, not to end of next prior word.
1980 void LyXText::cursorLeftOneWord()
1981 {
1982         LyXCursor tmpcursor = cursor;
1983         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
1984         setCursor(tmpcursor.par(), tmpcursor.pos());
1985 }
1986
1987
1988 void LyXText::selectWord(word_location loc)
1989 {
1990         LyXCursor from = cursor;
1991         LyXCursor to;
1992         ::getWord(from, to, loc, ownerParagraphs());
1993         if (cursor != from)
1994                 setCursor(from.par(), from.pos());
1995         if (to == from)
1996                 return;
1997         selection.cursor = cursor;
1998         setCursor(to.par(), to.pos());
1999         setSelection();
2000 }
2001
2002
2003 // Select the word currently under the cursor when no
2004 // selection is currently set
2005 bool LyXText::selectWordWhenUnderCursor(word_location loc)
2006 {
2007         if (!selection.set()) {
2008                 selectWord(loc);
2009                 return selection.set();
2010         }
2011         return false;
2012 }
2013
2014
2015 void LyXText::acceptChange()
2016 {
2017         if (!selection.set() && cursor.par()->size())
2018                 return;
2019
2020         if (selection.start.par() == selection.end.par()) {
2021                 LyXCursor & startc = selection.start;
2022                 LyXCursor & endc = selection.end;
2023                 setUndo(bv(), Undo::INSERT, startc.par());
2024                 startc.par()->acceptChange(startc.pos(), endc.pos());
2025                 finishUndo();
2026                 clearSelection();
2027                 redoParagraphs(startc, boost::next(startc.par()));
2028                 setCursorIntern(startc.par(), 0);
2029         }
2030 #warning handle multi par selection
2031 }
2032
2033
2034 void LyXText::rejectChange()
2035 {
2036         if (!selection.set() && cursor.par()->size())
2037                 return;
2038
2039         if (selection.start.par() == selection.end.par()) {
2040                 LyXCursor & startc = selection.start;
2041                 LyXCursor & endc = selection.end;
2042                 setUndo(bv(), Undo::INSERT, startc.par());
2043                 startc.par()->rejectChange(startc.pos(), endc.pos());
2044                 finishUndo();
2045                 clearSelection();
2046                 redoParagraphs(startc, boost::next(startc.par()));
2047                 setCursorIntern(startc.par(), 0);
2048         }
2049 #warning handle multi par selection
2050 }
2051
2052
2053 // This function is only used by the spellchecker for NextWord().
2054 // It doesn't handle LYX_ACCENTs and probably never will.
2055 WordLangTuple const
2056 LyXText::selectNextWordToSpellcheck(float & value)
2057 {
2058         if (the_locking_inset) {
2059                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
2060                 if (!word.word().empty()) {
2061                         value += float(cursor.y());
2062                         value /= float(height);
2063                         return word;
2064                 }
2065                 // we have to go on checking so move cursor to the next char
2066                 if (cursor.pos() == cursor.par()->size()) {
2067                         if (boost::next(cursor.par()) == ownerParagraphs().end())
2068                                 return word;
2069                         cursor.par(boost::next(cursor.par()));
2070                         cursor.pos(0);
2071                 } else
2072                         cursor.pos(cursor.pos() + 1);
2073         }
2074         ParagraphList::iterator tmppit = cursor.par();
2075
2076         // If this is not the very first word, skip rest of
2077         // current word because we are probably in the middle
2078         // of a word if there is text here.
2079         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
2080                 while (cursor.pos() < cursor.par()->size()
2081                        && cursor.par()->isLetter(cursor.pos()))
2082                         cursor.pos(cursor.pos() + 1);
2083         }
2084
2085         // Now, skip until we have real text (will jump paragraphs)
2086         while (true) {
2087                 ParagraphList::iterator cpit = cursor.par();
2088                 pos_type const cpos(cursor.pos());
2089
2090                 if (cpos == cpit->size()) {
2091                         if (boost::next(cpit) != ownerParagraphs().end()) {
2092                                 cursor.par(boost::next(cpit));
2093                                 cursor.pos(0);
2094                                 continue;
2095                         }
2096                         break;
2097                 }
2098
2099                 bool const is_good_inset = cpit->isInset(cpos)
2100                         && cpit->getInset(cpos)->allowSpellcheck();
2101
2102                 if (!isDeletedText(*cpit, cpos)
2103                     && (is_good_inset || cpit->isLetter(cpos)))
2104                         break;
2105
2106                 cursor.pos(cpos + 1);
2107         }
2108
2109         // now check if we hit an inset so it has to be a inset containing text!
2110         if (cursor.pos() < cursor.par()->size() &&
2111             cursor.par()->isInset(cursor.pos())) {
2112                 // lock the inset!
2113                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
2114                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
2115                 // now call us again to do the above trick
2116                 // but obviously we have to start from down below ;)
2117                 return bv()->text->selectNextWordToSpellcheck(value);
2118         }
2119
2120         // Update the value if we changed paragraphs
2121         if (cursor.par() != tmppit) {
2122                 setCursor(cursor.par(), cursor.pos());
2123                 value = float(cursor.y())/float(height);
2124         }
2125
2126         // Start the selection from here
2127         selection.cursor = cursor;
2128
2129         string lang_code(
2130                 getFont(bv()->buffer(), cursor.par(), cursor.pos())
2131                         .language()->code());
2132         // and find the end of the word (insets like optional hyphens
2133         // and ligature break are part of a word)
2134         while (cursor.pos() < cursor.par()->size()
2135                && cursor.par()->isLetter(cursor.pos())
2136                && !isDeletedText(*cursor.par(), cursor.pos()))
2137                 cursor.pos(cursor.pos() + 1);
2138
2139         // Finally, we copy the word to a string and return it
2140         string str;
2141         if (selection.cursor.pos() < cursor.pos()) {
2142                 pos_type i;
2143                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2144                         if (!cursor.par()->isInset(i))
2145                                 str += cursor.par()->getChar(i);
2146                 }
2147         }
2148         return WordLangTuple(str, lang_code);
2149 }
2150
2151
2152 // This one is also only for the spellchecker
2153 void LyXText::selectSelectedWord()
2154 {
2155         if (the_locking_inset) {
2156                 the_locking_inset->selectSelectedWord(bv());
2157                 return;
2158         }
2159         // move cursor to the beginning
2160         setCursor(selection.cursor.par(), selection.cursor.pos());
2161
2162         // set the sel cursor
2163         selection.cursor = cursor;
2164
2165         // now find the end of the word
2166         while (cursor.pos() < cursor.par()->size()
2167                && (cursor.par()->isLetter(cursor.pos())))
2168                 cursor.pos(cursor.pos() + 1);
2169
2170         setCursor(cursor.par(), cursor.pos());
2171
2172         // finally set the selection
2173         setSelection();
2174 }
2175
2176
2177 // Delete from cursor up to the end of the current or next word.
2178 void LyXText::deleteWordForward()
2179 {
2180         if (cursor.par()->empty())
2181                 cursorRight(bv());
2182         else {
2183                 LyXCursor tmpcursor = cursor;
2184                 selection.set(true); // to avoid deletion
2185                 cursorRightOneWord();
2186                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2187                 selection.cursor = cursor;
2188                 cursor = tmpcursor;
2189                 setSelection();
2190
2191                 // Great, CutSelection() gets rid of multiple spaces.
2192                 cutSelection(true, false);
2193         }
2194 }
2195
2196
2197 // Delete from cursor to start of current or prior word.
2198 void LyXText::deleteWordBackward()
2199 {
2200         if (cursor.par()->empty())
2201                 cursorLeft(bv());
2202         else {
2203                 LyXCursor tmpcursor = cursor;
2204                 selection.set(true); // to avoid deletion
2205                 cursorLeftOneWord();
2206                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2207                 selection.cursor = cursor;
2208                 cursor = tmpcursor;
2209                 setSelection();
2210                 cutSelection(true, false);
2211         }
2212 }
2213
2214
2215 // Kill to end of line.
2216 void LyXText::deleteLineForward()
2217 {
2218         if (cursor.par()->empty())
2219                 // Paragraph is empty, so we just go to the right
2220                 cursorRight(bv());
2221         else {
2222                 LyXCursor tmpcursor = cursor;
2223                 // We can't store the row over a regular setCursor
2224                 // so we set it to 0 and reset it afterwards.
2225                 selection.set(true); // to avoid deletion
2226                 cursorEnd();
2227                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2228                 selection.cursor = cursor;
2229                 cursor = tmpcursor;
2230                 setSelection();
2231                 // What is this test for ??? (JMarc)
2232                 if (!selection.set()) {
2233                         deleteWordForward();
2234                 } else {
2235                         cutSelection(true, false);
2236                 }
2237         }
2238 }
2239
2240
2241 void LyXText::changeCase(LyXText::TextCase action)
2242 {
2243         LyXCursor from;
2244         LyXCursor to;
2245
2246         if (selection.set()) {
2247                 from = selection.start;
2248                 to = selection.end;
2249         } else {
2250                 from = cursor;
2251                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
2252                 setCursor(to.par(), to.pos() + 1);
2253         }
2254
2255         setUndo(bv(), Undo::FINISH, from.par(), to.par());
2256
2257         pos_type pos = from.pos();
2258         ParagraphList::iterator pit = from.par();
2259
2260         while (pit != ownerParagraphs().end() &&
2261                (pos != to.pos() || pit != to.par())) {
2262                 if (pos == pit->size()) {
2263                         ++pit;
2264                         pos = 0;
2265                         continue;
2266                 }
2267                 unsigned char c = pit->getChar(pos);
2268                 if (!IsInsetChar(c)) {
2269                         switch (action) {
2270                         case text_lowercase:
2271                                 c = lowercase(c);
2272                                 break;
2273                         case text_capitalization:
2274                                 c = uppercase(c);
2275                                 action = text_lowercase;
2276                                 break;
2277                         case text_uppercase:
2278                                 c = uppercase(c);
2279                                 break;
2280                         }
2281                 }
2282 #warning changes
2283                 pit->setChar(pos, c);
2284                 checkParagraph(pit, pos);
2285
2286                 ++pos;
2287         }
2288
2289         if (getRow(to) != getRow(from))
2290                 postPaint();
2291 }
2292
2293
2294 void LyXText::Delete()
2295 {
2296         // this is a very easy implementation
2297
2298         LyXCursor old_cursor = cursor;
2299         int const old_cur_par_id = old_cursor.par()->id();
2300         int const old_cur_par_prev_id =
2301                 (old_cursor.par() != ownerParagraphs().begin() ?
2302                  boost::prior(old_cursor.par())->id() : -1);
2303
2304         // just move to the right
2305         cursorRight(bv());
2306
2307         // CHECK Look at the comment here.
2308         // This check is not very good...
2309         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2310         // and that can very well delete the par or par->previous in
2311         // old_cursor. Will a solution where we compare paragraph id's
2312         //work better?
2313         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
2314             == old_cur_par_prev_id
2315             && cursor.par()->id() != old_cur_par_id) {
2316                 // delete-empty-paragraph-mechanism has done it
2317                 return;
2318         }
2319
2320         // if you had success make a backspace
2321         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2322                 LyXCursor tmpcursor = cursor;
2323                 // to make sure undo gets the right cursor position
2324                 cursor = old_cursor;
2325                 setUndo(bv(), Undo::DELETE, cursor.par());
2326                 cursor = tmpcursor;
2327                 backspace();
2328         }
2329 }
2330
2331
2332 void LyXText::backspace()
2333 {
2334         // Get the font that is used to calculate the baselineskip
2335         pos_type lastpos = cursor.par()->size();
2336         LyXFont rawparfont =
2337                 cursor.par()->getFontSettings(bv()->buffer()->params,
2338                                               lastpos - 1);
2339
2340         if (cursor.pos() == 0) {
2341                 // The cursor is at the beginning of a paragraph,
2342                 // so the the backspace will collapse two paragraphs into one.
2343
2344                 // but it's not allowed unless it's new
2345                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2346                         return;
2347
2348                 // we may paste some paragraphs
2349
2350                 // is it an empty paragraph?
2351
2352                 if ((lastpos == 0
2353                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2354                         // This is an empty paragraph and we delete it just by moving the cursor one step
2355                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2356                         // of the paragraph.
2357
2358                         if (cursor.par() != ownerParagraphs().begin()) {
2359                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
2360                                 if (cursor.par()->layout() == tmppit->layout()
2361                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2362                                         // Inherit bottom DTD from the paragraph below.
2363                                         // (the one we are deleting)
2364                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
2365                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
2366                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2367                                 }
2368
2369                                 cursorLeft(bv());
2370
2371                                 // the layout things can change the height of a row !
2372                                 int const tmpheight = cursorRow()->height();
2373                                 setHeightOfRow(cursorRow());
2374                                 if (cursorRow()->height() != tmpheight)
2375                                         postPaint();
2376                                 return;
2377                         }
2378                 }
2379
2380                 if (cursor.par() != ownerParagraphs().begin()) {
2381                         setUndo(bv(), Undo::DELETE,
2382                                 boost::prior(cursor.par()),
2383                                 cursor.par());
2384                 }
2385
2386                 ParagraphList::iterator tmppit = cursor.par();
2387                 RowList::iterator tmprow = cursorRow();
2388
2389                 // We used to do cursorLeftIntern() here, but it is
2390                 // not a good idea since it triggers the auto-delete
2391                 // mechanism. So we do a cursorLeftIntern()-lite,
2392                 // without the dreaded mechanism. (JMarc)
2393                 if (cursor.par() != ownerParagraphs().begin()) {
2394                         // steps into the above paragraph.
2395                         setCursorIntern(boost::prior(cursor.par()),
2396                                         boost::prior(cursor.par())->size(),
2397                                         false);
2398                 }
2399
2400                 // Pasting is not allowed, if the paragraphs have different
2401                 // layout. I think it is a real bug of all other
2402                 // word processors to allow it. It confuses the user.
2403                 // Even so with a footnote paragraph and a non-footnote
2404                 // paragraph. I will not allow pasting in this case,
2405                 // because the user would be confused if the footnote behaves
2406                 // different wether it is open or closed.
2407
2408                 //      Correction: Pasting is always allowed with standard-layout
2409                 LyXTextClass const & tclass =
2410                         bv()->buffer()->params.getLyXTextClass();
2411
2412                 if (cursor.par() != tmppit
2413                     && (cursor.par()->layout() == tmppit->layout()
2414                         || tmppit->layout() == tclass.defaultLayout())
2415                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2416                         removeParagraph(tmprow);
2417                         removeRow(tmprow);
2418                         mergeParagraph(bv()->buffer()->params, bv()->buffer()->paragraphs, cursor.par());
2419
2420                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2421                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2422                         // strangely enough it seems that commenting out the line above removes
2423                         // most or all of the segfaults. I will however also try to move the
2424                         // two Remove... lines in front of the PasteParagraph too.
2425                         else
2426                                 if (cursor.pos())
2427                                         cursor.pos(cursor.pos() - 1);
2428
2429                         postPaint();
2430
2431                         // remove the lost paragraph
2432                         // This one is not safe, since the paragraph that the tmprow and the
2433                         // following rows belong to has been deleted by the PasteParagraph
2434                         // above. The question is... could this be moved in front of the
2435                         // PasteParagraph?
2436                         //RemoveParagraph(tmprow);
2437                         //RemoveRow(tmprow);
2438
2439                         // This rebuilds the rows.
2440                         appendParagraph(cursorRow());
2441                         updateCounters();
2442
2443                         // the row may have changed, block, hfills etc.
2444                         setCursor(cursor.par(), cursor.pos(), false);
2445                 }
2446         } else {
2447                 // this is the code for a normal backspace, not pasting
2448                 // any paragraphs
2449                 setUndo(bv(), Undo::DELETE, cursor.par());
2450                 // We used to do cursorLeftIntern() here, but it is
2451                 // not a good idea since it triggers the auto-delete
2452                 // mechanism. So we do a cursorLeftIntern()-lite,
2453                 // without the dreaded mechanism. (JMarc)
2454                 setCursorIntern(cursor.par(), cursor.pos()- 1,
2455                                 false, cursor.boundary());
2456
2457                 if (cursor.par()->isInset(cursor.pos())) {
2458                         // force complete redo when erasing display insets
2459                         // this is a cruel method but safe..... Matthias
2460                         if (cursor.par()->getInset(cursor.pos())->display() ||
2461                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2462                                 cursor.par()->erase(cursor.pos());
2463                                 redoParagraph();
2464                                 return;
2465                         }
2466                 }
2467
2468                 RowList::iterator row = cursorRow();
2469                 int y = cursor.y() - row->baseline();
2470                 pos_type z;
2471                 // remember that a space at the end of a row doesnt count
2472                 // when calculating the fill
2473                 if (cursor.pos() < lastPos(*this, row) ||
2474                     !cursor.par()->isLineSeparator(cursor.pos())) {
2475                         row->fill(row->fill() + singleWidth(
2476                                                             cursor.par(),
2477                                                             cursor.pos()));
2478                 }
2479
2480                 // some special code when deleting a newline. This is similar
2481                 // to the behavior when pasting paragraphs
2482                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2483                         cursor.par()->erase(cursor.pos());
2484                         // refresh the positions
2485                         RowList::iterator tmprow = row;
2486                         while (boost::next(tmprow) != rows().end() &&
2487                                boost::next(tmprow)->par() == row->par()) {
2488                                 ++tmprow;
2489                                 tmprow->pos(tmprow->pos() - 1);
2490                         }
2491                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2492                                 cursor.pos(cursor.pos() - 1);
2493
2494                         if (cursor.pos() < cursor.par()->size()
2495                             && !cursor.par()->isSeparator(cursor.pos())) {
2496                                 cursor.par()->insertChar(cursor.pos(), ' ');
2497                                 setCharFont(bv()->buffer(), cursor.par(),
2498                                             cursor.pos(), current_font);
2499                                 // refresh the positions
2500                                 tmprow = row;
2501                                 while (boost::next(tmprow) != rows().end() &&
2502                                        boost::next(tmprow)->par() == row->par()) {
2503                                         ++tmprow;
2504                                         tmprow->pos(tmprow->pos() + 1);
2505                                 }
2506                         }
2507                 } else {
2508                         cursor.par()->erase(cursor.pos());
2509
2510                         // refresh the positions
2511                         RowList::iterator tmprow = row;
2512                         while (boost::next(tmprow) != rows().end() &&
2513                                boost::next(tmprow)->par() == row->par()) {
2514                                 ++tmprow;
2515                                 tmprow->pos(tmprow->pos() - 1);
2516                         }
2517
2518                         // delete newlines at the beginning of paragraphs
2519                         while (!cursor.par()->empty() &&
2520                                cursor.pos() < cursor.par()->size() &&
2521                                cursor.par()->isNewline(cursor.pos()) &&
2522                                cursor.pos() == cursor.par()->beginningOfBody()) {
2523                                 cursor.par()->erase(cursor.pos());
2524                                 // refresh the positions
2525                                 tmprow = row;
2526                                 while (boost::next(tmprow) != rows().end() &&
2527                                        boost::next(tmprow)->par() == row->par()) {
2528                                         ++tmprow;
2529                                         tmprow->pos(tmprow->pos() - 1);
2530                                 }
2531                         }
2532                 }
2533
2534                 // is there a break one row above
2535                 if (row != rows().begin() && boost::prior(row)->par() == row->par()) {
2536                         z = rowBreakPoint(*boost::prior(row));
2537                         if (z >= row->pos()) {
2538                                 row->pos(z + 1);
2539
2540                                 RowList::iterator tmprow = boost::prior(row);
2541
2542                                 // maybe the current row is now empty
2543                                 if (row->pos() >= row->par()->size()) {
2544                                         // remove it
2545                                         removeRow(row);
2546                                         need_break_row = rows().end();
2547                                 } else {
2548                                         breakAgainOneRow(row);
2549                                         if (boost::next(row) != rows().end() &&
2550                                             boost::next(row)->par() == row->par())
2551                                                 need_break_row = boost::next(row);
2552                                         else
2553                                                 need_break_row = rows().end();
2554                                 }
2555
2556                                 // set the dimensions of the row above
2557                                 y -= tmprow->height();
2558                                 tmprow->fill(fill(tmprow, workWidth()));
2559                                 setHeightOfRow(tmprow);
2560                                 postPaint();
2561
2562                                 setCursor(cursor.par(), cursor.pos(),
2563                                           false, cursor.boundary());
2564                                 //current_font = rawtmpfont;
2565                                 //real_current_font = realtmpfont;
2566                                 // check, whether the last character's font has changed.
2567                                 if (rawparfont !=
2568                                     cursor.par()->getFontSettings(bv()->buffer()->params,
2569                                                                   cursor.par()->size() - 1))
2570                                         redoHeightOfParagraph();
2571                                 return;
2572                         }
2573                 }
2574
2575                 // break the cursor row again
2576                 if (boost::next(row) != rows().end() &&
2577                     boost::next(row)->par() == row->par() &&
2578                     (lastPos(*this, row) == row->par()->size() - 1 ||
2579                      rowBreakPoint(*row) != lastPos(*this, row))) {
2580
2581                         // it can happen that a paragraph loses one row
2582                         // without a real breakup. This is when a word
2583                         // is to long to be broken. Well, I don t care this
2584                         // hack ;-)
2585                         if (lastPos(*this, row) == row->par()->size() - 1)
2586                                 removeRow(boost::next(row));
2587
2588                         postPaint();
2589
2590                         breakAgainOneRow(row);
2591                         // will the cursor be in another row now?
2592                         if (boost::next(row) != rows().end() &&
2593                             boost::next(row)->par() == row->par() &&
2594                             lastPos(*this, row) <= cursor.pos()) {
2595                                 ++row;
2596                                 breakAgainOneRow(row);
2597                         }
2598
2599                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2600
2601                         if (boost::next(row) != rows().end() &&
2602                             boost::next(row)->par() == row->par())
2603                                 need_break_row = boost::next(row);
2604                         else
2605                                 need_break_row = rows().end();
2606                 } else  {
2607                         // set the dimensions of the row
2608                         row->fill(fill(row, workWidth()));
2609                         int const tmpheight = row->height();
2610                         setHeightOfRow(row);
2611                         postPaint();
2612                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2613                 }
2614         }
2615
2616         // current_font = rawtmpfont;
2617         // real_current_font = realtmpfont;
2618
2619         if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
2620             != cursor.boundary())
2621                 setCursor(cursor.par(), cursor.pos(), false,
2622                           !cursor.boundary());
2623
2624         lastpos = cursor.par()->size();
2625         if (cursor.pos() == lastpos)
2626                 setCurrentFont();
2627
2628         // check, whether the last characters font has changed.
2629         if (rawparfont !=
2630             cursor.par()->getFontSettings(bv()->buffer()->params, lastpos - 1)) {
2631                 redoHeightOfParagraph();
2632         }
2633 }
2634
2635
2636 RowList::iterator LyXText::cursorRow() const
2637 {
2638         return getRow(cursor.par(), cursor.pos());
2639 }
2640
2641
2642 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2643 {
2644         return getRow(cur.par(), cur.pos());
2645 }
2646
2647
2648 RowList::iterator
2649 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
2650 {
2651         if (rows().empty())
2652                 return rowlist_.end();
2653
2654         // find the first row of the specified paragraph
2655         RowList::iterator rit = rowlist_.begin();
2656         RowList::iterator end = rowlist_.end();
2657         while (boost::next(rit) != end && rit->par() != pit) {
2658                 ++rit;
2659         }
2660
2661         // now find the wanted row
2662         while (rit->pos() < pos
2663                && boost::next(rit) != end
2664                && boost::next(rit)->par() == pit
2665                && boost::next(rit)->pos() <= pos) {
2666                 ++rit;
2667         }
2668
2669         return rit;
2670 }
2671
2672 // returns pointer to a specified row
2673 RowList::iterator
2674 LyXText::getRow(ParagraphList::iterator pit, pos_type pos, int & y) const
2675 {
2676         y = 0;
2677
2678         if (rows().empty())
2679                 return rowlist_.end();
2680
2681         // find the first row of the specified paragraph
2682         RowList::iterator rit = rowlist_.begin();
2683         RowList::iterator end = rowlist_.end();
2684         while (boost::next(rit) != end && rit->par() != pit) {
2685                 y += rit->height();
2686                 ++rit;
2687         }
2688
2689         // now find the wanted row
2690         while (rit->pos() < pos
2691                && boost::next(rit) != end
2692                && boost::next(rit)->par() == pit
2693                && boost::next(rit)->pos() <= pos) {
2694                 y += rit->height();
2695                 ++rit;
2696         }
2697
2698         return rit;
2699 }
2700
2701 // returns pointer to some fancy row 'below' specified row
2702 RowList::iterator LyXText::cursorIRow() const
2703 {
2704         int y = 0;
2705         return getRow(cursor.par(), cursor.pos(), y);
2706 }
2707
2708
2709 RowList::iterator LyXText::getRowNearY(int & y) const
2710 {
2711         RowList::iterator rit = anchor_row_;
2712         RowList::iterator const beg = rows().begin();
2713         RowList::iterator const end = rows().end();
2714
2715         if (rows().empty()) {
2716                 y = 0;
2717                 return end;
2718         }
2719         if (rit == end)
2720                 rit = beg;
2721
2722         int tmpy = rit->y();
2723
2724         if (tmpy <= y) {
2725                 while (rit != end && tmpy <= y) {
2726                         tmpy += rit->height();
2727                         ++rit;
2728                 }
2729                 if (rit != beg) {
2730                         --rit;
2731                         tmpy -= rit->height();
2732                 }
2733         } else {
2734                 while (rit != beg && tmpy > y) {
2735                         --rit;
2736                         tmpy -= rit->height();
2737                 }
2738         }
2739         if (tmpy < 0 || rit == end) {
2740                 tmpy = 0;
2741                 rit = beg;
2742         }
2743
2744         // return the rel y
2745         y = tmpy;
2746
2747         return rit;
2748 }
2749
2750
2751 int LyXText::getDepth() const
2752 {
2753         return cursor.par()->getDepth();
2754 }