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