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