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