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