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