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