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