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