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