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