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