]> git.lyx.org Git - lyx.git/blob - src/text.C
27737df2376b9205928b2a315f46e955414c0f8d
[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 // Do we even need this at all ? Code that uses  RowPainter *already*
1345 // sets need_break_row when it sees a CHANGED_IN_DRAW, though not
1346 // quite like this
1347 void LyXText::markChangeInDraw(Row * row, Row * prev)
1348 {
1349         if (prev && prev->par() == row->par()) {
1350                 breakAgainOneRow(prev);
1351                 if (prev->next() != row) {
1352                         // breakAgainOneRow() has removed row_
1353                         need_break_row = prev;
1354                 } else {
1355                         need_break_row = row;
1356                 }
1357         } else if (!prev) {
1358                 need_break_row = firstrow;
1359         } else {
1360                 need_break_row = prev->next();
1361         }
1362         setCursor(cursor.par(), cursor.pos());
1363         /* FIXME */
1364 }
1365
1366
1367 void LyXText::breakAgain(Row * row)
1368 {
1369         bool not_ready = true;
1370
1371         do  {
1372                 pos_type z = rowBreakPoint(*row);
1373                 Row * tmprow = row;
1374
1375                 if (z < row->par()->size()) {
1376                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1377                                 // insert a new row
1378                                 ++z;
1379                                 insertRow(row, row->par(), z);
1380                                 row = row->next();
1381                                 row->height(0);
1382                         } else  {
1383                                 row = row->next();
1384                                 ++z;
1385                                 if (row->pos() == z)
1386                                         not_ready = false; // the rest will not change
1387                                 else {
1388                                         row->pos(z);
1389                                 }
1390                         }
1391                 } else {
1392                         // if there are some rows too much, delete them
1393                         // only if you broke the whole paragraph!
1394                         Row * tmprow2 = row;
1395                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1396                                 tmprow2 = tmprow2->next();
1397                         }
1398                         while (tmprow2 != row) {
1399                                 tmprow2 = tmprow2->previous();
1400                                 removeRow(tmprow2->next());
1401                         }
1402                         not_ready = false;
1403                 }
1404
1405                 // set the dimensions of the row
1406                 tmprow->fill(fill(*tmprow, workWidth()));
1407                 setHeightOfRow(tmprow);
1408         } while (not_ready);
1409 }
1410
1411
1412 // this is just a little changed version of break again
1413 void LyXText::breakAgainOneRow(Row * row)
1414 {
1415         pos_type z = rowBreakPoint(*row);
1416         Row * tmprow = row;
1417
1418         if (z < row->par()->size()) {
1419                 if (!row->next()
1420                     || (row->next() && row->next()->par() != row->par())) {
1421                         // insert a new row
1422                         ++z;
1423                         insertRow(row, row->par(), z);
1424                         row = row->next();
1425                         row->height(0);
1426                 } else  {
1427                         row = row->next();
1428                         ++z;
1429                         if (row->pos() != z)
1430                                 row->pos(z);
1431                 }
1432         } else {
1433                 // if there are some rows too much, delete them
1434                 // only if you broke the whole paragraph!
1435                 Row * tmprow2 = row;
1436                 while (tmprow2->next()
1437                        && tmprow2->next()->par() == row->par()) {
1438                         tmprow2 = tmprow2->next();
1439                 }
1440                 while (tmprow2 != row) {
1441                         tmprow2 = tmprow2->previous();
1442                         removeRow(tmprow2->next());
1443                 }
1444         }
1445
1446         // set the dimensions of the row
1447         tmprow->fill(fill(*tmprow, workWidth()));
1448         setHeightOfRow(tmprow);
1449 }
1450
1451
1452 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1453 {
1454         // allow only if at start or end, or all previous is new text
1455         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1456                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1457                 return;
1458
1459         LyXTextClass const & tclass =
1460                 bv()->buffer()->params.getLyXTextClass();
1461         LyXLayout_ptr const & layout = cursor.par()->layout();
1462
1463         // this is only allowed, if the current paragraph is not empty or caption
1464         // and if it has not the keepempty flag aktive
1465         if (cursor.par()->empty()
1466            && layout->labeltype != LABEL_SENSITIVE
1467            && !layout->keepempty)
1468                 return;
1469
1470         setUndo(bv(), Undo::FINISH, cursor.par(), cursor.par()->next());
1471
1472         // Always break behind a space
1473         //
1474         // It is better to erase the space (Dekel)
1475         if (cursor.pos() < cursor.par()->size()
1476              && cursor.par()->isLineSeparator(cursor.pos()))
1477            cursor.par()->erase(cursor.pos());
1478         // cursor.pos(cursor.pos() + 1);
1479
1480         // break the paragraph
1481         if (keep_layout)
1482                 keep_layout = 2;
1483         else
1484                 keep_layout = layout->isEnvironment();
1485
1486         // we need to set this before we insert the paragraph. IMO the
1487         // breakParagraph call should return a bool if it inserts the
1488         // paragraph before or behind and we should react on that one
1489         // but we can fix this in 1.3.0 (Jug 20020509)
1490         bool const isempty = (layout->keepempty && cursor.par()->empty());
1491         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(), cursor.pos(),
1492                        keep_layout);
1493
1494         // well this is the caption hack since one caption is really enough
1495         if (layout->labeltype == LABEL_SENSITIVE) {
1496                 if (!cursor.pos())
1497                         // set to standard-layout
1498                         cursor.par()->applyLayout(tclass.defaultLayout());
1499                 else
1500                         // set to standard-layout
1501                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1502         }
1503
1504         // if the cursor is at the beginning of a row without prior newline,
1505         // move one row up!
1506         // This touches only the screen-update. Otherwise we would may have
1507         // an empty row on the screen
1508         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1509                          && cursor.row()->pos() == cursor.pos())
1510         {
1511                 cursorLeft(bv());
1512         }
1513
1514         int y = cursor.y() - cursor.row()->baseline();
1515
1516         // Do not forget the special right address boxes
1517         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1518                 Row * r = cursor.row();
1519                 while (r->previous() && r->previous()->par() == r->par()) {
1520                         r = r->previous();
1521                         y -= r->height();
1522                 }
1523         }
1524
1525         postPaint(y);
1526
1527         removeParagraph(cursor.row());
1528
1529         // set the dimensions of the cursor row
1530         cursor.row()->fill(fill(*cursor.row(), workWidth()));
1531
1532         setHeightOfRow(cursor.row());
1533
1534 #warning Trouble Point! (Lgb)
1535         // When ::breakParagraph is called from within an inset we must
1536         // ensure that the correct ParagraphList is used. Today that is not
1537         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1538         while (!cursor.par()->next()->empty()
1539           && cursor.par()->next()->isNewline(0))
1540            cursor.par()->next()->erase(0);
1541
1542         insertParagraph(cursor.par()->next(), cursor.row());
1543
1544         updateCounters();
1545
1546         // This check is necessary. Otherwise the new empty paragraph will
1547         // be deleted automatically. And it is more friendly for the user!
1548         if (cursor.pos() || isempty)
1549                 setCursor(cursor.par()->next(), 0);
1550         else
1551                 setCursor(cursor.par(), 0);
1552
1553         if (cursor.row()->next())
1554                 breakAgain(cursor.row()->next());
1555
1556         need_break_row = 0;
1557 }
1558
1559
1560 // Just a macro to make some thing easier.
1561 void LyXText::redoParagraph()
1562 {
1563         clearSelection();
1564         redoParagraphs(cursor, cursor.par()->next());
1565         setCursorIntern(cursor.par(), cursor.pos());
1566 }
1567
1568
1569 // insert a character, moves all the following breaks in the
1570 // same Paragraph one to the right and make a rebreak
1571 void LyXText::insertChar(char c)
1572 {
1573         setUndo(bv(), Undo::INSERT, cursor.par(), cursor.par()->next());
1574
1575         // When the free-spacing option is set for the current layout,
1576         // disable the double-space checking
1577
1578         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1579                 cursor.row()->par()->isFreeSpacing();
1580
1581         if (lyxrc.auto_number) {
1582                 static string const number_operators = "+-/*";
1583                 static string const number_unary_operators = "+-";
1584                 static string const number_seperators = ".,:";
1585
1586                 if (current_font.number() == LyXFont::ON) {
1587                         if (!IsDigit(c) && !contains(number_operators, c) &&
1588                             !(contains(number_seperators, c) &&
1589                               cursor.pos() >= 1 &&
1590                               cursor.pos() < cursor.par()->size() &&
1591                               getFont(bv()->buffer(),
1592                                       cursor.par(),
1593                                       cursor.pos()).number() == LyXFont::ON &&
1594                               getFont(bv()->buffer(),
1595                                       cursor.par(),
1596                                       cursor.pos() - 1).number() == LyXFont::ON)
1597                            )
1598                                 number(bv()); // Set current_font.number to OFF
1599                 } else if (IsDigit(c) &&
1600                            real_current_font.isVisibleRightToLeft()) {
1601                         number(bv()); // Set current_font.number to ON
1602
1603                         if (cursor.pos() > 0) {
1604                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1605                                 if (contains(number_unary_operators, c) &&
1606                                     (cursor.pos() == 1 ||
1607                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1608                                      cursor.par()->isNewline(cursor.pos() - 2))
1609                                   ) {
1610                                         setCharFont(bv()->buffer(),
1611                                                     cursor.par(),
1612                                                     cursor.pos() - 1,
1613                                                     current_font);
1614                                 } else if (contains(number_seperators, c) &&
1615                                            cursor.pos() >= 2 &&
1616                                            getFont(bv()->buffer(),
1617                                                    cursor.par(),
1618                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1619                                         setCharFont(bv()->buffer(),
1620                                                     cursor.par(),
1621                                                     cursor.pos() - 1,
1622                                                     current_font);
1623                                 }
1624                         }
1625                 }
1626         }
1627
1628
1629         // First check, if there will be two blanks together or a blank at
1630         // the beginning of a paragraph.
1631         // I decided to handle blanks like normal characters, the main
1632         // difference are the special checks when calculating the row.fill
1633         // (blank does not count at the end of a row) and the check here
1634
1635         // The bug is triggered when we type in a description environment:
1636         // The current_font is not changed when we go from label to main text
1637         // and it should (along with realtmpfont) when we type the space.
1638         // CHECK There is a bug here! (Asger)
1639
1640         LyXFont realtmpfont = real_current_font;
1641         LyXFont rawtmpfont = current_font;
1642         // store the current font.  This is because of the use of cursor
1643         // movements. The moving cursor would refresh the current font
1644
1645         // Get the font that is used to calculate the baselineskip
1646         pos_type const lastpos = cursor.par()->size();
1647         LyXFont rawparfont =
1648                 cursor.par()->getFontSettings(bv()->buffer()->params,
1649                                               lastpos - 1);
1650
1651         bool jumped_over_space = false;
1652
1653         if (!freeSpacing && IsLineSeparatorChar(c)) {
1654                 if ((cursor.pos() > 0
1655                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1656                     || (cursor.pos() > 0
1657                         && cursor.par()->isNewline(cursor.pos() - 1))
1658                     || (cursor.pos() == 0)) {
1659                         static bool sent_space_message = false;
1660                         if (!sent_space_message) {
1661                                 if (cursor.pos() == 0)
1662                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1663                                 else
1664                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1665                                 sent_space_message = true;
1666                         }
1667                         charInserted();
1668                         return;
1669                 }
1670         }
1671
1672         // the display inset stuff
1673         if (cursor.row()->pos() < cursor.row()->par()->size()
1674             && cursor.row()->par()->isInset(cursor.row()->pos())) {
1675                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1676                 if (inset && (inset->display() || inset->needFullRow())) {
1677                         // force a new break
1678                         cursor.row()->fill(-1); // to force a new break
1679                 }
1680         }
1681
1682         // get the cursor row fist
1683         Row * row = cursor.row();
1684         int y = cursor.y() - row->baseline();
1685         if (c != Paragraph::META_INSET) {
1686                 // Here case LyXText::InsertInset  already insertet the character
1687                 cursor.par()->insertChar(cursor.pos(), c);
1688         }
1689         setCharFont(bv()->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1690
1691         if (!jumped_over_space) {
1692                 // refresh the positions
1693                 Row * tmprow = row;
1694                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1695                         tmprow = tmprow->next();
1696                         tmprow->pos(tmprow->pos() + 1);
1697                 }
1698         }
1699
1700         // Is there a break one row above
1701         if (row->previous() && row->previous()->par() == row->par()
1702             && (cursor.par()->isLineSeparator(cursor.pos())
1703                 || cursor.par()->isNewline(cursor.pos())
1704                 || ((cursor.pos() + 1 < cursor.par()->size()) &&
1705                     cursor.par()->isInset(cursor.pos() + 1))
1706                 || cursor.row()->fill() == -1))
1707         {
1708                 pos_type z = rowBreakPoint(*row->previous());
1709
1710                 if (z >= row->pos()) {
1711                         row->pos(z + 1);
1712
1713                         // set the dimensions of the row above
1714                         row->previous()->fill(fill(
1715                                                    *row->previous(),
1716                                                    workWidth()));
1717
1718                         setHeightOfRow(row->previous());
1719
1720                         y -= row->previous()->height();
1721
1722                         postPaint(y);
1723
1724                         breakAgainOneRow(row);
1725
1726                         current_font = rawtmpfont;
1727                         real_current_font = realtmpfont;
1728                         setCursor(cursor.par(), cursor.pos() + 1,
1729                                   false, cursor.boundary());
1730                         // cursor MUST be in row now.
1731
1732                         if (row->next() && row->next()->par() == row->par())
1733                                 need_break_row = row->next();
1734                         else
1735                                 need_break_row = 0;
1736
1737                         // check, wether the last characters font has changed.
1738                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1739                             && rawparfont != rawtmpfont)
1740                                 redoHeightOfParagraph();
1741
1742                         charInserted();
1743                         return;
1744                 }
1745         }
1746
1747         // recalculate the fill of the row
1748         if (row->fill() >= 0) {
1749                 // needed because a newline will set fill to -1. Otherwise
1750                 // we would not get a rebreak!
1751                 row->fill(fill(*row, workWidth()));
1752         }
1753
1754         if (c == Paragraph::META_INSET || row->fill() < 0) {
1755                 postPaint(y);
1756                 breakAgainOneRow(row);
1757                 // will the cursor be in another row now?
1758                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1759                         if (row->next() && row->next()->par() == row->par())
1760                                 // this should always be true
1761                                 row = row->next();
1762                         breakAgainOneRow(row);
1763                 }
1764                 current_font = rawtmpfont;
1765                 real_current_font = realtmpfont;
1766
1767                 setCursor(cursor.par(), cursor.pos() + 1, false,
1768                           cursor.boundary());
1769                 if (isBoundary(bv()->buffer(), cursor.par(), cursor.pos())
1770                     != cursor.boundary())
1771                         setCursor(cursor.par(), cursor.pos(), false,
1772                           !cursor.boundary());
1773                 if (row->next() && row->next()->par() == row->par())
1774                         need_break_row = row->next();
1775                 else
1776                         need_break_row = 0;
1777         } else {
1778                 // FIXME: similar code is duplicated all over - make resetHeightOfRow
1779                 int const tmpheight = row->height();
1780
1781                 setHeightOfRow(row);
1782
1783                 if (tmpheight == row->height()) {
1784                         postRowPaint(row, y);
1785                 } else {
1786                         postPaint(y);
1787                 }
1788
1789                 current_font = rawtmpfont;
1790                 real_current_font = realtmpfont;
1791                 setCursor(cursor.par(), cursor.pos() + 1, false,
1792                           cursor.boundary());
1793         }
1794
1795         // check, wether the last characters font has changed.
1796         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1797             && rawparfont != rawtmpfont) {
1798                 redoHeightOfParagraph();
1799         } else {
1800                 // now the special right address boxes
1801                 if (cursor.par()->layout()->margintype
1802                     == MARGIN_RIGHT_ADDRESS_BOX) {
1803                         redoDrawingOfParagraph(cursor);
1804                 }
1805         }
1806
1807         charInserted();
1808 }
1809
1810
1811 void LyXText::charInserted()
1812 {
1813         // Here we could call FinishUndo for every 20 characters inserted.
1814         // This is from my experience how emacs does it.
1815         static unsigned int counter;
1816         if (counter < 20) {
1817                 ++counter;
1818         } else {
1819                 finishUndo();
1820                 counter = 0;
1821         }
1822 }
1823
1824
1825 void LyXText::prepareToPrint(Row * row, float & x,
1826                              float & fill_separator,
1827                              float & fill_hfill,
1828                              float & fill_label_hfill,
1829                              bool bidi) const
1830 {
1831         float nlh;
1832         float ns;
1833
1834         float w = row->fill();
1835         fill_hfill = 0;
1836         fill_label_hfill = 0;
1837         fill_separator = 0;
1838         fill_label_hfill = 0;
1839
1840         bool const is_rtl =
1841                 row->par()->isRightToLeftPar(bv()->buffer()->params);
1842         if (is_rtl) {
1843                 x = (workWidth() > 0)
1844                         ? rightMargin(*bv()->buffer(), *row) : 0;
1845         } else
1846                 x = (workWidth() > 0)
1847                         ? leftMargin(row) : 0;
1848
1849         // is there a manual margin with a manual label
1850         LyXLayout_ptr const & layout = row->par()->layout();
1851
1852         if (layout->margintype == MARGIN_MANUAL
1853             && layout->labeltype == LABEL_MANUAL) {
1854                 /// We might have real hfills in the label part
1855                 nlh = row->numberOfLabelHfills();
1856
1857                 // A manual label par (e.g. List) has an auto-hfill
1858                 // between the label text and the body of the
1859                 // paragraph too.
1860                 // But we don't want to do this auto hfill if the par
1861                 // is empty.
1862                 if (!row->par()->empty())
1863                         ++nlh;
1864
1865                 if (nlh && !row->par()->getLabelWidthString().empty()) {
1866                         fill_label_hfill = labelFill(*row) / nlh;
1867                 }
1868         }
1869
1870         // are there any hfills in the row?
1871         float const nh = row->numberOfHfills();
1872
1873         if (nh) {
1874                 if (w > 0)
1875                         fill_hfill = w / nh;
1876         // we don't have to look at the alignment if it is ALIGN_LEFT and
1877         // if the row is already larger then the permitted width as then
1878         // we force the LEFT_ALIGN'edness!
1879         } else if (static_cast<int>(row->width()) < workWidth()) {
1880                 // is it block, flushleft or flushright?
1881                 // set x how you need it
1882                 int align;
1883                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
1884                         align = layout->align;
1885                 } else {
1886                         align = row->par()->params().align();
1887                 }
1888
1889                 // center displayed insets
1890                 Inset * inset;
1891                 if (row->pos() < row->par()->size()
1892                     && row->par()->isInset(row->pos())
1893                     && (inset = row->par()->getInset(row->pos()))
1894                     && (inset->display())) // || (inset->scroll() < 0)))
1895                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1896                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1897                 // ERT insets should always be LEFT ALIGNED on screen
1898                 inset = row->par()->inInset();
1899                 if (inset && inset->owner() &&
1900                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1901                 {
1902                         align = LYX_ALIGN_LEFT;
1903                 }
1904
1905                 switch (align) {
1906             case LYX_ALIGN_BLOCK:
1907                         ns = row->numberOfSeparators();
1908                         if (ns && row->next() && row->next()->par() == row->par() &&
1909                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
1910                             && !(row->next()->par()->isInset(row->next()->pos())
1911                                  && row->next()->par()->getInset(row->next()->pos())
1912                                  && row->next()->par()->getInset(row->next()->pos())->display())
1913                                 )
1914                         {
1915                                 fill_separator = w / ns;
1916                         } else if (is_rtl) {
1917                                 x += w;
1918                         }
1919                         break;
1920             case LYX_ALIGN_RIGHT:
1921                         x += w;
1922                         break;
1923             case LYX_ALIGN_CENTER:
1924                         x += w / 2;
1925                         break;
1926                 }
1927         }
1928         if (!bidi)
1929                 return;
1930
1931         computeBidiTables(bv()->buffer(), row);
1932         if (is_rtl) {
1933                 pos_type body_pos = row->par()->beginningOfBody();
1934                 pos_type last = row->lastPos();
1935
1936                 if (body_pos > 0 &&
1937                     (body_pos - 1 > last ||
1938                      !row->par()->isLineSeparator(body_pos - 1))) {
1939                         x += font_metrics::width(layout->labelsep,
1940                                             getLabelFont(bv()->buffer(), row->par()));
1941                         if (body_pos - 1 <= last)
1942                                 x += fill_label_hfill;
1943                 }
1944         }
1945 }
1946
1947
1948 // important for the screen
1949
1950
1951 // the cursor set functions have a special mechanism. When they
1952 // realize, that you left an empty paragraph, they will delete it.
1953 // They also delete the corresponding row
1954
1955 void LyXText::cursorRightOneWord()
1956 {
1957         // treat floats, HFills and Insets as words
1958         LyXCursor tmpcursor = cursor;
1959         // CHECK See comment on top of text.C
1960
1961         if (tmpcursor.pos() == tmpcursor.par()->size()
1962             && tmpcursor.par()->next()) {
1963                         tmpcursor.par(tmpcursor.par()->next());
1964                         tmpcursor.pos(0);
1965         } else {
1966                 int steps = 0;
1967
1968                 // Skip through initial nonword stuff.
1969                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1970                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
1971                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
1972                         tmpcursor.pos(tmpcursor.pos() + 1);
1973                         ++steps;
1974                 }
1975                 // Advance through word.
1976                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1977                         tmpcursor.par()->isWord(tmpcursor.pos())) {
1978                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
1979                         tmpcursor.pos(tmpcursor.pos() + 1);
1980                         ++steps;
1981                 }
1982         }
1983         setCursor(tmpcursor.par(), tmpcursor.pos());
1984 }
1985
1986
1987 void LyXText::cursorTab()
1988 {
1989         LyXCursor tmpcursor = cursor;
1990         while (tmpcursor.pos() < tmpcursor.par()->size()
1991            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
1992         tmpcursor.pos(tmpcursor.pos() + 1);
1993
1994         if (tmpcursor.pos() == tmpcursor.par()->size()) {
1995                 if (tmpcursor.par()->next()) {
1996                         tmpcursor.par(tmpcursor.par()->next());
1997                         tmpcursor.pos(0);
1998                 }
1999         } else
2000                 tmpcursor.pos(tmpcursor.pos() + 1);
2001         setCursor(tmpcursor.par(), tmpcursor.pos());
2002 }
2003
2004
2005 // Skip initial whitespace at end of word and move cursor to *start*
2006 // of prior word, not to end of next prior word.
2007 void LyXText::cursorLeftOneWord()
2008 {
2009         LyXCursor tmpcursor = cursor;
2010         cursorLeftOneWord(tmpcursor);
2011         setCursor(tmpcursor.par(), tmpcursor.pos());
2012 }
2013
2014
2015 void LyXText::cursorLeftOneWord(LyXCursor & cur)
2016 {
2017         // treat HFills, floats and Insets as words
2018         cur = cursor;
2019         while (cur.pos()
2020                && (cur.par()->isSeparator(cur.pos() - 1)
2021                    || cur.par()->isKomma(cur.pos() - 1)
2022                    || cur.par()->isNewline(cur.pos() - 1))
2023                && !(cur.par()->isHfill(cur.pos() - 1)
2024                     || cur.par()->isInset(cur.pos() - 1)))
2025                 cur.pos(cur.pos() - 1);
2026
2027         if (cur.pos()
2028             && (cur.par()->isInset(cur.pos() - 1)
2029                 || cur.par()->isHfill(cur.pos() - 1))) {
2030                 cur.pos(cur.pos() - 1);
2031         } else if (!cur.pos()) {
2032                 if (cur.par()->previous()) {
2033                         cur.par(cur.par()->previous());
2034                         cur.pos(cur.par()->size());
2035                 }
2036         } else {                // Here, cur != 0
2037                 while (cur.pos() > 0 &&
2038                        cur.par()->isWord(cur.pos() - 1))
2039                         cur.pos(cur.pos() - 1);
2040         }
2041 }
2042
2043
2044 // Select current word. This depends on behaviour of
2045 // CursorLeftOneWord(), so it is patched as well.
2046 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
2047                       word_location const loc)
2048 {
2049         // first put the cursor where we wana start to select the word
2050         from = cursor;
2051         switch (loc) {
2052         case WHOLE_WORD_STRICT:
2053                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2054                     || cursor.par()->isSeparator(cursor.pos())
2055                     || cursor.par()->isKomma(cursor.pos())
2056                     || cursor.par()->isNewline(cursor.pos())
2057                     || cursor.par()->isSeparator(cursor.pos() - 1)
2058                     || cursor.par()->isKomma(cursor.pos() - 1)
2059                     || cursor.par()->isNewline(cursor.pos() - 1)) {
2060                         to = from;
2061                         return;
2062                 }
2063                 // no break here, we go to the next
2064
2065         case WHOLE_WORD:
2066                 // Move cursor to the beginning, when not already there.
2067                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2068                     && !(from.par()->isKomma(from.pos() - 1)
2069                          || from.par()->isNewline(from.pos() - 1)))
2070                         cursorLeftOneWord(from);
2071                 break;
2072         case PREVIOUS_WORD:
2073                 // always move the cursor to the beginning of previous word
2074                 cursorLeftOneWord(from);
2075                 break;
2076         case NEXT_WORD:
2077                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2078                 break;
2079         case PARTIAL_WORD:
2080                 break;
2081         }
2082         to = from;
2083         while (to.pos() < to.par()->size()
2084                && !to.par()->isSeparator(to.pos())
2085                && !to.par()->isKomma(to.pos())
2086                && !to.par()->isNewline(to.pos())
2087                && !to.par()->isHfill(to.pos())
2088                && !to.par()->isInset(to.pos()))
2089         {
2090                 to.pos(to.pos() + 1);
2091         }
2092 }
2093
2094
2095 void LyXText::selectWord(word_location loc)
2096 {
2097         LyXCursor from;
2098         LyXCursor to;
2099         getWord(from, to, loc);
2100         if (cursor != from)
2101                 setCursor(from.par(), from.pos());
2102         if (to == from)
2103                 return;
2104         selection.cursor = cursor;
2105         setCursor(to.par(), to.pos());
2106         setSelection();
2107 }
2108
2109
2110 // Select the word currently under the cursor when no
2111 // selection is currently set
2112 bool LyXText::selectWordWhenUnderCursor(word_location loc)
2113 {
2114         if (!selection.set()) {
2115                 selectWord(loc);
2116                 return selection.set();
2117         }
2118         return false;
2119 }
2120
2121
2122 void LyXText::acceptChange()
2123 {
2124         if (!selection.set() && cursor.par()->size())
2125                 return;
2126
2127         bv()->hideCursor();
2128
2129         if (selection.start.par() == selection.end.par()) {
2130                 LyXCursor & startc = selection.start;
2131                 LyXCursor & endc = selection.end;
2132                 setUndo(bv(), Undo::INSERT, startc.par(), startc.par()->next());
2133                 startc.par()->acceptChange(startc.pos(), endc.pos());
2134                 finishUndo();
2135                 clearSelection();
2136                 redoParagraphs(startc, startc.par()->next());
2137                 setCursorIntern(startc.par(), 0);
2138         }
2139 #warning handle multi par selection
2140 }
2141
2142
2143 void LyXText::rejectChange()
2144 {
2145         if (!selection.set() && cursor.par()->size())
2146                 return;
2147
2148         bv()->hideCursor();
2149
2150         if (selection.start.par() == selection.end.par()) {
2151                 LyXCursor & startc = selection.start;
2152                 LyXCursor & endc = selection.end;
2153                 setUndo(bv(), Undo::INSERT, startc.par(), startc.par()->next());
2154                 startc.par()->rejectChange(startc.pos(), endc.pos());
2155                 finishUndo();
2156                 clearSelection();
2157                 redoParagraphs(startc, startc.par()->next());
2158                 setCursorIntern(startc.par(), 0);
2159         }
2160 #warning handle multi par selection
2161 }
2162
2163
2164 // This function is only used by the spellchecker for NextWord().
2165 // It doesn't handle LYX_ACCENTs and probably never will.
2166 WordLangTuple const
2167 LyXText::selectNextWordToSpellcheck(float & value)
2168 {
2169         if (the_locking_inset) {
2170                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
2171                 if (!word.word().empty()) {
2172                         value += float(cursor.y());
2173                         value /= float(height);
2174                         return word;
2175                 }
2176                 // we have to go on checking so move cursor to the next char
2177                 if (cursor.pos() == cursor.par()->size()) {
2178                         if (!cursor.par()->next())
2179                                 return word;
2180                         cursor.par(cursor.par()->next());
2181                         cursor.pos(0);
2182                 } else
2183                         cursor.pos(cursor.pos() + 1);
2184         }
2185         Paragraph * tmppar = cursor.par();
2186
2187         // If this is not the very first word, skip rest of
2188         // current word because we are probably in the middle
2189         // of a word if there is text here.
2190         if (cursor.pos() || cursor.par()->previous()) {
2191                 while (cursor.pos() < cursor.par()->size()
2192                        && cursor.par()->isLetter(cursor.pos()))
2193                         cursor.pos(cursor.pos() + 1);
2194         }
2195
2196         // Now, skip until we have real text (will jump paragraphs)
2197         while (1) {
2198                 Paragraph * cpar(cursor.par());
2199                 pos_type const cpos(cursor.pos());
2200
2201                 if (cpos == cpar->size()) {
2202                         if (cpar->next()) {
2203                                 cursor.par(cpar->next());
2204                                 cursor.pos(0);
2205                                 continue;
2206                         }
2207                         break;
2208                 }
2209
2210                 bool const is_bad_inset(cpar->isInset(cpos)
2211                         && !cpar->getInset(cpos)->allowSpellcheck());
2212
2213                 if (cpar->isLetter(cpos) && !isDeletedText(*cpar, cpos)
2214                         && !is_bad_inset)
2215                         break;
2216
2217                 cursor.pos(cpos + 1);
2218         }
2219
2220         // now check if we hit an inset so it has to be a inset containing text!
2221         if (cursor.pos() < cursor.par()->size() &&
2222             cursor.par()->isInset(cursor.pos())) {
2223                 // lock the inset!
2224                 cursor.par()->getInset(cursor.pos())->edit(bv());
2225                 // now call us again to do the above trick
2226                 // but obviously we have to start from down below ;)
2227                 return bv()->text->selectNextWordToSpellcheck(value);
2228         }
2229
2230         // Update the value if we changed paragraphs
2231         if (cursor.par() != tmppar) {
2232                 setCursor(cursor.par(), cursor.pos());
2233                 value = float(cursor.y())/float(height);
2234         }
2235
2236         // Start the selection from here
2237         selection.cursor = cursor;
2238
2239         string lang_code(
2240                 getFont(bv()->buffer(), cursor.par(), cursor.pos())
2241                         .language()->code());
2242         // and find the end of the word (insets like optional hyphens
2243         // and ligature break are part of a word)
2244         while (cursor.pos() < cursor.par()->size()
2245                && cursor.par()->isLetter(cursor.pos())
2246                && !isDeletedText(*cursor.par(), cursor.pos()))
2247                 cursor.pos(cursor.pos() + 1);
2248
2249         // Finally, we copy the word to a string and return it
2250         string str;
2251         if (selection.cursor.pos() < cursor.pos()) {
2252                 pos_type i;
2253                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2254                         if (!cursor.par()->isInset(i))
2255                                 str += cursor.par()->getChar(i);
2256                 }
2257         }
2258         return WordLangTuple(str, lang_code);
2259 }
2260
2261
2262 // This one is also only for the spellchecker
2263 void LyXText::selectSelectedWord()
2264 {
2265         if (the_locking_inset) {
2266                 the_locking_inset->selectSelectedWord(bv());
2267                 return;
2268         }
2269         // move cursor to the beginning
2270         setCursor(selection.cursor.par(), selection.cursor.pos());
2271
2272         // set the sel cursor
2273         selection.cursor = cursor;
2274
2275         // now find the end of the word
2276         while (cursor.pos() < cursor.par()->size()
2277                && (cursor.par()->isLetter(cursor.pos())))
2278                 cursor.pos(cursor.pos() + 1);
2279
2280         setCursor(cursor.par(), cursor.pos());
2281
2282         // finally set the selection
2283         setSelection();
2284 }
2285
2286
2287 // Delete from cursor up to the end of the current or next word.
2288 void LyXText::deleteWordForward()
2289 {
2290         if (cursor.par()->empty())
2291                 cursorRight(bv());
2292         else {
2293                 LyXCursor tmpcursor = cursor;
2294                 tmpcursor.row(0); // ??
2295                 selection.set(true); // to avoid deletion
2296                 cursorRightOneWord();
2297                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2298                 selection.cursor = cursor;
2299                 cursor = tmpcursor;
2300                 setSelection();
2301
2302                 // Great, CutSelection() gets rid of multiple spaces.
2303                 cutSelection(true, false);
2304         }
2305 }
2306
2307
2308 // Delete from cursor to start of current or prior word.
2309 void LyXText::deleteWordBackward()
2310 {
2311         if (cursor.par()->empty())
2312                 cursorLeft(bv());
2313         else {
2314                 LyXCursor tmpcursor = cursor;
2315                 tmpcursor.row(0); // ??
2316                 selection.set(true); // to avoid deletion
2317                 cursorLeftOneWord();
2318                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2319                 selection.cursor = cursor;
2320                 cursor = tmpcursor;
2321                 setSelection();
2322                 cutSelection(true, false);
2323         }
2324 }
2325
2326
2327 // Kill to end of line.
2328 void LyXText::deleteLineForward()
2329 {
2330         if (cursor.par()->empty())
2331                 // Paragraph is empty, so we just go to the right
2332                 cursorRight(bv());
2333         else {
2334                 LyXCursor tmpcursor = cursor;
2335                 // We can't store the row over a regular setCursor
2336                 // so we set it to 0 and reset it afterwards.
2337                 tmpcursor.row(0); // ??
2338                 selection.set(true); // to avoid deletion
2339                 cursorEnd();
2340                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2341                 selection.cursor = cursor;
2342                 cursor = tmpcursor;
2343                 setSelection();
2344                 // What is this test for ??? (JMarc)
2345                 if (!selection.set()) {
2346                         deleteWordForward();
2347                 } else {
2348                         cutSelection(true, false);
2349                 }
2350         }
2351 }
2352
2353
2354 void LyXText::changeCase(LyXText::TextCase action)
2355 {
2356         LyXCursor from;
2357         LyXCursor to;
2358
2359         if (selection.set()) {
2360                 from = selection.start;
2361                 to = selection.end;
2362         } else {
2363                 getWord(from, to, PARTIAL_WORD);
2364                 setCursor(to.par(), to.pos() + 1);
2365         }
2366
2367         lyx::Assert(from <= to);
2368
2369         setUndo(bv(), Undo::FINISH, from.par(), to.par()->next());
2370
2371         pos_type pos = from.pos();
2372         Paragraph * par = from.par();
2373
2374         while (par && (pos != to.pos() || par != to.par())) {
2375                 if (pos == par->size()) {
2376                         par = par->next();
2377                         pos = 0;
2378                         continue;
2379                 }
2380                 unsigned char c = par->getChar(pos);
2381                 if (!IsInsetChar(c)) {
2382                         switch (action) {
2383                         case text_lowercase:
2384                                 c = lowercase(c);
2385                                 break;
2386                         case text_capitalization:
2387                                 c = uppercase(c);
2388                                 action = text_lowercase;
2389                                 break;
2390                         case text_uppercase:
2391                                 c = uppercase(c);
2392                                 break;
2393                         }
2394                 }
2395 #warning changes
2396                 par->setChar(pos, c);
2397                 checkParagraph(par, pos);
2398
2399                 ++pos;
2400         }
2401
2402         if (to.row() != from.row())
2403                 postPaint(from.y() - from.row()->baseline());
2404 }
2405
2406
2407 void LyXText::transposeChars()
2408 {
2409         Paragraph * tmppar = cursor.par();
2410
2411         setUndo(bv(), Undo::FINISH, tmppar, tmppar->next());
2412
2413         pos_type tmppos = cursor.pos();
2414
2415         // First decide if it is possible to transpose at all
2416
2417         if (tmppos == 0 || tmppos == tmppar->size())
2418                 return;
2419
2420         if (isDeletedText(*tmppar, tmppos - 1)
2421                 || isDeletedText(*tmppar, tmppos))
2422                 return;
2423
2424         unsigned char c1 = tmppar->getChar(tmppos);
2425         unsigned char c2 = tmppar->getChar(tmppos - 1);
2426
2427         // We should have an implementation that handles insets
2428         // as well, but that will have to come later. (Lgb)
2429         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET)
2430                 return;
2431
2432         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2433         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2434
2435         tmppar->insertChar(ipos, c1);
2436         tmppar->insertChar(ipos + 1, c2);
2437
2438         checkParagraph(tmppar, tmppos);
2439 }
2440
2441
2442 void LyXText::Delete()
2443 {
2444         // this is a very easy implementation
2445
2446         LyXCursor old_cursor = cursor;
2447         int const old_cur_par_id = old_cursor.par()->id();
2448         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2449                 old_cursor.par()->previous()->id() : -1;
2450
2451         // just move to the right
2452         cursorRight(bv());
2453
2454         // CHECK Look at the comment here.
2455         // This check is not very good...
2456         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2457         // and that can very well delete the par or par->previous in
2458         // old_cursor. Will a solution where we compare paragraph id's
2459         //work better?
2460         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2461             == old_cur_par_prev_id
2462             && cursor.par()->id() != old_cur_par_id) {
2463                 // delete-empty-paragraph-mechanism has done it
2464                 return;
2465         }
2466
2467         // if you had success make a backspace
2468         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2469                 LyXCursor tmpcursor = cursor;
2470                 // to make sure undo gets the right cursor position
2471                 cursor = old_cursor;
2472                 setUndo(bv(), Undo::DELETE,
2473                         cursor.par(), cursor.par()->next());
2474                 cursor = tmpcursor;
2475                 backspace();
2476         }
2477 }
2478
2479
2480 void LyXText::backspace()
2481 {
2482         // Get the font that is used to calculate the baselineskip
2483         pos_type lastpos = cursor.par()->size();
2484         LyXFont rawparfont =
2485                 cursor.par()->getFontSettings(bv()->buffer()->params,
2486                                               lastpos - 1);
2487
2488         if (cursor.pos() == 0) {
2489                 // The cursor is at the beginning of a paragraph,
2490                 // so the the backspace will collapse two paragraphs into one.
2491
2492                 // but it's not allowed unless it's new
2493                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2494                         return;
2495
2496                 // we may paste some paragraphs
2497
2498                 // is it an empty paragraph?
2499
2500                 if ((lastpos == 0
2501                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2502                         // This is an empty paragraph and we delete it just by moving the cursor one step
2503                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2504                         // of the paragraph.
2505
2506                         if (cursor.par()->previous()) {
2507                                 Paragraph * tmppar = cursor.par()->previous();
2508                                 if (cursor.par()->layout() == tmppar->layout()
2509                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2510                                         // Inherit bottom DTD from the paragraph below.
2511                                         // (the one we are deleting)
2512                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2513                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2514                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2515                                 }
2516
2517                                 cursorLeft(bv());
2518
2519                                 // the layout things can change the height of a row !
2520                                 int const tmpheight = cursor.row()->height();
2521                                 setHeightOfRow(cursor.row());
2522                                 if (cursor.row()->height() != tmpheight) {
2523                                         postPaint(cursor.y() - cursor.row()->baseline());
2524                                 }
2525                                 return;
2526                         }
2527                 }
2528
2529                 if (cursor.par()->previous()) {
2530                         setUndo(bv(), Undo::DELETE,
2531                                 cursor.par()->previous(), cursor.par()->next());
2532                 }
2533
2534                 Paragraph * tmppar = cursor.par();
2535                 Row * tmprow = cursor.row();
2536
2537                 // We used to do cursorLeftIntern() here, but it is
2538                 // not a good idea since it triggers the auto-delete
2539                 // mechanism. So we do a cursorLeftIntern()-lite,
2540                 // without the dreaded mechanism. (JMarc)
2541                 if (cursor.par()->previous()) {
2542                         // steps into the above paragraph.
2543                         setCursorIntern(cursor.par()->previous(),
2544                                         cursor.par()->previous()->size(),
2545                                         false);
2546                 }
2547
2548                 // Pasting is not allowed, if the paragraphs have different
2549                 // layout. I think it is a real bug of all other
2550                 // word processors to allow it. It confuses the user.
2551                 // Even so with a footnote paragraph and a non-footnote
2552                 // paragraph. I will not allow pasting in this case,
2553                 // because the user would be confused if the footnote behaves
2554                 // different wether it is open or closed.
2555
2556                 //      Correction: Pasting is always allowed with standard-layout
2557                 LyXTextClass const & tclass =
2558                         bv()->buffer()->params.getLyXTextClass();
2559
2560                 if (cursor.par() != tmppar
2561                     && (cursor.par()->layout() == tmppar->layout()
2562                         || tmppar->layout() == tclass.defaultLayout())
2563                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2564                         removeParagraph(tmprow);
2565                         removeRow(tmprow);
2566                         mergeParagraph(bv()->buffer()->params, bv()->buffer()->paragraphs, cursor.par());
2567
2568                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2569                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2570                         // strangely enough it seems that commenting out the line above removes
2571                         // most or all of the segfaults. I will however also try to move the
2572                         // two Remove... lines in front of the PasteParagraph too.
2573                         else
2574                                 if (cursor.pos())
2575                                         cursor.pos(cursor.pos() - 1);
2576
2577                         postPaint(cursor.y() - cursor.row()->baseline());
2578
2579                         // remove the lost paragraph
2580                         // This one is not safe, since the paragraph that the tmprow and the
2581                         // following rows belong to has been deleted by the PasteParagraph
2582                         // above. The question is... could this be moved in front of the
2583                         // PasteParagraph?
2584                         //RemoveParagraph(tmprow);
2585                         //RemoveRow(tmprow);
2586
2587                         // This rebuilds the rows.
2588                         appendParagraph(cursor.row());
2589                         updateCounters();
2590
2591                         // the row may have changed, block, hfills etc.
2592                         setCursor(cursor.par(), cursor.pos(), false);
2593                 }
2594         } else {
2595                 // this is the code for a normal backspace, not pasting
2596                 // any paragraphs
2597                 setUndo(bv(), Undo::DELETE,
2598                         cursor.par(), cursor.par()->next());
2599                 // We used to do cursorLeftIntern() here, but it is
2600                 // not a good idea since it triggers the auto-delete
2601                 // mechanism. So we do a cursorLeftIntern()-lite,
2602                 // without the dreaded mechanism. (JMarc)
2603                 setCursorIntern(cursor.par(), cursor.pos()- 1,
2604                                 false, cursor.boundary());
2605
2606                 if (cursor.par()->isInset(cursor.pos())) {
2607                         // force complete redo when erasing display insets
2608                         // this is a cruel method but safe..... Matthias
2609                         if (cursor.par()->getInset(cursor.pos())->display() ||
2610                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2611                                 cursor.par()->erase(cursor.pos());
2612                                 redoParagraph();
2613                                 return;
2614                         }
2615                 }
2616
2617                 Row * row = cursor.row();
2618                 int y = cursor.y() - row->baseline();
2619                 pos_type z;
2620                 // remember that a space at the end of a row doesnt count
2621                 // when calculating the fill
2622                 if (cursor.pos() < row->lastPos() ||
2623                     !cursor.par()->isLineSeparator(cursor.pos())) {
2624                         row->fill(row->fill() + singleWidth(
2625                                                             cursor.par(),
2626                                                             cursor.pos()));
2627                 }
2628
2629                 // some special code when deleting a newline. This is similar
2630                 // to the behavior when pasting paragraphs
2631                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2632                         cursor.par()->erase(cursor.pos());
2633                         // refresh the positions
2634                         Row * tmprow = row;
2635                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2636                                 tmprow = tmprow->next();
2637                                 tmprow->pos(tmprow->pos() - 1);
2638                         }
2639                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2640                                 cursor.pos(cursor.pos() - 1);
2641
2642                         if (cursor.pos() < cursor.par()->size()
2643                             && !cursor.par()->isSeparator(cursor.pos())) {
2644                                 cursor.par()->insertChar(cursor.pos(), ' ');
2645                                 setCharFont(bv()->buffer(), cursor.par(),
2646                                             cursor.pos(), current_font);
2647                                 // refresh the positions
2648                                 tmprow = row;
2649                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2650                                         tmprow = tmprow->next();
2651                                         tmprow->pos(tmprow->pos() + 1);
2652                                 }
2653                         }
2654                 } else {
2655                         cursor.par()->erase(cursor.pos());
2656
2657                         // refresh the positions
2658                         Row * tmprow = row;
2659                         while (tmprow->next()
2660                                && tmprow->next()->par() == row->par()) {
2661                                 tmprow = tmprow->next();
2662                                 tmprow->pos(tmprow->pos() - 1);
2663                         }
2664
2665                         // delete newlines at the beginning of paragraphs
2666                         while (!cursor.par()->empty() &&
2667                                cursor.pos() < cursor.par()->size() &&
2668                                cursor.par()->isNewline(cursor.pos()) &&
2669                                cursor.pos() == cursor.par()->beginningOfBody()) {
2670                                 cursor.par()->erase(cursor.pos());
2671                                 // refresh the positions
2672                                 tmprow = row;
2673                                 while (tmprow->next() &&
2674                                        tmprow->next()->par() == row->par()) {
2675                                         tmprow = tmprow->next();
2676                                         tmprow->pos(tmprow->pos() - 1);
2677                                 }
2678                         }
2679                 }
2680
2681                 // is there a break one row above
2682                 if (row->previous() && row->previous()->par() == row->par()) {
2683                         z = rowBreakPoint(*row->previous());
2684                         if (z >= row->pos()) {
2685                                 row->pos(z + 1);
2686
2687                                 Row * tmprow = row->previous();
2688
2689                                 // maybe the current row is now empty
2690                                 if (row->pos() >= row->par()->size()) {
2691                                         // remove it
2692                                         removeRow(row);
2693                                         need_break_row = 0;
2694                                 } else {
2695                                         breakAgainOneRow(row);
2696                                         if (row->next() && row->next()->par() == row->par())
2697                                                 need_break_row = row->next();
2698                                         else
2699                                                 need_break_row = 0;
2700                                 }
2701
2702                                 // set the dimensions of the row above
2703                                 y -= tmprow->height();
2704                                 tmprow->fill(fill(*tmprow, workWidth()));
2705                                 setHeightOfRow(tmprow);
2706
2707                                 postPaint(y);
2708
2709                                 setCursor(cursor.par(), cursor.pos(),
2710                                           false, cursor.boundary());
2711                                 //current_font = rawtmpfont;
2712                                 //real_current_font = realtmpfont;
2713                                 // check, whether the last character's font has changed.
2714                                 if (rawparfont !=
2715                                     cursor.par()->getFontSettings(bv()->buffer()->params,
2716                                                                   cursor.par()->size() - 1))
2717                                         redoHeightOfParagraph();
2718                                 return;
2719                         }
2720                 }
2721
2722                 // break the cursor row again
2723                 if (row->next() && row->next()->par() == row->par() &&
2724                     (row->lastPos() == row->par()->size() - 1 ||
2725                      rowBreakPoint(*row) != row->lastPos())) {
2726
2727                         // it can happen that a paragraph loses one row
2728                         // without a real breakup. This is when a word
2729                         // is to long to be broken. Well, I don t care this
2730                         // hack ;-)
2731                         if (row->lastPos() == row->par()->size() - 1)
2732                                 removeRow(row->next());
2733
2734                         postPaint(y);
2735
2736                         breakAgainOneRow(row);
2737                         // will the cursor be in another row now?
2738                         if (row->next() && row->next()->par() == row->par() &&
2739                             row->lastPos() <= cursor.pos()) {
2740                                 row = row->next();
2741                                 breakAgainOneRow(row);
2742                         }
2743
2744                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2745
2746                         if (row->next() && row->next()->par() == row->par())
2747                                 need_break_row = row->next();
2748                         else
2749                                 need_break_row = 0;
2750                 } else  {
2751                         // set the dimensions of the row
2752                         row->fill(fill(*row, workWidth()));
2753                         int const tmpheight = row->height();
2754                         setHeightOfRow(row);
2755                         if (tmpheight == row->height()) {
2756                                 postRowPaint(row, y);
2757                         } else {
2758                                 postPaint(y);
2759                         }
2760                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2761                 }
2762         }
2763
2764         // current_font = rawtmpfont;
2765         // real_current_font = realtmpfont;
2766
2767         if (isBoundary(bv()->buffer(), cursor.par(), cursor.pos())
2768             != cursor.boundary())
2769                 setCursor(cursor.par(), cursor.pos(), false,
2770                           !cursor.boundary());
2771
2772         lastpos = cursor.par()->size();
2773         if (cursor.pos() == lastpos)
2774                 setCurrentFont();
2775
2776         // check, whether the last characters font has changed.
2777         if (rawparfont !=
2778             cursor.par()->getFontSettings(bv()->buffer()->params, lastpos - 1)) {
2779                 redoHeightOfParagraph();
2780         } else {
2781                 // now the special right address boxes
2782                 if (cursor.par()->layout()->margintype
2783                     == MARGIN_RIGHT_ADDRESS_BOX) {
2784                         redoDrawingOfParagraph(cursor);
2785                 }
2786         }
2787 }
2788
2789
2790 // returns pointer to a specified row
2791 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
2792 {
2793         if (!firstrow)
2794                 return 0;
2795
2796         Row * tmprow = firstrow;
2797         y = 0;
2798
2799         // find the first row of the specified paragraph
2800         while (tmprow->next() && tmprow->par() != par) {
2801                 y += tmprow->height();
2802                 tmprow = tmprow->next();
2803         }
2804
2805         // now find the wanted row
2806         while (tmprow->pos() < pos
2807                && tmprow->next()
2808                && tmprow->next()->par() == par
2809                && tmprow->next()->pos() <= pos) {
2810                 y += tmprow->height();
2811                 tmprow = tmprow->next();
2812         }
2813
2814         return tmprow;
2815 }
2816
2817
2818 Row * LyXText::getRowNearY(int & y) const
2819 {
2820 #if 1
2821         // If possible we should optimize this method. (Lgb)
2822         Row * tmprow = firstrow;
2823         int tmpy = 0;
2824
2825         while (tmprow->next() && tmpy + tmprow->height() <= y) {
2826                 tmpy += tmprow->height();
2827                 tmprow = tmprow->next();
2828         }
2829
2830         y = tmpy;   // return the real y
2831
2832         //lyxerr << "returned y = " << y << endl;
2833
2834         return tmprow;
2835 #else
2836         // Search from the current cursor position.
2837
2838         Row * tmprow = cursor.row();
2839         int tmpy = cursor.y() - tmprow->baseline();
2840
2841         lyxerr << "cursor.y() = " << tmpy << endl;
2842         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
2843         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
2844         lyxerr << "first = " << first << endl;
2845         lyxerr << "y = " << y << endl;
2846
2847         if (y < tmpy) {
2848                 lyxerr << "up" << endl;
2849                 do {
2850                         tmpy -= tmprow->height();
2851                         tmprow = tmprow->previous();
2852                 } while (tmprow && tmpy - tmprow->height() >= y);
2853         } else if (y > tmpy) {
2854                 lyxerr << "down" << endl;
2855
2856                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
2857                         tmpy += tmprow->height();
2858                         tmprow = tmprow->next();
2859                 }
2860         } else {
2861                 lyxerr << "equal" << endl;
2862         }
2863
2864         y = tmpy; // return the real y
2865
2866         lyxerr << "returned y = " << y << endl;
2867
2868         return tmprow;
2869
2870 #endif
2871 }
2872
2873
2874 int LyXText::getDepth() const
2875 {
2876         return cursor.par()->getDepth();
2877 }