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