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