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