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