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