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