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