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