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