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