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