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