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