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