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