]> git.lyx.org Git - lyx.git/blob - src/text.C
remove pointless 2nd arg to setHeightOfParagraph
[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                 if (firstpar->params().startOfAppendix())
1074                         maxasc += 3 * defaultRowHeight();
1075
1076                 // This is special code for the chapter, since the label of this
1077                 // layout is printed in an extra row
1078                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1079                         && bview->buffer()->params.secnumdepth >= 0)
1080                 {
1081                         float spacing_val = 1.0;
1082                         if (!row->par()->params().spacing().isDefault()) {
1083                                 spacing_val = row->par()->params().spacing().getValue();
1084                         } else {
1085                                 spacing_val = bview->buffer()->params.spacing.getValue();
1086                         }
1087
1088                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1089                                          layout->spacing.getValue() *
1090                                          spacing_val)
1091                                 + int(font_metrics::maxAscent(labelfont) *
1092                                       layout->spacing.getValue() *
1093                                       spacing_val);
1094                 }
1095
1096                 // special code for the top label
1097                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1098                      || layout->labeltype == LABEL_BIBLIO
1099                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1100                     && row->par()->isFirstInSequence()
1101                     && !row->par()->getLabelstring().empty())
1102                 {
1103                         float spacing_val = 1.0;
1104                         if (!row->par()->params().spacing().isDefault()) {
1105                                 spacing_val = row->par()->params().spacing().getValue();
1106                         } else {
1107                                 spacing_val = bview->buffer()->params.spacing.getValue();
1108                         }
1109
1110                         labeladdon = int(
1111                                 (font_metrics::maxAscent(labelfont) *
1112                                  layout->spacing.getValue() *
1113                                  spacing_val)
1114                                 +(font_metrics::maxDescent(labelfont) *
1115                                   layout->spacing.getValue() *
1116                                   spacing_val)
1117                                 + layout->topsep * defaultRowHeight()
1118                                 + layout->labelbottomsep * defaultRowHeight());
1119                 }
1120
1121                 // and now the layout spaces, for example before and after a section,
1122                 // or between the items of a itemize or enumerate environment
1123
1124                 if (!firstpar->params().pagebreakTop()) {
1125                         Paragraph * prev = row->par()->previous();
1126                         if (prev)
1127                                 prev = row->par()->depthHook(row->par()->getDepth());
1128                         if (prev && prev->layout() == firstpar->layout() &&
1129                                 prev->getDepth() == firstpar->getDepth() &&
1130                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1131                         {
1132                                 layoutasc = (layout->itemsep * defaultRowHeight());
1133                         } else if (row->previous()) {
1134                                 tmptop = layout->topsep;
1135
1136                                 if (row->previous()->par()->getDepth() >= row->par()->getDepth())
1137                                         tmptop -= row->previous()->par()->layout()->bottomsep;
1138
1139                                 if (tmptop > 0)
1140                                         layoutasc = (tmptop * defaultRowHeight());
1141                         } else if (row->par()->params().lineTop()) {
1142                                 tmptop = layout->topsep;
1143
1144                                 if (tmptop > 0)
1145                                         layoutasc = (tmptop * defaultRowHeight());
1146                         }
1147
1148                         prev = row->par()->outerHook();
1149                         if (prev)  {
1150                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1151                         } else {
1152                                 if (firstpar->previous() &&
1153                                         firstpar->previous()->getDepth() == 0 &&
1154                                         firstpar->previous()->layout() !=
1155                                         firstpar->layout())
1156                                 {
1157                                         // avoid parsep
1158                                 } else if (firstpar->previous()) {
1159                                         maxasc += int(layout->parsep * defaultRowHeight());
1160                                 }
1161                         }
1162                 }
1163         }
1164
1165         // is it a bottom line?
1166         if (row->par() == par
1167                 && (!row->next() || row->next()->par() != row->par())) {
1168                 // the bottom margin
1169                 if (!par->next() && isTopLevel())
1170                         maxdesc += PAPER_MARGIN;
1171
1172                 // add the vertical spaces, that the user added
1173                 maxdesc += getLengthMarkerHeight(*bview, firstpar->params().spaceBottom());
1174
1175                 // do not forget the DTP-lines!
1176                 // there height depends on the font of the nearest character
1177                 if (firstpar->params().lineBottom())
1178                         maxdesc += 2 * font_metrics::ascent('x',
1179                                                        getFont(bview->buffer(),
1180                                                                par,
1181                                                                max(pos_type(0), par->size() - 1)));
1182
1183                 // and now the pagebreaks
1184                 if (firstpar->params().pagebreakBottom())
1185                         maxdesc += 3 * defaultRowHeight();
1186
1187                 // and now the layout spaces, for example before and after
1188                 // a section, or between the items of a itemize or enumerate
1189                 // environment
1190                 if (!firstpar->params().pagebreakBottom()
1191                     && row->par()->next()) {
1192                         Paragraph * nextpar = row->par()->next();
1193                         Paragraph * comparepar = row->par();
1194                         float usual = 0;
1195                         float unusual = 0;
1196
1197                         if (comparepar->getDepth() > nextpar->getDepth()) {
1198                                 usual = (comparepar->layout()->bottomsep * defaultRowHeight());
1199                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1200                                 if (comparepar->layout()!= nextpar->layout()
1201                                         || nextpar->getLabelWidthString() !=
1202                                         comparepar->getLabelWidthString())
1203                                 {
1204                                         unusual = (comparepar->layout()->bottomsep * defaultRowHeight());
1205                                 }
1206                                 if (unusual > usual)
1207                                         layoutdesc = unusual;
1208                                 else
1209                                         layoutdesc = usual;
1210                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1211
1212                                 if (comparepar->layout() != nextpar->layout()
1213                                         || nextpar->getLabelWidthString() !=
1214                                         comparepar->getLabelWidthString())
1215                                         layoutdesc = int(comparepar->layout()->bottomsep * defaultRowHeight());
1216                         }
1217                 }
1218         }
1219
1220         // incalculate the layout spaces
1221         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1222         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1223
1224         // calculate the new height of the text
1225         height -= row->height();
1226
1227         row->height(maxasc + maxdesc + labeladdon);
1228         row->baseline(maxasc + labeladdon);
1229
1230         height += row->height();
1231
1232         row->top_of_text(row->baseline() - font_metrics::maxAscent(font));
1233
1234         float x = 0;
1235         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1236                 float dummy;
1237                 // this IS needed
1238                 row->width(maxwidth);
1239                 prepareToPrint(bview, row, x, dummy, dummy, dummy, false);
1240         }
1241         row->width(int(maxwidth + x));
1242         if (inset_owner) {
1243                 Row * r = firstrow;
1244                 width = max(0, workWidth(*bview));
1245                 while (r) {
1246                         if (r->width() > width)
1247                                 width = r->width();
1248                         r = r->next();
1249                 }
1250         }
1251 }
1252
1253
1254 // Appends the implicit specified paragraph before the specified row,
1255 // start at the implicit given position
1256 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1257 {
1258         pos_type const last = row->par()->size();
1259         bool done = false;
1260
1261         do {
1262                 pos_type z = rowBreakPoint(*bview, *row);
1263
1264                 Row * tmprow = row;
1265
1266                 if (z < last) {
1267                         ++z;
1268                         insertRow(row, row->par(), z);
1269                         row = row->next();
1270                         row->height(0);
1271                 } else {
1272                         done = true;
1273                 }
1274
1275                 // Set the dimensions of the row
1276                 // fixed fill setting now by calling inset->update() in
1277                 // SingleWidth when needed!
1278                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1279                 setHeightOfRow(bview, tmprow);
1280
1281         } while (!done);
1282 }
1283
1284
1285 // Do we even need this at all ? Code that uses  RowPainter *already*
1286 // sets need_break_row when it sees a CHANGED_IN_DRAW, though not
1287 // quite like this
1288 void LyXText::markChangeInDraw(BufferView * bv, Row * row, Row * prev)
1289 {
1290         if (prev && prev->par() == row->par()) {
1291                 breakAgainOneRow(bv, prev);
1292                 if (prev->next() != row) {
1293                         // breakAgainOneRow() has removed row_
1294                         need_break_row = prev;
1295                 } else {
1296                         need_break_row = row;
1297                 }
1298         } else if (!prev) {
1299                 need_break_row = firstrow;
1300         } else {
1301                 need_break_row = prev->next();
1302         }
1303         setCursor(bv, cursor.par(), cursor.pos());
1304         /* FIXME */
1305 }
1306
1307
1308 void LyXText::breakAgain(BufferView * bview, Row * row) const
1309 {
1310         bool not_ready = true;
1311
1312         do  {
1313                 pos_type z = rowBreakPoint(*bview, *row);
1314                 Row * tmprow = row;
1315
1316                 if (z < row->par()->size()) {
1317                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1318                                 // insert a new row
1319                                 ++z;
1320                                 insertRow(row, row->par(), z);
1321                                 row = row->next();
1322                                 row->height(0);
1323                         } else  {
1324                                 row = row->next();
1325                                 ++z;
1326                                 if (row->pos() == z)
1327                                         not_ready = false;     // the rest will not change
1328                                 else {
1329                                         row->pos(z);
1330                                 }
1331                         }
1332                 } else {
1333                         // if there are some rows too much, delete them
1334                         // only if you broke the whole paragraph!
1335                         Row * tmprow2 = row;
1336                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1337                                 tmprow2 = tmprow2->next();
1338                         }
1339                         while (tmprow2 != row) {
1340                                 tmprow2 = tmprow2->previous();
1341                                 removeRow(tmprow2->next());
1342                         }
1343                         not_ready = false;
1344                 }
1345
1346                 // set the dimensions of the row
1347                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1348                 setHeightOfRow(bview, tmprow);
1349         } while (not_ready);
1350 }
1351
1352
1353 // this is just a little changed version of break again
1354 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1355 {
1356         pos_type z = rowBreakPoint(*bview, *row);
1357         Row * tmprow = row;
1358
1359         if (z < row->par()->size()) {
1360                 if (!row->next()
1361                     || (row->next() && row->next()->par() != row->par())) {
1362                         // insert a new row
1363                         ++z;
1364                         insertRow(row, row->par(), z);
1365                         row = row->next();
1366                         row->height(0);
1367                 } else  {
1368                         row = row->next();
1369                         ++z;
1370                         if (row->pos() != z)
1371                                 row->pos(z);
1372                 }
1373         } else {
1374                 // if there are some rows too much, delete them
1375                 // only if you broke the whole paragraph!
1376                 Row * tmprow2 = row;
1377                 while (tmprow2->next()
1378                        && tmprow2->next()->par() == row->par()) {
1379                         tmprow2 = tmprow2->next();
1380                 }
1381                 while (tmprow2 != row) {
1382                         tmprow2 = tmprow2->previous();
1383                         removeRow(tmprow2->next());
1384                 }
1385         }
1386
1387         // set the dimensions of the row
1388         tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1389         setHeightOfRow(bview, tmprow);
1390 }
1391
1392
1393 void LyXText::breakParagraph(BufferView * bview,
1394                              ParagraphList & paragraphs, char keep_layout)
1395 {
1396         // allow only if at start or end, or all previous is new text
1397         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1398                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1399                 return;
1400
1401         LyXTextClass const & tclass =
1402                 bview->buffer()->params.getLyXTextClass();
1403         LyXLayout_ptr const & layout = cursor.par()->layout();
1404
1405         // this is only allowed, if the current paragraph is not empty or caption
1406         // and if it has not the keepempty flag aktive
1407         if (cursor.par()->empty()
1408            && layout->labeltype != LABEL_SENSITIVE
1409            && !layout->keepempty)
1410                 return;
1411
1412         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1413
1414         // Always break behind a space
1415         //
1416         // It is better to erase the space (Dekel)
1417         if (cursor.pos() < cursor.par()->size()
1418              && cursor.par()->isLineSeparator(cursor.pos()))
1419            cursor.par()->erase(cursor.pos());
1420         // cursor.pos(cursor.pos() + 1);
1421
1422         // break the paragraph
1423         if (keep_layout)
1424                 keep_layout = 2;
1425         else
1426                 keep_layout = layout->isEnvironment();
1427
1428         // we need to set this before we insert the paragraph. IMO the
1429         // breakParagraph call should return a bool if it inserts the
1430         // paragraph before or behind and we should react on that one
1431         // but we can fix this in 1.3.0 (Jug 20020509)
1432         bool const isempty = (layout->keepempty && cursor.par()->empty());
1433         ::breakParagraph(bview->buffer()->params, paragraphs, cursor.par(), cursor.pos(),
1434                        keep_layout);
1435
1436         // well this is the caption hack since one caption is really enough
1437         if (layout->labeltype == LABEL_SENSITIVE) {
1438                 if (!cursor.pos())
1439                         // set to standard-layout
1440                         cursor.par()->applyLayout(tclass.defaultLayout());
1441                 else
1442                         // set to standard-layout
1443                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1444         }
1445
1446         // if the cursor is at the beginning of a row without prior newline,
1447         // move one row up!
1448         // This touches only the screen-update. Otherwise we would may have
1449         // an empty row on the screen
1450         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1451                          && cursor.row()->pos() == cursor.pos())
1452         {
1453                 cursorLeft(bview);
1454         }
1455
1456         status(bview, LyXText::NEED_MORE_REFRESH);
1457         refresh_row = cursor.row();
1458         refresh_y = cursor.y() - cursor.row()->baseline();
1459
1460         // Do not forget the special right address boxes
1461         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1462                 while (refresh_row->previous() &&
1463                        refresh_row->previous()->par() == refresh_row->par())
1464                 {
1465                         refresh_row = refresh_row->previous();
1466                         refresh_y -= refresh_row->height();
1467                 }
1468         }
1469         removeParagraph(cursor.row());
1470
1471         // set the dimensions of the cursor row
1472         cursor.row()->fill(fill(*bview, *cursor.row(), workWidth(*bview)));
1473
1474         setHeightOfRow(bview, cursor.row());
1475
1476 #warning Trouble Point! (Lgb)
1477         // When ::breakParagraph is called from within an inset we must
1478         // ensure that the correct ParagraphList is used. Today that is not
1479         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1480         while (!cursor.par()->next()->empty()
1481           && cursor.par()->next()->isNewline(0))
1482            cursor.par()->next()->erase(0);
1483
1484         insertParagraph(bview, cursor.par()->next(), cursor.row());
1485
1486         updateCounters(bview);
1487
1488         // This check is necessary. Otherwise the new empty paragraph will
1489         // be deleted automatically. And it is more friendly for the user!
1490         if (cursor.pos() || isempty)
1491                 setCursor(bview, cursor.par()->next(), 0);
1492         else
1493                 setCursor(bview, cursor.par(), 0);
1494
1495         if (cursor.row()->next())
1496                 breakAgain(bview, cursor.row()->next());
1497
1498         need_break_row = 0;
1499 }
1500
1501
1502 // Just a macro to make some thing easier.
1503 void LyXText::redoParagraph(BufferView * bview) const
1504 {
1505         clearSelection();
1506         redoParagraphs(bview, cursor, cursor.par()->next());
1507         setCursorIntern(bview, cursor.par(), cursor.pos());
1508 }
1509
1510
1511 // insert a character, moves all the following breaks in the
1512 // same Paragraph one to the right and make a rebreak
1513 void LyXText::insertChar(BufferView * bview, char c)
1514 {
1515         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1516
1517         // When the free-spacing option is set for the current layout,
1518         // disable the double-space checking
1519
1520         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1521                 cursor.row()->par()->isFreeSpacing();
1522
1523         if (lyxrc.auto_number) {
1524                 static string const number_operators = "+-/*";
1525                 static string const number_unary_operators = "+-";
1526                 static string const number_seperators = ".,:";
1527
1528                 if (current_font.number() == LyXFont::ON) {
1529                         if (!IsDigit(c) && !contains(number_operators, c) &&
1530                             !(contains(number_seperators, c) &&
1531                               cursor.pos() >= 1 &&
1532                               cursor.pos() < cursor.par()->size() &&
1533                               getFont(bview->buffer(),
1534                                       cursor.par(),
1535                                       cursor.pos()).number() == LyXFont::ON &&
1536                               getFont(bview->buffer(),
1537                                       cursor.par(),
1538                                       cursor.pos() - 1).number() == LyXFont::ON)
1539                            )
1540                                 number(bview); // Set current_font.number to OFF
1541                 } else if (IsDigit(c) &&
1542                            real_current_font.isVisibleRightToLeft()) {
1543                         number(bview); // Set current_font.number to ON
1544
1545                         if (cursor.pos() > 0) {
1546                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1547                                 if (contains(number_unary_operators, c) &&
1548                                     (cursor.pos() == 1 ||
1549                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1550                                      cursor.par()->isNewline(cursor.pos() - 2))
1551                                   ) {
1552                                         setCharFont(bview->buffer(),
1553                                                     cursor.par(),
1554                                                     cursor.pos() - 1,
1555                                                     current_font);
1556                                 } else if (contains(number_seperators, c) &&
1557                                            cursor.pos() >= 2 &&
1558                                            getFont(bview->buffer(),
1559                                                    cursor.par(),
1560                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1561                                         setCharFont(bview->buffer(),
1562                                                     cursor.par(),
1563                                                     cursor.pos() - 1,
1564                                                     current_font);
1565                                 }
1566                         }
1567                 }
1568         }
1569
1570
1571         // First check, if there will be two blanks together or a blank at
1572         // the beginning of a paragraph.
1573         // I decided to handle blanks like normal characters, the main
1574         // difference are the special checks when calculating the row.fill
1575         // (blank does not count at the end of a row) and the check here
1576
1577         // The bug is triggered when we type in a description environment:
1578         // The current_font is not changed when we go from label to main text
1579         // and it should (along with realtmpfont) when we type the space.
1580         // CHECK There is a bug here! (Asger)
1581
1582         LyXFont realtmpfont = real_current_font;
1583         LyXFont rawtmpfont = current_font;
1584         // store the current font.  This is because of the use of cursor
1585         // movements. The moving cursor would refresh the current font
1586
1587         // Get the font that is used to calculate the baselineskip
1588         pos_type const lastpos = cursor.par()->size();
1589         LyXFont rawparfont =
1590                 cursor.par()->getFontSettings(bview->buffer()->params,
1591                                               lastpos - 1);
1592
1593         bool jumped_over_space = false;
1594
1595         if (!freeSpacing && IsLineSeparatorChar(c)) {
1596                 if ((cursor.pos() > 0
1597                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1598                     || (cursor.pos() > 0
1599                         && cursor.par()->isNewline(cursor.pos() - 1))
1600                     || (cursor.pos() == 0)) {
1601                         static bool sent_space_message = false;
1602                         if (!sent_space_message) {
1603                                 if (cursor.pos() == 0)
1604                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1605                                 else
1606                                         bview->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1607                                 sent_space_message = true;
1608                         }
1609                         charInserted();
1610                         return;
1611                 }
1612         }
1613
1614         // the display inset stuff
1615         if (cursor.row()->pos() < cursor.row()->par()->size()
1616             && cursor.row()->par()->isInset(cursor.row()->pos())) {
1617                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1618                 if (inset && (inset->display() || inset->needFullRow())) {
1619                         // force a new break
1620                         cursor.row()->fill(-1); // to force a new break
1621                 }
1622         }
1623
1624         // get the cursor row fist
1625         Row * row = cursor.row();
1626         int y = cursor.y() - row->baseline();
1627         if (c != Paragraph::META_INSET) {
1628                 // Here case LyXText::InsertInset  already insertet the character
1629                 cursor.par()->insertChar(cursor.pos(), c);
1630         }
1631         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1632
1633         if (!jumped_over_space) {
1634                 // refresh the positions
1635                 Row * tmprow = row;
1636                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1637                         tmprow = tmprow->next();
1638                         tmprow->pos(tmprow->pos() + 1);
1639                 }
1640         }
1641
1642         // Is there a break one row above
1643         if (row->previous() && row->previous()->par() == row->par()
1644             && (cursor.par()->isLineSeparator(cursor.pos())
1645                 || cursor.par()->isNewline(cursor.pos())
1646                 || ((cursor.pos() < cursor.par()->size()) &&
1647                     cursor.par()->isInset(cursor.pos()+1))
1648                 || cursor.row()->fill() == -1))
1649         {
1650                 pos_type z = rowBreakPoint(*bview, *row->previous());
1651
1652                 if (z >= row->pos()) {
1653                         row->pos(z + 1);
1654
1655                         // set the dimensions of the row above
1656                         row->previous()->fill(fill(*bview,
1657                                                    *row->previous(),
1658                                                    workWidth(*bview)));
1659
1660                         setHeightOfRow(bview, row->previous());
1661
1662                         y -= row->previous()->height();
1663                         refresh_y = y;
1664                         refresh_row = row->previous();
1665                         status(bview, LyXText::NEED_MORE_REFRESH);
1666
1667                         breakAgainOneRow(bview, row);
1668
1669                         current_font = rawtmpfont;
1670                         real_current_font = realtmpfont;
1671                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1672                                   false, cursor.boundary());
1673                         // cursor MUST be in row now.
1674
1675                         if (row->next() && row->next()->par() == row->par())
1676                                 need_break_row = row->next();
1677                         else
1678                                 need_break_row = 0;
1679
1680                         // check, wether the last characters font has changed.
1681                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1682                             && rawparfont != rawtmpfont)
1683                                 redoHeightOfParagraph(bview);
1684
1685                         charInserted();
1686                         return;
1687                 }
1688         }
1689
1690         // recalculate the fill of the row
1691         if (row->fill() >= 0) {
1692                 // needed because a newline will set fill to -1. Otherwise
1693                 // we would not get a rebreak!
1694                 row->fill(fill(*bview, *row, workWidth(*bview)));
1695         }
1696
1697         if (c == Paragraph::META_INSET || row->fill() < 0) {
1698                 refresh_y = y;
1699                 refresh_row = row;
1700                 status(bview, LyXText::NEED_MORE_REFRESH);
1701                 breakAgainOneRow(bview, row);
1702                 // will the cursor be in another row now?
1703                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1704                         if (row->next() && row->next()->par() == row->par())
1705                                 // this should always be true
1706                                 row = row->next();
1707                         breakAgainOneRow(bview, row);
1708                 }
1709                 current_font = rawtmpfont;
1710                 real_current_font = realtmpfont;
1711
1712                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1713                           cursor.boundary());
1714                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1715                     != cursor.boundary())
1716                         setCursor(bview, cursor.par(), cursor.pos(), false,
1717                           !cursor.boundary());
1718                 if (row->next() && row->next()->par() == row->par())
1719                         need_break_row = row->next();
1720                 else
1721                         need_break_row = 0;
1722         } else {
1723                 refresh_y = y;
1724                 refresh_row = row;
1725
1726                 int const tmpheight = row->height();
1727                 setHeightOfRow(bview, row);
1728                 if (tmpheight == row->height())
1729                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1730                 else
1731                         status(bview, LyXText::NEED_MORE_REFRESH);
1732
1733                 current_font = rawtmpfont;
1734                 real_current_font = realtmpfont;
1735                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1736                           cursor.boundary());
1737         }
1738
1739         // check, wether the last characters font has changed.
1740         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1741             && rawparfont != rawtmpfont) {
1742                 redoHeightOfParagraph(bview);
1743         } else {
1744                 // now the special right address boxes
1745                 if (cursor.par()->layout()->margintype
1746                     == MARGIN_RIGHT_ADDRESS_BOX) {
1747                         redoDrawingOfParagraph(bview, cursor);
1748                 }
1749         }
1750
1751         charInserted();
1752 }
1753
1754
1755 void LyXText::charInserted()
1756 {
1757         // Here we could call FinishUndo for every 20 characters inserted.
1758         // This is from my experience how emacs does it.
1759         static unsigned int counter;
1760         if (counter < 20) {
1761                 ++counter;
1762         } else {
1763                 finishUndo();
1764                 counter = 0;
1765         }
1766 }
1767
1768
1769 void LyXText::prepareToPrint(BufferView * bview,
1770                              Row * row, float & x,
1771                              float & fill_separator,
1772                              float & fill_hfill,
1773                              float & fill_label_hfill,
1774                              bool bidi) const
1775 {
1776         float nlh;
1777         float ns;
1778
1779         float w = row->fill();
1780         fill_hfill = 0;
1781         fill_label_hfill = 0;
1782         fill_separator = 0;
1783         fill_label_hfill = 0;
1784
1785         bool const is_rtl =
1786                 row->par()->isRightToLeftPar(bview->buffer()->params);
1787         if (is_rtl) {
1788                 x = (workWidth(*bview) > 0)
1789                         ? rightMargin(*bview->buffer(), *row) : 0;
1790         } else
1791                 x = (workWidth(*bview) > 0)
1792                         ? leftMargin(bview, row) : 0;
1793
1794         // is there a manual margin with a manual label
1795         LyXLayout_ptr const & layout = row->par()->layout();
1796
1797         if (layout->margintype == MARGIN_MANUAL
1798             && layout->labeltype == LABEL_MANUAL) {
1799                 /// We might have real hfills in the label part
1800                 nlh = row->numberOfLabelHfills();
1801
1802                 // A manual label par (e.g. List) has an auto-hfill
1803                 // between the label text and the body of the
1804                 // paragraph too.
1805                 // But we don't want to do this auto hfill if the par
1806                 // is empty.
1807                 if (!row->par()->empty())
1808                         ++nlh;
1809
1810                 if (nlh && !row->par()->getLabelWidthString().empty()) {
1811                         fill_label_hfill = labelFill(*bview, *row) / nlh;
1812                 }
1813         }
1814
1815         // are there any hfills in the row?
1816         float const nh = row->numberOfHfills();
1817
1818         if (nh) {
1819                 if (w > 0)
1820                         fill_hfill = w / nh;
1821         // we don't have to look at the alignment if it is ALIGN_LEFT and
1822         // if the row is already larger then the permitted width as then
1823         // we force the LEFT_ALIGN'edness!
1824         } else if (static_cast<int>(row->width()) < workWidth(*bview)) {
1825                 // is it block, flushleft or flushright?
1826                 // set x how you need it
1827                 int align;
1828                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
1829                         align = layout->align;
1830                 } else {
1831                         align = row->par()->params().align();
1832                 }
1833
1834                 // center displayed insets
1835                 Inset * inset;
1836                 if (row->pos() < row->par()->size()
1837                     && row->par()->isInset(row->pos())
1838                     && (inset = row->par()->getInset(row->pos()))
1839                     && (inset->display())) // || (inset->scroll() < 0)))
1840                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1841                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1842                 // ERT insets should always be LEFT ALIGNED on screen
1843                 inset = row->par()->inInset();
1844                 if (inset && inset->owner() &&
1845                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1846                 {
1847                         align = LYX_ALIGN_LEFT;
1848                 }
1849
1850                 switch (align) {
1851             case LYX_ALIGN_BLOCK:
1852                         ns = row->numberOfSeparators();
1853                         if (ns && row->next() && row->next()->par() == row->par() &&
1854                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
1855                             && !(row->next()->par()->isInset(row->next()->pos())
1856                                  && row->next()->par()->getInset(row->next()->pos())
1857                                  && row->next()->par()->getInset(row->next()->pos())->display())
1858                                 )
1859                         {
1860                                 fill_separator = w / ns;
1861                         } else if (is_rtl) {
1862                                 x += w;
1863                         }
1864                         break;
1865             case LYX_ALIGN_RIGHT:
1866                         x += w;
1867                         break;
1868             case LYX_ALIGN_CENTER:
1869                         x += w / 2;
1870                         break;
1871                 }
1872         }
1873         if (!bidi)
1874                 return;
1875
1876         computeBidiTables(bview->buffer(), row);
1877         if (is_rtl) {
1878                 pos_type body_pos = row->par()->beginningOfBody();
1879                 pos_type last = row->lastPos();
1880
1881                 if (body_pos > 0 &&
1882                     (body_pos - 1 > last ||
1883                      !row->par()->isLineSeparator(body_pos - 1))) {
1884                         x += font_metrics::width(layout->labelsep,
1885                                             getLabelFont(bview->buffer(), row->par()));
1886                         if (body_pos - 1 <= last)
1887                                 x += fill_label_hfill;
1888                 }
1889         }
1890 }
1891
1892
1893 // important for the screen
1894
1895
1896 // the cursor set functions have a special mechanism. When they
1897 // realize, that you left an empty paragraph, they will delete it.
1898 // They also delete the corresponding row
1899
1900 void LyXText::cursorRightOneWord(BufferView * bview) const
1901 {
1902         // treat floats, HFills and Insets as words
1903         LyXCursor tmpcursor = cursor;
1904         // CHECK See comment on top of text.C
1905
1906         if (tmpcursor.pos() == tmpcursor.par()->size()
1907             && tmpcursor.par()->next()) {
1908                         tmpcursor.par(tmpcursor.par()->next());
1909                         tmpcursor.pos(0);
1910         } else {
1911                 int steps = 0;
1912
1913                 // Skip through initial nonword stuff.
1914                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1915                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
1916                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
1917                         tmpcursor.pos(tmpcursor.pos() + 1);
1918                         ++steps;
1919                 }
1920                 // Advance through word.
1921                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1922                         tmpcursor.par()->isWord(tmpcursor.pos())) {
1923                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
1924                         tmpcursor.pos(tmpcursor.pos() + 1);
1925                         ++steps;
1926                 }
1927         }
1928         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1929 }
1930
1931
1932 void LyXText::cursorTab(BufferView * bview) const
1933 {
1934         LyXCursor tmpcursor = cursor;
1935         while (tmpcursor.pos() < tmpcursor.par()->size()
1936            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
1937         tmpcursor.pos(tmpcursor.pos() + 1);
1938
1939         if (tmpcursor.pos() == tmpcursor.par()->size()) {
1940                 if (tmpcursor.par()->next()) {
1941                         tmpcursor.par(tmpcursor.par()->next());
1942                         tmpcursor.pos(0);
1943                 }
1944         } else
1945                 tmpcursor.pos(tmpcursor.pos() + 1);
1946         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1947 }
1948
1949
1950 // Skip initial whitespace at end of word and move cursor to *start*
1951 // of prior word, not to end of next prior word.
1952 void LyXText::cursorLeftOneWord(BufferView * bview)  const
1953 {
1954         LyXCursor tmpcursor = cursor;
1955         cursorLeftOneWord(tmpcursor);
1956         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1957 }
1958
1959
1960 void LyXText::cursorLeftOneWord(LyXCursor & cur) const
1961 {
1962         // treat HFills, floats and Insets as words
1963         cur = cursor;
1964         while (cur.pos()
1965                && (cur.par()->isSeparator(cur.pos() - 1)
1966                    || cur.par()->isKomma(cur.pos() - 1)
1967                    || cur.par()->isNewline(cur.pos() - 1))
1968                && !(cur.par()->isHfill(cur.pos() - 1)
1969                     || cur.par()->isInset(cur.pos() - 1)))
1970                 cur.pos(cur.pos() - 1);
1971
1972         if (cur.pos()
1973             && (cur.par()->isInset(cur.pos() - 1)
1974                 || cur.par()->isHfill(cur.pos() - 1))) {
1975                 cur.pos(cur.pos() - 1);
1976         } else if (!cur.pos()) {
1977                 if (cur.par()->previous()) {
1978                         cur.par(cur.par()->previous());
1979                         cur.pos(cur.par()->size());
1980                 }
1981         } else {                // Here, cur != 0
1982                 while (cur.pos() > 0 &&
1983                        cur.par()->isWord(cur.pos() - 1))
1984                         cur.pos(cur.pos() - 1);
1985         }
1986 }
1987
1988
1989 // Select current word. This depends on behaviour of
1990 // CursorLeftOneWord(), so it is patched as well.
1991 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
1992                       word_location const loc) const
1993 {
1994         // first put the cursor where we wana start to select the word
1995         from = cursor;
1996         switch (loc) {
1997         case WHOLE_WORD_STRICT:
1998                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
1999                     || cursor.par()->isSeparator(cursor.pos())
2000                     || cursor.par()->isKomma(cursor.pos())
2001                     || cursor.par()->isNewline(cursor.pos())
2002                     || cursor.par()->isSeparator(cursor.pos() - 1)
2003                     || cursor.par()->isKomma(cursor.pos() - 1)
2004                     || cursor.par()->isNewline(cursor.pos() - 1)) {
2005                         to = from;
2006                         return;
2007                 }
2008                 // no break here, we go to the next
2009
2010         case WHOLE_WORD:
2011                 // Move cursor to the beginning, when not already there.
2012                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2013                     && !(from.par()->isKomma(from.pos() - 1)
2014                          || from.par()->isNewline(from.pos() - 1)))
2015                         cursorLeftOneWord(from);
2016                 break;
2017         case PREVIOUS_WORD:
2018                 // always move the cursor to the beginning of previous word
2019                 cursorLeftOneWord(from);
2020                 break;
2021         case NEXT_WORD:
2022                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2023                 break;
2024         case PARTIAL_WORD:
2025                 break;
2026         }
2027         to = from;
2028         while (to.pos() < to.par()->size()
2029                && !to.par()->isSeparator(to.pos())
2030                && !to.par()->isKomma(to.pos())
2031                && !to.par()->isNewline(to.pos())
2032                && !to.par()->isHfill(to.pos())
2033                && !to.par()->isInset(to.pos()))
2034         {
2035                 to.pos(to.pos() + 1);
2036         }
2037 }
2038
2039
2040 void LyXText::selectWord(BufferView * bview, word_location const loc)
2041 {
2042         LyXCursor from;
2043         LyXCursor to;
2044         getWord(from, to, loc);
2045         if (cursor != from)
2046                 setCursor(bview, from.par(), from.pos());
2047         if (to == from)
2048                 return;
2049         selection.cursor = cursor;
2050         setCursor(bview, to.par(), to.pos());
2051         setSelection(bview);
2052 }
2053
2054
2055 // Select the word currently under the cursor when no
2056 // selection is currently set
2057 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2058                                         word_location const loc)
2059 {
2060         if (!selection.set()) {
2061                 selectWord(bview, loc);
2062                 return selection.set();
2063         }
2064         return false;
2065 }
2066
2067
2068 void LyXText::acceptChange(BufferView * bv)
2069 {
2070         if (!selection.set() && cursor.par()->size())
2071                 return;
2072
2073         bv->hideCursor();
2074
2075         if (selection.start.par() == selection.end.par()) {
2076                 LyXCursor & startc = selection.start;
2077                 LyXCursor & endc = selection.end;
2078                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2079                 startc.par()->acceptChange(startc.pos(), endc.pos());
2080                 finishUndo();
2081                 clearSelection();
2082                 redoParagraphs(bv, startc, startc.par()->next());
2083                 setCursorIntern(bv, startc.par(), 0);
2084         }
2085 #warning handle multi par selection
2086 }
2087
2088
2089 void LyXText::rejectChange(BufferView * bv)
2090 {
2091         if (!selection.set() && cursor.par()->size())
2092                 return;
2093
2094         bv->hideCursor();
2095
2096         if (selection.start.par() == selection.end.par()) {
2097                 LyXCursor & startc = selection.start;
2098                 LyXCursor & endc = selection.end;
2099                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2100                 startc.par()->rejectChange(startc.pos(), endc.pos());
2101                 finishUndo();
2102                 clearSelection();
2103                 redoParagraphs(bv, startc, startc.par()->next());
2104                 setCursorIntern(bv, startc.par(), 0);
2105         }
2106 #warning handle multi par selection
2107 }
2108
2109
2110 // This function is only used by the spellchecker for NextWord().
2111 // It doesn't handle LYX_ACCENTs and probably never will.
2112 WordLangTuple const
2113 LyXText::selectNextWordToSpellcheck(BufferView * bview, float & value) const
2114 {
2115         if (the_locking_inset) {
2116                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2117                 if (!word.word().empty()) {
2118                         value += float(cursor.y());
2119                         value /= float(height);
2120                         return word;
2121                 }
2122                 // we have to go on checking so move cursor to the next char
2123                 if (cursor.pos() == cursor.par()->size()) {
2124                         if (!cursor.par()->next())
2125                                 return word;
2126                         cursor.par(cursor.par()->next());
2127                         cursor.pos(0);
2128                 } else
2129                         cursor.pos(cursor.pos() + 1);
2130         }
2131         Paragraph * tmppar = cursor.par();
2132
2133         // If this is not the very first word, skip rest of
2134         // current word because we are probably in the middle
2135         // of a word if there is text here.
2136         if (cursor.pos() || cursor.par()->previous()) {
2137                 while (cursor.pos() < cursor.par()->size()
2138                        && cursor.par()->isLetter(cursor.pos()))
2139                         cursor.pos(cursor.pos() + 1);
2140         }
2141
2142         // Now, skip until we have real text (will jump paragraphs)
2143         while (1) {
2144                 Paragraph * cpar(cursor.par());
2145                 pos_type const cpos(cursor.pos());
2146
2147                 if (cpos == cpar->size()) {
2148                         if (cpar->next()) {
2149                                 cursor.par(cpar->next());
2150                                 cursor.pos(0);
2151                                 continue;
2152                         }
2153                         break;
2154                 }
2155
2156                 bool const is_bad_inset(cpar->isInset(cpos)
2157                         && !cpar->getInset(cpos)->allowSpellcheck());
2158
2159                 if (cpar->isLetter(cpos) && !isDeletedText(*cpar, cpos)
2160                         && !is_bad_inset)
2161                         break;
2162
2163                 cursor.pos(cpos + 1);
2164         }
2165
2166         // now check if we hit an inset so it has to be a inset containing text!
2167         if (cursor.pos() < cursor.par()->size() &&
2168             cursor.par()->isInset(cursor.pos())) {
2169                 // lock the inset!
2170                 cursor.par()->getInset(cursor.pos())->edit(bview);
2171                 // now call us again to do the above trick
2172                 // but obviously we have to start from down below ;)
2173                 return bview->text->selectNextWordToSpellcheck(bview, value);
2174         }
2175
2176         // Update the value if we changed paragraphs
2177         if (cursor.par() != tmppar) {
2178                 setCursor(bview, cursor.par(), cursor.pos());
2179                 value = float(cursor.y())/float(height);
2180         }
2181
2182         // Start the selection from here
2183         selection.cursor = cursor;
2184
2185         string lang_code(
2186                 getFont(bview->buffer(), cursor.par(), cursor.pos())
2187                         .language()->code());
2188         // and find the end of the word (insets like optional hyphens
2189         // and ligature break are part of a word)
2190         while (cursor.pos() < cursor.par()->size()
2191                && cursor.par()->isLetter(cursor.pos())
2192                && !isDeletedText(*cursor.par(), cursor.pos()))
2193                 cursor.pos(cursor.pos() + 1);
2194
2195         // Finally, we copy the word to a string and return it
2196         string str;
2197         if (selection.cursor.pos() < cursor.pos()) {
2198                 pos_type i;
2199                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2200                         if (!cursor.par()->isInset(i))
2201                                 str += cursor.par()->getChar(i);
2202                 }
2203         }
2204         return WordLangTuple(str, lang_code);
2205 }
2206
2207
2208 // This one is also only for the spellchecker
2209 void LyXText::selectSelectedWord(BufferView * bview)
2210 {
2211         if (the_locking_inset) {
2212                 the_locking_inset->selectSelectedWord(bview);
2213                 return;
2214         }
2215         // move cursor to the beginning
2216         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2217
2218         // set the sel cursor
2219         selection.cursor = cursor;
2220
2221         // now find the end of the word
2222         while (cursor.pos() < cursor.par()->size()
2223                && (cursor.par()->isLetter(cursor.pos())))
2224                 cursor.pos(cursor.pos() + 1);
2225
2226         setCursor(bview, cursor.par(), cursor.pos());
2227
2228         // finally set the selection
2229         setSelection(bview);
2230 }
2231
2232
2233 // Delete from cursor up to the end of the current or next word.
2234 void LyXText::deleteWordForward(BufferView * bview)
2235 {
2236         if (cursor.par()->empty())
2237                 cursorRight(bview);
2238         else {
2239                 LyXCursor tmpcursor = cursor;
2240                 tmpcursor.row(0); // ??
2241                 selection.set(true); // to avoid deletion
2242                 cursorRightOneWord(bview);
2243                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2244                 selection.cursor = cursor;
2245                 cursor = tmpcursor;
2246                 setSelection(bview);
2247
2248                 // Great, CutSelection() gets rid of multiple spaces.
2249                 cutSelection(bview, true, false);
2250         }
2251 }
2252
2253
2254 // Delete from cursor to start of current or prior word.
2255 void LyXText::deleteWordBackward(BufferView * bview)
2256 {
2257         if (cursor.par()->empty())
2258                 cursorLeft(bview);
2259         else {
2260                 LyXCursor tmpcursor = cursor;
2261                 tmpcursor.row(0); // ??
2262                 selection.set(true); // to avoid deletion
2263                 cursorLeftOneWord(bview);
2264                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2265                 selection.cursor = cursor;
2266                 cursor = tmpcursor;
2267                 setSelection(bview);
2268                 cutSelection(bview, true, false);
2269         }
2270 }
2271
2272
2273 // Kill to end of line.
2274 void LyXText::deleteLineForward(BufferView * bview)
2275 {
2276         if (cursor.par()->empty())
2277                 // Paragraph is empty, so we just go to the right
2278                 cursorRight(bview);
2279         else {
2280                 LyXCursor tmpcursor = cursor;
2281                 // We can't store the row over a regular setCursor
2282                 // so we set it to 0 and reset it afterwards.
2283                 tmpcursor.row(0); // ??
2284                 selection.set(true); // to avoid deletion
2285                 cursorEnd(bview);
2286                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2287                 selection.cursor = cursor;
2288                 cursor = tmpcursor;
2289                 setSelection(bview);
2290                 // What is this test for ??? (JMarc)
2291                 if (!selection.set()) {
2292                         deleteWordForward(bview);
2293                 } else {
2294                         cutSelection(bview, true, false);
2295                 }
2296         }
2297 }
2298
2299
2300 void LyXText::changeCase(BufferView & bview, LyXText::TextCase action)
2301 {
2302         LyXCursor from;
2303         LyXCursor to;
2304
2305         if (selection.set()) {
2306                 from = selection.start;
2307                 to = selection.end;
2308         } else {
2309                 getWord(from, to, PARTIAL_WORD);
2310                 setCursor(&bview, to.par(), to.pos() + 1);
2311         }
2312
2313         lyx::Assert(from <= to);
2314
2315         setUndo(&bview, Undo::FINISH, from.par(), to.par()->next());
2316
2317         pos_type pos = from.pos();
2318         Paragraph * par = from.par();
2319
2320         while (par && (pos != to.pos() || par != to.par())) {
2321                 if (pos == par->size()) {
2322                         par = par->next();
2323                         pos = 0;
2324                         continue;
2325                 }
2326                 unsigned char c = par->getChar(pos);
2327                 if (!IsInsetChar(c)) {
2328                         switch (action) {
2329                         case text_lowercase:
2330                                 c = lowercase(c);
2331                                 break;
2332                         case text_capitalization:
2333                                 c = uppercase(c);
2334                                 action = text_lowercase;
2335                                 break;
2336                         case text_uppercase:
2337                                 c = uppercase(c);
2338                                 break;
2339                         }
2340                 }
2341 #warning changes
2342                 par->setChar(pos, c);
2343                 checkParagraph(&bview, par, pos);
2344
2345                 ++pos;
2346         }
2347         if (to.row() != from.row()) {
2348                 refresh_y = from.y() - from.row()->baseline();
2349                 refresh_row = from.row();
2350                 status(&bview, LyXText::NEED_MORE_REFRESH);
2351         }
2352 }
2353
2354
2355 void LyXText::transposeChars(BufferView & bview)
2356 {
2357         Paragraph * tmppar = cursor.par();
2358
2359         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2360
2361         pos_type tmppos = cursor.pos();
2362
2363         // First decide if it is possible to transpose at all
2364
2365         if (tmppos == 0 || tmppos == tmppar->size())
2366                 return;
2367
2368         if (isDeletedText(*tmppar, tmppos - 1)
2369                 || isDeletedText(*tmppar, tmppos))
2370                 return;
2371
2372         unsigned char c1 = tmppar->getChar(tmppos);
2373         unsigned char c2 = tmppar->getChar(tmppos - 1);
2374
2375         // We should have an implementation that handles insets
2376         // as well, but that will have to come later. (Lgb)
2377         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET)
2378                 return;
2379
2380         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2381         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2382
2383         tmppar->insertChar(ipos, c1);
2384         tmppar->insertChar(ipos + 1, c2);
2385
2386         checkParagraph(&bview, tmppar, tmppos);
2387 }
2388
2389
2390 void LyXText::Delete(BufferView * bview)
2391 {
2392         // this is a very easy implementation
2393
2394         LyXCursor old_cursor = cursor;
2395         int const old_cur_par_id = old_cursor.par()->id();
2396         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2397                 old_cursor.par()->previous()->id() : -1;
2398
2399         // just move to the right
2400         cursorRight(bview);
2401
2402         // CHECK Look at the comment here.
2403         // This check is not very good...
2404         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2405         // and that can very well delete the par or par->previous in
2406         // old_cursor. Will a solution where we compare paragraph id's
2407         //work better?
2408         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2409             == old_cur_par_prev_id
2410             && cursor.par()->id() != old_cur_par_id) {
2411                 // delete-empty-paragraph-mechanism has done it
2412                 return;
2413         }
2414
2415         // if you had success make a backspace
2416         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2417                 LyXCursor tmpcursor = cursor;
2418                 // to make sure undo gets the right cursor position
2419                 cursor = old_cursor;
2420                 setUndo(bview, Undo::DELETE,
2421                         cursor.par(), cursor.par()->next());
2422                 cursor = tmpcursor;
2423                 backspace(bview);
2424         }
2425 }
2426
2427
2428 void LyXText::backspace(BufferView * bview)
2429 {
2430         // Get the font that is used to calculate the baselineskip
2431         pos_type lastpos = cursor.par()->size();
2432         LyXFont rawparfont =
2433                 cursor.par()->getFontSettings(bview->buffer()->params,
2434                                               lastpos - 1);
2435
2436         if (cursor.pos() == 0) {
2437                 // The cursor is at the beginning of a paragraph,
2438                 // so the the backspace will collapse two paragraphs into one.
2439
2440                 // but it's not allowed unless it's new
2441                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2442                         return;
2443
2444                 // we may paste some paragraphs
2445
2446                 // is it an empty paragraph?
2447
2448                 if ((lastpos == 0
2449                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2450                         // This is an empty paragraph and we delete it just by moving the cursor one step
2451                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2452                         // of the paragraph.
2453
2454                         if (cursor.par()->previous()) {
2455                                 Paragraph * tmppar = cursor.par()->previous();
2456                                 if (cursor.par()->layout() == tmppar->layout()
2457                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2458                                         // Inherit bottom DTD from the paragraph below.
2459                                         // (the one we are deleting)
2460                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2461                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2462                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2463                                 }
2464
2465                                 cursorLeft(bview);
2466
2467                                 // the layout things can change the height of a row !
2468                                 int const tmpheight = cursor.row()->height();
2469                                 setHeightOfRow(bview, cursor.row());
2470                                 if (cursor.row()->height() != tmpheight) {
2471                                         refresh_y = cursor.y() - cursor.row()->baseline();
2472                                         refresh_row = cursor.row();
2473                                         status(bview, LyXText::NEED_MORE_REFRESH);
2474                                 }
2475                                 return;
2476                         }
2477                 }
2478
2479                 if (cursor.par()->previous()) {
2480                         setUndo(bview, Undo::DELETE,
2481                                 cursor.par()->previous(), cursor.par()->next());
2482                 }
2483
2484                 Paragraph * tmppar = cursor.par();
2485                 Row * tmprow = cursor.row();
2486
2487                 // We used to do cursorLeftIntern() here, but it is
2488                 // not a good idea since it triggers the auto-delete
2489                 // mechanism. So we do a cursorLeftIntern()-lite,
2490                 // without the dreaded mechanism. (JMarc)
2491                 if (cursor.par()->previous()) {
2492                         // steps into the above paragraph.
2493                         setCursorIntern(bview, cursor.par()->previous(),
2494                                         cursor.par()->previous()->size(),
2495                                         false);
2496                 }
2497
2498                 // Pasting is not allowed, if the paragraphs have different
2499                 // layout. I think it is a real bug of all other
2500                 // word processors to allow it. It confuses the user.
2501                 // Even so with a footnote paragraph and a non-footnote
2502                 // paragraph. I will not allow pasting in this case,
2503                 // because the user would be confused if the footnote behaves
2504                 // different wether it is open or closed.
2505
2506                 //      Correction: Pasting is always allowed with standard-layout
2507                 LyXTextClass const & tclass =
2508                         bview->buffer()->params.getLyXTextClass();
2509
2510                 if (cursor.par() != tmppar
2511                     && (cursor.par()->layout() == tmppar->layout()
2512                         || tmppar->layout() == tclass.defaultLayout())
2513                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2514                         removeParagraph(tmprow);
2515                         removeRow(tmprow);
2516                         mergeParagraph(bview->buffer()->params, bview->buffer()->paragraphs, cursor.par());
2517
2518                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2519                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2520                         // strangely enough it seems that commenting out the line above removes
2521                         // most or all of the segfaults. I will however also try to move the
2522                         // two Remove... lines in front of the PasteParagraph too.
2523                         else
2524                                 if (cursor.pos())
2525                                         cursor.pos(cursor.pos() - 1);
2526
2527                         status(bview, LyXText::NEED_MORE_REFRESH);
2528                         refresh_row = cursor.row();
2529                         refresh_y = cursor.y() - cursor.row()->baseline();
2530
2531                         // remove the lost paragraph
2532                         // This one is not safe, since the paragraph that the tmprow and the
2533                         // following rows belong to has been deleted by the PasteParagraph
2534                         // above. The question is... could this be moved in front of the
2535                         // PasteParagraph?
2536                         //RemoveParagraph(tmprow);
2537                         //RemoveRow(tmprow);
2538
2539                         // This rebuilds the rows.
2540                         appendParagraph(bview, cursor.row());
2541                         updateCounters(bview);
2542
2543                         // the row may have changed, block, hfills etc.
2544                         setCursor(bview, cursor.par(), cursor.pos(), false);
2545                 }
2546         } else {
2547                 // this is the code for a normal backspace, not pasting
2548                 // any paragraphs
2549                 setUndo(bview, Undo::DELETE,
2550                         cursor.par(), cursor.par()->next());
2551                 // We used to do cursorLeftIntern() here, but it is
2552                 // not a good idea since it triggers the auto-delete
2553                 // mechanism. So we do a cursorLeftIntern()-lite,
2554                 // without the dreaded mechanism. (JMarc)
2555                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2556                                 false, cursor.boundary());
2557
2558                 if (cursor.par()->isInset(cursor.pos())) {
2559                         // force complete redo when erasing display insets
2560                         // this is a cruel method but safe..... Matthias
2561                         if (cursor.par()->getInset(cursor.pos())->display() ||
2562                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2563                                 cursor.par()->erase(cursor.pos());
2564                                 redoParagraph(bview);
2565                                 return;
2566                         }
2567                 }
2568
2569                 Row * row = cursor.row();
2570                 int y = cursor.y() - row->baseline();
2571                 pos_type z;
2572                 // remember that a space at the end of a row doesnt count
2573                 // when calculating the fill
2574                 if (cursor.pos() < row->lastPos() ||
2575                     !cursor.par()->isLineSeparator(cursor.pos())) {
2576                         row->fill(row->fill() + singleWidth(bview,
2577                                                             cursor.par(),
2578                                                             cursor.pos()));
2579                 }
2580
2581                 // some special code when deleting a newline. This is similar
2582                 // to the behavior when pasting paragraphs
2583                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2584                         cursor.par()->erase(cursor.pos());
2585                         // refresh the positions
2586                         Row * tmprow = row;
2587                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2588                                 tmprow = tmprow->next();
2589                                 tmprow->pos(tmprow->pos() - 1);
2590                         }
2591                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2592                                 cursor.pos(cursor.pos() - 1);
2593
2594                         if (cursor.pos() < cursor.par()->size()
2595                             && !cursor.par()->isSeparator(cursor.pos())) {
2596                                 cursor.par()->insertChar(cursor.pos(), ' ');
2597                                 setCharFont(bview->buffer(), cursor.par(),
2598                                             cursor.pos(), current_font);
2599                                 // refresh the positions
2600                                 tmprow = row;
2601                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2602                                         tmprow = tmprow->next();
2603                                         tmprow->pos(tmprow->pos() + 1);
2604                                 }
2605                         }
2606                 } else {
2607                         cursor.par()->erase(cursor.pos());
2608
2609                         // refresh the positions
2610                         Row * tmprow = row;
2611                         while (tmprow->next()
2612                                && tmprow->next()->par() == row->par()) {
2613                                 tmprow = tmprow->next();
2614                                 tmprow->pos(tmprow->pos() - 1);
2615                         }
2616
2617                         // delete newlines at the beginning of paragraphs
2618                         while (!cursor.par()->empty() &&
2619                                cursor.par()->isNewline(cursor.pos()) &&
2620                                cursor.pos() == cursor.par()->beginningOfBody()) {
2621                                 cursor.par()->erase(cursor.pos());
2622                                 // refresh the positions
2623                                 tmprow = row;
2624                                 while (tmprow->next() &&
2625                                        tmprow->next()->par() == row->par()) {
2626                                         tmprow = tmprow->next();
2627                                         tmprow->pos(tmprow->pos() - 1);
2628                                 }
2629                         }
2630                 }
2631
2632                 // is there a break one row above
2633                 if (row->previous() && row->previous()->par() == row->par()) {
2634                         z = rowBreakPoint(*bview, *row->previous());
2635                         if (z >= row->pos()) {
2636                                 row->pos(z + 1);
2637
2638                                 Row * tmprow = row->previous();
2639
2640                                 // maybe the current row is now empty
2641                                 if (row->pos() >= row->par()->size()) {
2642                                         // remove it
2643                                         removeRow(row);
2644                                         need_break_row = 0;
2645                                 } else {
2646                                         breakAgainOneRow(bview, row);
2647                                         if (row->next() && row->next()->par() == row->par())
2648                                                 need_break_row = row->next();
2649                                         else
2650                                                 need_break_row = 0;
2651                                 }
2652
2653                                 // set the dimensions of the row above
2654                                 y -= tmprow->height();
2655                                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
2656                                 setHeightOfRow(bview, tmprow);
2657
2658                                 refresh_y = y;
2659                                 refresh_row = tmprow;
2660                                 status(bview, LyXText::NEED_MORE_REFRESH);
2661                                 setCursor(bview, cursor.par(), cursor.pos(),
2662                                           false, cursor.boundary());
2663                                 //current_font = rawtmpfont;
2664                                 //real_current_font = realtmpfont;
2665                                 // check, whether the last character's font has changed.
2666                                 if (rawparfont !=
2667                                     cursor.par()->getFontSettings(bview->buffer()->params,
2668                                                                   cursor.par()->size() - 1))
2669                                         redoHeightOfParagraph(bview);
2670                                 return;
2671                         }
2672                 }
2673
2674                 // break the cursor row again
2675                 if (row->next() && row->next()->par() == row->par() &&
2676                     (row->lastPos() == row->par()->size() - 1 ||
2677                      rowBreakPoint(*bview, *row) != row->lastPos())) {
2678
2679                         // it can happen that a paragraph loses one row
2680                         // without a real breakup. This is when a word
2681                         // is to long to be broken. Well, I don t care this
2682                         // hack ;-)
2683                         if (row->lastPos() == row->par()->size() - 1)
2684                                 removeRow(row->next());
2685
2686                         refresh_y = y;
2687                         refresh_row = row;
2688                         status(bview, LyXText::NEED_MORE_REFRESH);
2689
2690                         breakAgainOneRow(bview, row);
2691                         // will the cursor be in another row now?
2692                         if (row->next() && row->next()->par() == row->par() &&
2693                             row->lastPos() <= cursor.pos()) {
2694                                 row = row->next();
2695                                 breakAgainOneRow(bview, row);
2696                         }
2697
2698                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2699
2700                         if (row->next() && row->next()->par() == row->par())
2701                                 need_break_row = row->next();
2702                         else
2703                                 need_break_row = 0;
2704                 } else  {
2705                         // set the dimensions of the row
2706                         row->fill(fill(*bview, *row, workWidth(*bview)));
2707                         int const tmpheight = row->height();
2708                         setHeightOfRow(bview, row);
2709                         if (tmpheight == row->height())
2710                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2711                         else
2712                                 status(bview, LyXText::NEED_MORE_REFRESH);
2713                         refresh_y = y;
2714                         refresh_row = row;
2715                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2716                 }
2717         }
2718
2719         // current_font = rawtmpfont;
2720         // real_current_font = realtmpfont;
2721
2722         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2723             != cursor.boundary())
2724                 setCursor(bview, cursor.par(), cursor.pos(), false,
2725                           !cursor.boundary());
2726
2727         lastpos = cursor.par()->size();
2728         if (cursor.pos() == lastpos)
2729                 setCurrentFont(bview);
2730
2731         // check, whether the last characters font has changed.
2732         if (rawparfont !=
2733             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2734                 redoHeightOfParagraph(bview);
2735         } else {
2736                 // now the special right address boxes
2737                 if (cursor.par()->layout()->margintype
2738                     == MARGIN_RIGHT_ADDRESS_BOX) {
2739                         redoDrawingOfParagraph(bview, cursor);
2740                 }
2741         }
2742 }
2743
2744
2745 // returns pointer to a specified row
2746 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
2747 {
2748         if (!firstrow)
2749                 return 0;
2750
2751         Row * tmprow = firstrow;
2752         y = 0;
2753
2754         // find the first row of the specified paragraph
2755         while (tmprow->next() && tmprow->par() != par) {
2756                 y += tmprow->height();
2757                 tmprow = tmprow->next();
2758         }
2759
2760         // now find the wanted row
2761         while (tmprow->pos() < pos
2762                && tmprow->next()
2763                && tmprow->next()->par() == par
2764                && tmprow->next()->pos() <= pos) {
2765                 y += tmprow->height();
2766                 tmprow = tmprow->next();
2767         }
2768
2769         return tmprow;
2770 }
2771
2772
2773 Row * LyXText::getRowNearY(int & y) const
2774 {
2775 #if 1
2776         // If possible we should optimize this method. (Lgb)
2777         Row * tmprow = firstrow;
2778         int tmpy = 0;
2779
2780         while (tmprow->next() && tmpy + tmprow->height() <= y) {
2781                 tmpy += tmprow->height();
2782                 tmprow = tmprow->next();
2783         }
2784
2785         y = tmpy;   // return the real y
2786
2787         //lyxerr << "returned y = " << y << endl;
2788
2789         return tmprow;
2790 #else
2791         // Search from the current cursor position.
2792
2793         Row * tmprow = cursor.row();
2794         int tmpy = cursor.y() - tmprow->baseline();
2795
2796         lyxerr << "cursor.y() = " << tmpy << endl;
2797         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
2798         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
2799         lyxerr << "first = " << first << endl;
2800         lyxerr << "y = " << y << endl;
2801
2802         if (y < tmpy) {
2803                 lyxerr << "up" << endl;
2804                 do {
2805                         tmpy -= tmprow->height();
2806                         tmprow = tmprow->previous();
2807                 } while (tmprow && tmpy - tmprow->height() >= y);
2808         } else if (y > tmpy) {
2809                 lyxerr << "down" << endl;
2810
2811                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
2812                         tmpy += tmprow->height();
2813                         tmprow = tmprow->next();
2814                 }
2815         } else {
2816                 lyxerr << "equal" << endl;
2817         }
2818
2819         y = tmpy; // return the real y
2820
2821         lyxerr << "returned y = " << y << endl;
2822
2823         return tmprow;
2824
2825 #endif
2826 }
2827
2828
2829 int LyXText::getDepth() const
2830 {
2831         return cursor.par()->getDepth();
2832 }