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