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