]> git.lyx.org Git - lyx.git/blob - src/text.C
pass mouse clicks also to insets "close enough"
[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
36 #include "insets/insettext.h"
37
38 #include "support/textutils.h"
39 #include "support/LAssert.h"
40 #include "support/lstrings.h"
41
42 #include <algorithm>
43
44 using std::max;
45 using std::min;
46 using std::endl;
47 using std::pair;
48 using lyx::pos_type;
49
50 namespace {
51
52 /// top, right, bottom pixel margin
53 int const PAPER_MARGIN = 20;
54 /// margin for changebar
55 int const CHANGEBAR_MARGIN = 10;
56 /// left margin
57 int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
58
59 } // namespace anon
60
61 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
62
63
64 int LyXText::workWidth(BufferView * bview) const
65 {
66         if (inset_owner) {
67                 return inset_owner->textWidth(bview);
68         }
69         return bview->workWidth();
70 }
71
72
73 int LyXText::workWidth(BufferView * bview, Inset * inset) const
74 {
75         Paragraph * par = 0;
76         pos_type pos = -1;
77
78         par = inset->parOwner();
79         if (par)
80                 pos = par->getPositionOfInset(inset);
81
82         if (!par || pos == -1) {
83                 lyxerr << "LyXText::workWidth: something is wrong,"
84                         " fall back to the brute force method" << endl;
85                 Buffer::inset_iterator it = bview->buffer()->inset_iterator_begin();
86                 Buffer::inset_iterator end = bview->buffer()->inset_iterator_end();
87                 for (; it != end; ++it) {
88                         if (&(*it) == inset) {
89                                 par = it.getPar();
90                                 pos = it.getPos();
91                                 break;
92                         }
93                 }
94         }
95
96         if (!par) {
97                 return workWidth(bview);
98         }
99
100         LyXLayout_ptr const & layout = par->layout();
101
102         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
103                 // Optimization here: in most cases, the real row is
104                 // not needed, but only the par/pos values. So we just
105                 // construct a dummy row for leftMargin. (JMarc)
106                 Row dummyrow;
107                 dummyrow.par(par);
108                 dummyrow.pos(pos);
109                 return workWidth(bview) - leftMargin(bview, &dummyrow);
110         } else {
111                 int dummy_y;
112                 Row * row = getRow(par, pos, dummy_y);
113                 Row * frow = row;
114                 while (frow->previous() && frow->par() == frow->previous()->par())
115                         frow = frow->previous();
116                 unsigned int maxw = 0;
117                 while (frow->next() && frow->par() == frow->next()->par()) {
118                         if ((frow != row) && (maxw < frow->width()))
119                                 maxw = frow->width();
120                         frow = frow->next();
121                 }
122                 if (maxw)
123                         return maxw;
124         }
125         return workWidth(bview);
126 }
127
128
129 int LyXText::getRealCursorX(BufferView * bview) const
130 {
131         int x = cursor.x();
132         if (the_locking_inset && (the_locking_inset->getLyXText(bview)!=this))
133                 x = the_locking_inset->getLyXText(bview)->getRealCursorX(bview);
134         return x;
135 }
136
137
138 unsigned char LyXText::transformChar(unsigned char c, Paragraph * par,
139                         pos_type pos) const
140 {
141         if (!Encodings::is_arabic(c))
142                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
143                         return c + (0xb0 - '0');
144                 else
145                         return c;
146
147         unsigned char const prev_char = pos > 0 ? par->getChar(pos-1) : ' ';
148         unsigned char next_char = ' ';
149
150         for (pos_type i = pos+1; i < par->size(); ++i)
151                 if (!Encodings::IsComposeChar_arabic(par->getChar(i))) {
152                         next_char = par->getChar(i);
153                         break;
154                 }
155
156         if (Encodings::is_arabic(next_char)) {
157                 if (Encodings::is_arabic(prev_char) &&
158                         !Encodings::is_arabic_special(prev_char))
159                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
160                 else
161                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
162         } else {
163                 if (Encodings::is_arabic(prev_char) &&
164                         !Encodings::is_arabic_special(prev_char))
165                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
166                 else
167                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
168         }
169 }
170
171 // This is the comments that some of the warnings below refers to.
172 // There are some issues in this file and I don't think they are
173 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
174 // this is a problem that has been here almost from day one and that a
175 // larger userbase with differenct access patters triggers the bad
176 // behaviour. (segfaults.) What I think happen is: In several places
177 // we store the paragraph in the current cursor and then moves the
178 // cursor. This movement of the cursor will delete paragraph at the
179 // old position if it is now empty. This will make the temporary
180 // pointer to the old cursor paragraph invalid and dangerous to use.
181 // And is some cases this will trigger a segfault. I have marked some
182 // of the cases where this happens with a warning, but I am sure there
183 // are others in this file and in text2.C. There is also a note in
184 // Delete() that you should read. In Delete I store the paragraph->id
185 // instead of a pointer to the paragraph. I am pretty sure this faulty
186 // use of temporary pointers to paragraphs that might have gotten
187 // invalidated (through a cursor movement) before they are used, are
188 // the cause of the strange crashes we get reported often.
189 //
190 // It is very tiresom to change this code, especially when it is as
191 // hard to read as it is. Help to fix all the cases where this is done
192 // would be greately appreciated.
193 //
194 // Lgb
195
196 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
197                          pos_type pos) const
198 {
199         char const c = par->getChar(pos);
200         return singleWidth(bview, par, pos, c);
201 }
202
203
204 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
205                          pos_type pos, char c) const
206 {
207         LyXFont const font = getFont(bview->buffer(), par, pos);
208
209         // The most common case is handled first (Asger)
210         if (IsPrintable(c)) {
211                 if (font.language()->RightToLeft()) {
212                         if (font.language()->lang() == "arabic" &&
213                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
214                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
215                                 if (Encodings::IsComposeChar_arabic(c))
216                                         return 0;
217                                 else
218                                         c = transformChar(c, par, pos);
219                         else if (font.language()->lang() == "hebrew" &&
220                                  Encodings::IsComposeChar_hebrew(c))
221                                 return 0;
222                 }
223                 return font_metrics::width(c, font);
224
225         } else if (IsHfillChar(c)) {
226                 // Because of the representation as vertical lines
227                 return 3;
228         } else if (c == Paragraph::META_INSET) {
229                 Inset * tmpinset = par->getInset(pos);
230                 if (tmpinset) {
231 #if 1
232                         // this IS needed otherwise on initialitation we don't get the fill
233                         // of the row right (ONLY on initialization if we read a file!)
234                         // should be changed! (Jug 20011204)
235                         tmpinset->update(bview, font);
236 #endif
237                         return tmpinset->width(bview, font);
238                 } else
239                         return 0;
240
241         } else if (IsSeparatorChar(c))
242                 c = ' ';
243         else if (IsNewlineChar(c))
244                 c = 'n';
245         return font_metrics::width(c, font);
246 }
247
248
249 void LyXText::computeBidiTables(Buffer const * buf, Row * row) const
250 {
251         bidi_same_direction = true;
252         if (!lyxrc.rtl_support) {
253                 bidi_start = -1;
254                 return;
255         }
256
257         Inset * inset = row->par()->inInset();
258         if (inset && inset->owner() &&
259             inset->owner()->lyxCode() == Inset::ERT_CODE) {
260                 bidi_start = -1;
261                 return;
262         }
263
264         bidi_start = row->pos();
265         bidi_end = row->lastPrintablePos();
266
267         if (bidi_start > bidi_end) {
268                 bidi_start = -1;
269                 return;
270         }
271
272         if (bidi_end + 2 - bidi_start >
273             static_cast<pos_type>(log2vis_list.size())) {
274                 pos_type new_size =
275                         (bidi_end + 2 - bidi_start < 500) ?
276                         500 : 2 * (bidi_end + 2 - bidi_start);
277                 log2vis_list.resize(new_size);
278                 vis2log_list.resize(new_size);
279                 bidi_levels.resize(new_size);
280         }
281
282         vis2log_list[bidi_end + 1 - bidi_start] = -1;
283         log2vis_list[bidi_end + 1 - bidi_start] = -1;
284
285         pos_type stack[2];
286         bool const rtl_par =
287                 row->par()->isRightToLeftPar(buf->params);
288         int level = 0;
289         bool rtl = false;
290         bool rtl0 = false;
291         pos_type const main_body = row->par()->beginningOfMainBody();
292
293         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
294                 bool is_space = row->par()->isLineSeparator(lpos);
295                 pos_type const pos =
296                         (is_space && lpos + 1 <= bidi_end &&
297                          !row->par()->isLineSeparator(lpos + 1) &&
298                          !row->par()->isNewline(lpos + 1))
299                         ? lpos + 1 : lpos;
300                 LyXFont font = row->par()->getFontSettings(buf->params, pos);
301                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
302                     font.number() == LyXFont::ON &&
303                     row->par()->getFontSettings(buf->params, lpos - 1).number()
304                     == LyXFont::ON) {
305                         font = row->par()->getFontSettings(buf->params, lpos);
306                         is_space = false;
307                 }
308
309
310                 bool new_rtl = font.isVisibleRightToLeft();
311                 bool new_rtl0 = font.isRightToLeft();
312                 int new_level;
313
314                 if (lpos == main_body - 1
315                     && row->pos() < main_body - 1
316                     && is_space) {
317                         new_level = (rtl_par) ? 1 : 0;
318                         new_rtl = new_rtl0 = rtl_par;
319                 } else if (new_rtl0)
320                         new_level = (new_rtl) ? 1 : 2;
321                 else
322                         new_level = (rtl_par) ? 2 : 0;
323
324                 if (is_space && new_level >= level) {
325                         new_level = level;
326                         new_rtl = rtl;
327                         new_rtl0 = rtl0;
328                 }
329
330                 int new_level2 = new_level;
331
332                 if (level == new_level && rtl0 != new_rtl0) {
333                         --new_level2;
334                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
335                 } else if (level < new_level) {
336                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
337                         if (new_level > rtl_par)
338                                 bidi_same_direction = false;
339                 } else
340                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
341                 rtl = new_rtl;
342                 rtl0 = new_rtl0;
343                 bidi_levels[lpos - bidi_start] = new_level;
344
345                 while (level > new_level2) {
346                         pos_type old_lpos = stack[--level];
347                         int delta = lpos - old_lpos - 1;
348                         if (level % 2)
349                                 delta = -delta;
350                         log2vis_list[lpos - bidi_start] += delta;
351                         log2vis_list[old_lpos - bidi_start] += delta;
352                 }
353                 while (level < new_level)
354                         stack[level++] = lpos;
355         }
356
357         while (level > 0) {
358                 pos_type const old_lpos = stack[--level];
359                 int delta = bidi_end - old_lpos;
360                 if (level % 2)
361                         delta = -delta;
362                 log2vis_list[old_lpos - bidi_start] += delta;
363         }
364
365         pos_type vpos = bidi_start - 1;
366         for (pos_type lpos = bidi_start;
367              lpos <= bidi_end; ++lpos) {
368                 vpos += log2vis_list[lpos - bidi_start];
369                 vis2log_list[vpos - bidi_start] = lpos;
370                 log2vis_list[lpos - bidi_start] = vpos;
371         }
372 }
373
374
375 // This method requires a previous call to ComputeBidiTables()
376 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
377                          pos_type pos) const
378 {
379         if (!lyxrc.rtl_support || pos == 0)
380                 return false;
381
382         if (!bidi_InRange(pos - 1)) {
383                 /// This can happen if pos is the first char of a row.
384                 /// Returning false in this case is incorrect!
385                 return false;
386         }
387
388         bool const rtl = bidi_level(pos - 1) % 2;
389         bool const rtl2 = bidi_InRange(pos)
390                 ? bidi_level(pos) % 2
391                 : par->isRightToLeftPar(buf->params);
392         return rtl != rtl2;
393 }
394
395
396 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
397                          pos_type pos, LyXFont const & font) const
398 {
399         if (!lyxrc.rtl_support)
400                 return false;    // This is just for speedup
401
402         bool const rtl = font.isVisibleRightToLeft();
403         bool const rtl2 = bidi_InRange(pos)
404                 ? bidi_level(pos) % 2
405                 : par->isRightToLeftPar(buf->params);
406         return rtl != rtl2;
407 }
408
409
410 void LyXText::drawNewline(DrawRowParams & p, pos_type const pos)
411 {
412         // Draw end-of-line marker
413         LyXFont const font = getFont(p.bv->buffer(), p.row->par(), pos);
414         int const wid = font_metrics::width('n', font);
415         int const asc = font_metrics::maxAscent(font);
416         int const y = p.yo + p.row->baseline();
417         int xp[3];
418         int yp[3];
419
420         yp[0] = int(y - 0.875 * asc * 0.75);
421         yp[1] = int(y - 0.500 * asc * 0.75);
422         yp[2] = int(y - 0.125 * asc * 0.75);
423
424         if (bidi_level(pos) % 2 == 0) {
425                 xp[0] = int(p.x + wid * 0.375);
426                 xp[1] = int(p.x);
427                 xp[2] = int(p.x + wid * 0.375);
428         } else {
429                 xp[0] = int(p.x + wid * 0.625);
430                 xp[1] = int(p.x + wid);
431                 xp[2] = int(p.x + wid * 0.625);
432         }
433
434         p.pain->lines(xp, yp, 3, LColor::eolmarker);
435
436         yp[0] = int(y - 0.500 * asc * 0.75);
437         yp[1] = int(y - 0.500 * asc * 0.75);
438         yp[2] = int(y - asc * 0.75);
439
440         if (bidi_level(pos) % 2 == 0) {
441                 xp[0] = int(p.x);
442                 xp[1] = int(p.x + wid);
443                 xp[2] = int(p.x + wid);
444         } else {
445                 xp[0] = int(p.x + wid);
446                 xp[1] = int(p.x);
447                 xp[2] = int(p.x);
448         }
449
450         p.pain->lines(xp, yp, 3, LColor::eolmarker);
451
452         p.x += wid;
453 }
454
455
456 bool LyXText::drawInset(DrawRowParams & p, pos_type const pos)
457 {
458         Inset * inset = p.row->par()->getInset(pos);
459
460         // FIXME: shouldn't happen
461         if (!inset) {
462                 return true;
463         }
464
465         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
466         // we need this here as the row pointer may be illegal
467         // at a later time (Jug20020502)
468         Row * prev = p.row->previous();
469
470         inset->update(p.bv, font, false);
471         inset->draw(p.bv, font, p.yo + p.row->baseline(), p.x, p.cleared);
472
473         if (!need_break_row && !inset_owner
474             && p.bv->text->status() == CHANGED_IN_DRAW) {
475                 if (prev && prev->par() == p.row->par()) {
476                         breakAgainOneRow(p.bv, prev);
477                         if (prev->next() != p.row) {
478                                 // breakAgainOneRow() has removed p.row
479                                 p.row = 0;  // see what this breaks
480                                 need_break_row = prev;
481                         } else {
482                                 need_break_row = p.row;
483                         }
484                 } else if (!prev) {
485                         need_break_row = firstrow;
486                 } else {
487                         need_break_row = prev->next();
488                 }
489                 setCursor(p.bv, cursor.par(), cursor.pos());
490                 return false;
491         }
492         return true;
493 }
494
495
496 void LyXText::drawForeignMark(DrawRowParams & p, float const orig_x, LyXFont const & orig_font)
497 {
498         if (!lyxrc.mark_foreign_language)
499                 return;
500         if (orig_font.language() == latex_language)
501                 return;
502         if (orig_font.language() == p.bv->buffer()->params.language)
503                 return;
504
505         int const y = p.yo + p.row->baseline() + 1;
506         p.pain->line(int(orig_x), y, int(p.x), y, LColor::language);
507 }
508
509
510 void LyXText::drawHebrewComposeChar(DrawRowParams & p, pos_type & vpos)
511 {
512         pos_type pos = vis2log(vpos);
513
514         string str;
515
516         // first char
517         char c = p.row->par()->getChar(pos);
518         str += c;
519         ++vpos;
520
521         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
522         int const width = font_metrics::width(c, font);
523         int dx = 0;
524
525         for (pos_type i = pos-1; i >= 0; --i) {
526                 c = p.row->par()->getChar(i);
527                 if (!Encodings::IsComposeChar_hebrew(c)) {
528                         if (IsPrintableNonspace(c)) {
529                                 int const width2 =
530                                         singleWidth(p.bv, p.row->par(), i, c);
531                                 // dalet / resh
532                                 dx = (c == 'ø' || c == 'ã')
533                                         ? width2 - width
534                                         : (width2 - width) / 2;
535                         }
536                         break;
537                 }
538         }
539
540         // Draw nikud
541         p.pain->text(int(p.x) + dx, p.yo + p.row->baseline(), str, font);
542 }
543
544
545 void LyXText::drawArabicComposeChar(DrawRowParams & p, pos_type & vpos)
546 {
547         pos_type pos = vis2log(vpos);
548         string str;
549
550         // first char
551         char c = p.row->par()->getChar(pos);
552         c = transformChar(c, p.row->par(), pos);
553         str +=c;
554         ++vpos;
555
556         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
557         int const width = font_metrics::width(c, font);
558         int dx = 0;
559
560         for (pos_type i = pos-1; i >= 0; --i) {
561                 c = p.row->par()->getChar(i);
562                 if (!Encodings::IsComposeChar_arabic(c)) {
563                         if (IsPrintableNonspace(c)) {
564                                 int const width2 =
565                                         singleWidth(p.bv, p.row->par(), i, c);
566                                 dx = (width2 - width) / 2;
567                         }
568                         break;
569                 }
570         }
571         // Draw nikud
572         p.pain->text(int(p.x) + dx, p.yo + p.row->baseline(), str, font);
573 }
574
575
576 void LyXText::drawChars(DrawRowParams & p, pos_type & vpos,
577                         bool hebrew, bool arabic)
578 {
579         pos_type pos = vis2log(vpos);
580         pos_type const last = p.row->lastPrintablePos();
581         LyXFont orig_font(getFont(p.bv->buffer(), p.row->par(), pos));
582
583         // first character
584         string str;
585         str += p.row->par()->getChar(pos);
586         if (arabic) {
587                 unsigned char c = str[0];
588                 str[0] = transformChar(c, p.row->par(), pos);
589         }
590  
591         bool prev_struckout(isDeletedText(p.row->par(), pos));
592         bool prev_newtext(isInsertedText(p.row->par(), pos));
593  
594         ++vpos;
595
596         // collect as much similar chars as we can
597         while (vpos <= last && (pos = vis2log(vpos)) >= 0) {
598                 char c = p.row->par()->getChar(pos);
599
600                 if (!IsPrintableNonspace(c))
601                         break;
602
603                 if (prev_struckout != isDeletedText(p.row->par(), pos))
604                         break;
605  
606                 if (prev_newtext != isInsertedText(p.row->par(), pos))
607                         break;
608  
609                 if (arabic && Encodings::IsComposeChar_arabic(c))
610                         break;
611                 if (hebrew && Encodings::IsComposeChar_hebrew(c))
612                         break;
613
614                 if (orig_font != getFont(p.bv->buffer(), p.row->par(), pos))
615                         break;
616
617                 if (arabic)
618                         c = transformChar(c, p.row->par(), pos);
619                 str += c;
620                 ++vpos;
621         }
622
623         if (prev_struckout) {
624                 orig_font.setColor(LColor::strikeout);
625         } else if (prev_newtext) {
626                 orig_font.setColor(LColor::newtext);
627         }
628
629         // Draw text and set the new x position
630         p.pain->text(int(p.x), p.yo + p.row->baseline(), str, orig_font);
631         p.x += font_metrics::width(str, orig_font);
632 }
633
634
635 bool LyXText::draw(DrawRowParams & p, pos_type & vpos)
636 {
637         pos_type const pos = vis2log(vpos);
638         Paragraph * par = p.row->par();
639
640         LyXFont const & orig_font = getFont(p.bv->buffer(), par, pos);
641
642         float const orig_x = p.x;
643
644         char const c = par->getChar(pos);
645
646         if (IsNewlineChar(c)) {
647                 ++vpos;
648                 drawNewline(p, pos);
649                 return true;
650         } else if (IsInsetChar(c)) {
651                 if (!drawInset(p, pos))
652                         return false;
653                 ++vpos;
654                 drawForeignMark(p, orig_x, orig_font);
655                 return true;
656         }
657
658         // usual characters, no insets
659
660         // special case languages
661         bool const hebrew = (orig_font.language()->lang() == "hebrew");
662         bool const arabic =
663                 orig_font.language()->lang() == "arabic" &&
664                 (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
665                 lyxrc.font_norm_type == LyXRC::ISO_10646_1);
666
667         // draw as many chars as we can
668         if ((!hebrew && !arabic)
669                 || (hebrew && !Encodings::IsComposeChar_hebrew(c))
670                 || (arabic && !Encodings::IsComposeChar_arabic(c))) {
671                 drawChars(p, vpos, hebrew, arabic);
672         } else if (hebrew) {
673                 drawHebrewComposeChar(p, vpos);
674         } else if (arabic) {
675                 drawArabicComposeChar(p, vpos);
676         }
677
678         drawForeignMark(p, orig_x, orig_font);
679
680         return true;
681 }
682
683
684 int LyXText::leftMargin(BufferView * bview, Row const * row) const
685 {
686         Inset * ins;
687         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
688                 (ins=row->par()->getInset(row->pos())) &&
689                 (ins->needFullRow() || ins->display()))
690                 return LEFT_MARGIN;
691
692         LyXTextClass const & tclass =
693                 bview->buffer()->params.getLyXTextClass();
694         LyXLayout_ptr const & layout = row->par()->layout();
695
696         string parindent = layout->parindent;
697
698         int x = LEFT_MARGIN;
699
700         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
701
702         // this is the way, LyX handles the LaTeX-Environments.
703         // I have had this idea very late, so it seems to be a
704         // later added hack and this is true
705         if (!row->par()->getDepth()) {
706                 if (row->par()->layout() == tclass.defaultLayout()) {
707                         // find the previous same level paragraph
708                         if (row->par()->previous()) {
709                                 Paragraph * newpar = row->par()
710                                         ->depthHook(row->par()->getDepth());
711                                 if (newpar &&
712                                     newpar->layout()->nextnoindent)
713                                         parindent.erase();
714                         }
715                 }
716         } else {
717                 // find the next level paragraph
718
719                 Paragraph * newpar = row->par()->outerHook();
720
721                 // make a corresponding row. Needed to call LeftMargin()
722
723                 // check wether it is a sufficent paragraph
724                 if (newpar && newpar->layout()->isEnvironment()) {
725                         Row dummyrow;
726                         dummyrow.par(newpar);
727                         dummyrow.pos(newpar->size());
728                         x = leftMargin(bview, &dummyrow);
729                 } else {
730                         // this is no longer an error, because this function
731                         // is used to clear impossible depths after changing
732                         // a layout. Since there is always a redo,
733                         // LeftMargin() is always called
734                         row->par()->params().depth(0);
735                 }
736
737                 if (newpar && row->par()->layout() == tclass.defaultLayout()) {
738                         if (newpar->params().noindent())
739                                 parindent.erase();
740                         else {
741                                 parindent = newpar->layout()->parindent;
742                         }
743
744                 }
745         }
746
747         LyXFont const labelfont = getLabelFont(bview->buffer(), row->par());
748         switch (layout->margintype) {
749         case MARGIN_DYNAMIC:
750                 if (!layout->leftmargin.empty()) {
751                         x += font_metrics::signedWidth(layout->leftmargin,
752                                                   tclass.defaultfont());
753                 }
754                 if (!row->par()->getLabelstring().empty()) {
755                         x += font_metrics::signedWidth(layout->labelindent,
756                                                   labelfont);
757                         x += font_metrics::width(row->par()->getLabelstring(),
758                                             labelfont);
759                         x += font_metrics::width(layout->labelsep, labelfont);
760                 }
761                 break;
762         case MARGIN_MANUAL:
763                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
764                 if (row->pos() >= row->par()->beginningOfMainBody()) {
765                         if (!row->par()->getLabelWidthString().empty()) {
766                                 x += font_metrics::width(row->par()->getLabelWidthString(),
767                                                labelfont);
768                                 x += font_metrics::width(layout->labelsep, labelfont);
769                         }
770                 }
771                 break;
772         case MARGIN_STATIC:
773                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
774                         / (row->par()->getDepth() + 4);
775                 break;
776         case MARGIN_FIRST_DYNAMIC:
777                 if (layout->labeltype == LABEL_MANUAL) {
778                         if (row->pos() >= row->par()->beginningOfMainBody()) {
779                                 x += font_metrics::signedWidth(layout->leftmargin,
780                                                           labelfont);
781                         } else {
782                                 x += font_metrics::signedWidth(layout->labelindent,
783                                                           labelfont);
784                         }
785                 } else if (row->pos()
786                            // Special case to fix problems with
787                            // theorems (JMarc)
788                            || (layout->labeltype == LABEL_STATIC
789                                && layout->latextype == LATEX_ENVIRONMENT
790                                && ! row->par()->isFirstInSequence())) {
791                         x += font_metrics::signedWidth(layout->leftmargin,
792                                                   labelfont);
793                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
794                            && layout->labeltype != LABEL_BIBLIO
795                            && layout->labeltype !=
796                            LABEL_CENTERED_TOP_ENVIRONMENT) {
797                         x += font_metrics::signedWidth(layout->labelindent,
798                                                   labelfont);
799                         x += font_metrics::width(layout->labelsep, labelfont);
800                         x += font_metrics::width(row->par()->getLabelstring(),
801                                             labelfont);
802                 }
803                 break;
804
805         case MARGIN_RIGHT_ADDRESS_BOX:
806         {
807                 // ok, a terrible hack. The left margin depends on the widest
808                 // row in this paragraph. Do not care about footnotes, they
809                 // are *NOT* allowed in the LaTeX realisation of this layout.
810
811                 // find the first row of this paragraph
812                 Row const * tmprow = row;
813                 while (tmprow->previous()
814                        && tmprow->previous()->par() == row->par())
815                         tmprow = tmprow->previous();
816
817                 int minfill = tmprow->fill();
818                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
819                         tmprow = tmprow->next();
820                         if (tmprow->fill() < minfill)
821                                 minfill = tmprow->fill();
822                 }
823
824                 x += font_metrics::signedWidth(layout->leftmargin,
825                         tclass.defaultfont());
826                 x += minfill;
827         }
828         break;
829         }
830
831         if ((workWidth(bview) > 0) &&
832                 !row->par()->params().leftIndent().zero())
833         {
834                 LyXLength const len = row->par()->params().leftIndent();
835                 int const tw = inset_owner ?
836                         inset_owner->latexTextWidth(bview) : workWidth(bview);
837                 x += len.inPixels(tw);
838         }
839
840         LyXAlignment align; // wrong type
841
842         if (row->par()->params().align() == LYX_ALIGN_LAYOUT)
843                 align = layout->align;
844         else
845                 align = row->par()->params().align();
846
847         // set the correct parindent
848         if (row->pos() == 0) {
849                 if ((layout->labeltype == LABEL_NO_LABEL
850                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
851                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
852                      || (layout->labeltype == LABEL_STATIC
853                          && layout->latextype == LATEX_ENVIRONMENT
854                          && ! row->par()->isFirstInSequence()))
855                     && align == LYX_ALIGN_BLOCK
856                     && !row->par()->params().noindent()
857                         // in tabulars and ert paragraphs are never indented!
858                         && (!row->par()->inInset() || !row->par()->inInset()->owner() ||
859                                 (row->par()->inInset()->owner()->lyxCode() != Inset::TABULAR_CODE &&
860                                  row->par()->inInset()->owner()->lyxCode() != Inset::ERT_CODE))
861                     && (row->par()->layout() != tclass.defaultLayout() ||
862                         bview->buffer()->params.paragraph_separation ==
863                         BufferParams::PARSEP_INDENT)) {
864                         x += font_metrics::signedWidth(parindent,
865                                                   tclass.defaultfont());
866                 } else if (layout->labeltype == LABEL_BIBLIO) {
867                         // ale970405 Right width for bibitems
868                         x += bibitemMaxWidth(bview, tclass.defaultfont());
869                 }
870         }
871
872         return x;
873 }
874
875
876 int LyXText::rightMargin(Buffer const * buf, Row const * row) const
877 {
878         Inset * ins;
879         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
880                 (ins=row->par()->getInset(row->pos())) &&
881                 (ins->needFullRow() || ins->display()))
882                 return PAPER_MARGIN;
883
884         LyXTextClass const & tclass = buf->params.getLyXTextClass();
885         LyXLayout_ptr const & layout = row->par()->layout();
886
887         int x = PAPER_MARGIN
888                 + font_metrics::signedWidth(tclass.rightmargin(),
889                                        tclass.defaultfont());
890
891         // this is the way, LyX handles the LaTeX-Environments.
892         // I have had this idea very late, so it seems to be a
893         // later added hack and this is true
894         if (row->par()->getDepth()) {
895                 // find the next level paragraph
896
897                 Paragraph * newpar = row->par();
898
899                 do {
900                         newpar = newpar->previous();
901                 } while (newpar
902                          && newpar->getDepth() >= row->par()->getDepth());
903
904                 // make a corresponding row. Needed to call LeftMargin()
905
906                 // check wether it is a sufficent paragraph
907                 if (newpar && newpar->layout()->isEnvironment()) {
908                         Row dummyrow;
909                         dummyrow.par(newpar);
910                         dummyrow.pos(0);
911                         x = rightMargin(buf, &dummyrow);
912                 } else {
913                         // this is no longer an error, because this function
914                         // is used to clear impossible depths after changing
915                         // a layout. Since there is always a redo,
916                         // LeftMargin() is always called
917                         row->par()->params().depth(0);
918                 }
919         }
920
921         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
922         x += font_metrics::signedWidth(layout->rightmargin,
923                                        tclass.defaultfont())
924                 * 4 / (row->par()->getDepth() + 4);
925         return x;
926 }
927
928
929 int LyXText::labelEnd(BufferView * bview, Row const * row) const
930 {
931         if (row->par()->layout()->margintype == MARGIN_MANUAL) {
932                 Row tmprow;
933                 tmprow = *row;
934                 tmprow.pos(row->par()->size());
935                 // just the beginning of the main body
936                 return leftMargin(bview, &tmprow);
937         } else {
938                 // LabelEnd is only needed,
939                 // if the layout fills a flushleft label.
940                 return 0;
941         }
942 }
943
944
945 // get the next breakpoint in a given paragraph
946 pos_type
947 LyXText::nextBreakPoint(BufferView * bview, Row const * row, int width) const
948 {
949         Paragraph * par = row->par();
950
951         if (width < 0)
952                 return par->size();
953
954         pos_type const pos = row->pos();
955
956         // position of the last possible breakpoint
957         // -1 isn't a suitable value, but a flag
958         pos_type last_separator = -1;
959         width -= rightMargin(bview->buffer(), row);
960
961         pos_type const main_body = par->beginningOfMainBody();
962         LyXLayout_ptr const & layout = par->layout();
963
964         pos_type i = pos;
965
966         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
967                 // special code for right address boxes, only newlines count
968                 while (i < par->size()) {
969                         if (par->isNewline(i)) {
970                                 last_separator = i;
971                                 i = par->size() - 1; // this means break
972                                 //x = width;
973                         } else if (par->isInset(i) && par->getInset(i)
974                                 && par->getInset(i)->display()) {
975                                 par->getInset(i)->display(false);
976                         }
977                         ++i;
978                 }
979         } else {
980                 // Last position is an invariant
981                 pos_type const last = par->size();
982                 // this is the usual handling
983                 int x = leftMargin(bview, row);
984                 bool doitonetime = true;
985                 while (doitonetime || ((x < width) && (i < last))) {
986                         doitonetime = false;
987                         char const c = par->getChar(i);
988                         Inset * in = 0;
989                         if (c == Paragraph::META_INSET)
990                                 in = par->getInset(i);
991                         if (IsNewlineChar(c)) {
992                                 last_separator = i;
993                                 x = width; // this means break
994                         } else if (in && !in->isChar()) {
995                                 // check wether a Display() inset is
996                                 // valid here. if not, change it to
997                                 // non-display
998                                 if (in->display() &&
999                                     (layout->isCommand() ||
1000                                      (layout->labeltype == LABEL_MANUAL
1001                                       && i < par->beginningOfMainBody())))
1002                                 {
1003                                         // display istn't allowd
1004                                         in->display(false);
1005                                         x += singleWidth(bview, par, i, c);
1006                                 } else if (in->display() || in->needFullRow()) {
1007                                         // So break the line here
1008                                         if (i == pos) {
1009                                                 if (pos < last-1) {
1010                                                         last_separator = i;
1011                                                         if (par->isLineSeparator(i+1))
1012                                                                 ++last_separator;
1013                                                 } else
1014                                                         last_separator = last; // to avoid extra rows
1015                                         } else
1016                                                 last_separator = i - 1;
1017                                         x = width;  // this means break
1018                                 } else {
1019                                         x += singleWidth(bview, par, i, c);
1020                                         // we have to check this separately as we could have a
1021                                         // lineseparator and then the algorithm below would prefer
1022                                         // that which IS wrong! We should always break on an inset
1023                                         // if it's too long and not on the last separator.
1024                                         // Maybe the only exeption is insets used as chars but
1025                                         // then we would have to have a special function inside
1026                                         // the inset to tell us this. Till then we leave it as
1027                                         // it is now. (Jug 20020106)
1028                                         if (pos < i && x >= width && last_separator >= 0)
1029                                                 last_separator = i - 1;
1030                                 }
1031                         } else  {
1032                                 if (par->isLineSeparator(i))
1033                                         last_separator = i;
1034                                 x += singleWidth(bview, par, i, c);
1035                         }
1036                         ++i;
1037                         if (i == main_body) {
1038                                 x += font_metrics::width(layout->labelsep,
1039                                                     getLabelFont(bview->buffer(), par));
1040                                 if (par->isLineSeparator(i - 1))
1041                                         x-= singleWidth(bview, par, i - 1);
1042                                 int left_margin = labelEnd(bview, row);
1043                                 if (x < left_margin)
1044                                         x = left_margin;
1045                         }
1046                 }
1047                 if ((pos+1 < i) && (last_separator < 0) && (x >= width))
1048                         last_separator = i - 2;
1049                 else if ((pos < i) && (last_separator < 0) && (x >= width))
1050                         last_separator = i - 1;
1051                 // end of paragraph is always a suitable separator
1052                 else if (i == last && x < width)
1053                         last_separator = i;
1054         }
1055
1056         // well, if last_separator is still 0, the line isn't breakable.
1057         // don't care and cut simply at the end
1058         if (last_separator < 0) {
1059                 last_separator = i;
1060         }
1061
1062         // manual labels cannot be broken in LaTeX, do not care
1063         if (main_body && last_separator < main_body)
1064                 last_separator = main_body - 1;
1065
1066         return last_separator;
1067 }
1068
1069
1070 // returns the minimum space a row needs on the screen in pixel
1071 int LyXText::fill(BufferView * bview, Row * row, int paper_width) const
1072 {
1073         if (paper_width < 0)
1074                 return 0;
1075
1076         int w;
1077         // get the pure distance
1078         pos_type const last = row->lastPrintablePos();
1079
1080         // special handling of the right address boxes
1081         if (row->par()->layout()->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1082                 int const tmpfill = row->fill();
1083                 row->fill(0); // the minfill in MarginLeft()
1084                 w = leftMargin(bview, row);
1085                 row->fill(tmpfill);
1086         } else
1087                 w = leftMargin(bview, row);
1088
1089         LyXLayout_ptr const & layout = row->par()->layout();
1090
1091         pos_type const main_body = row->par()->beginningOfMainBody();
1092         pos_type i = row->pos();
1093
1094         while (i <= last) {
1095                 if (main_body > 0 && i == main_body) {
1096                         w += font_metrics::width(layout->labelsep, getLabelFont(bview->buffer(), row->par()));
1097                         if (row->par()->isLineSeparator(i - 1))
1098                                 w -= singleWidth(bview, row->par(), i - 1);
1099                         int left_margin = labelEnd(bview, row);
1100                         if (w < left_margin)
1101                                 w = left_margin;
1102                 }
1103                 w += singleWidth(bview, row->par(), i);
1104                 ++i;
1105         }
1106         if (main_body > 0 && main_body > last) {
1107                 w += font_metrics::width(layout->labelsep, getLabelFont(bview->buffer(), row->par()));
1108                 if (last >= 0 && row->par()->isLineSeparator(last))
1109                         w -= singleWidth(bview, row->par(), last);
1110                 int const left_margin = labelEnd(bview, row);
1111                 if (w < left_margin)
1112                         w = left_margin;
1113         }
1114
1115         int const fill = paper_width - w - rightMargin(bview->buffer(), row);
1116         return fill;
1117 }
1118
1119
1120 // returns the minimum space a manual label needs on the screen in pixel
1121 int LyXText::labelFill(BufferView * bview, Row const * row) const
1122 {
1123         pos_type last = row->par()->beginningOfMainBody() - 1;
1124         // -1 because a label ends either with a space that is in the label,
1125         // or with the beginning of a footnote that is outside the label.
1126
1127         // I don't understand this code in depth, but sometimes "last" is
1128         // less than 0 and this causes a crash. This fix seems to work
1129         // correctly, but I bet the real error is elsewhere.  The bug is
1130         // triggered when you have an open footnote in a paragraph
1131         // environment with a manual label. (Asger)
1132         if (last < 0) last = 0;
1133
1134         // a separator at this end does not count
1135         if (row->par()->isLineSeparator(last))
1136                 --last;
1137
1138         int w = 0;
1139         pos_type i = row->pos();
1140         while (i <= last) {
1141                 w += singleWidth(bview, row->par(), i);
1142                 ++i;
1143         }
1144
1145         int fill = 0;
1146         if (!row->par()->params().labelWidthString().empty()) {
1147                 fill = max(font_metrics::width(row->par()->params().labelWidthString(),
1148                                           getLabelFont(bview->buffer(), row->par())) - w,
1149                            0);
1150         }
1151
1152         return fill;
1153 }
1154
1155
1156 LColor::color LyXText::backgroundColor()
1157 {
1158         if (inset_owner)
1159                 return inset_owner->backgroundColor();
1160         else
1161                 return LColor::background;
1162 }
1163
1164 void LyXText::setHeightOfRow(BufferView * bview, Row * row) const
1165 {
1166         // get the maximum ascent and the maximum descent
1167         int asc = 0;
1168         int desc = 0;
1169         float layoutasc = 0;
1170         float layoutdesc = 0;
1171         float tmptop = 0;
1172         LyXFont tmpfont;
1173         Inset * tmpinset = 0;
1174
1175         // ok , let us initialize the maxasc and maxdesc value.
1176         // This depends in LaTeX of the font of the last character
1177         // in the paragraph. The hack below is necessary because
1178         // of the possibility of open footnotes
1179
1180         // Correction: only the fontsize count. The other properties
1181         //  are taken from the layoutfont. Nicer on the screen :)
1182         Paragraph * par = row->par();
1183         Paragraph * firstpar = row->par();
1184
1185         LyXLayout_ptr const & layout = firstpar->layout();
1186
1187         // as max get the first character of this row then it can increase but not
1188         // decrease the height. Just some point to start with so we don't have to
1189         // do the assignment below too often.
1190         LyXFont font = getFont(bview->buffer(), par, row->pos());
1191         LyXFont::FONT_SIZE const tmpsize = font.size();
1192         font = getLayoutFont(bview->buffer(), par);
1193         LyXFont::FONT_SIZE const size = font.size();
1194         font.setSize(tmpsize);
1195
1196         LyXFont labelfont = getLabelFont(bview->buffer(), par);
1197
1198         float spacing_val = 1.0;
1199         if (!row->par()->params().spacing().isDefault()) {
1200                 spacing_val = row->par()->params().spacing().getValue();
1201         } else {
1202                 spacing_val = bview->buffer()->params.spacing.getValue();
1203         }
1204         //lyxerr << "spacing_val = " << spacing_val << endl;
1205
1206         int maxasc = int(font_metrics::maxAscent(font) *
1207                          layout->spacing.getValue() *
1208                          spacing_val);
1209         int maxdesc = int(font_metrics::maxDescent(font) *
1210                           layout->spacing.getValue() *
1211                           spacing_val);
1212
1213         pos_type const pos_end = row->lastPos();
1214         int labeladdon = 0;
1215         int maxwidth = 0;
1216
1217         // Check if any insets are larger
1218         for (pos_type pos = row->pos(); pos <= pos_end; ++pos) {
1219                 if (row->par()->isInset(pos)) {
1220                         tmpfont = getFont(bview->buffer(), row->par(), pos);
1221                         tmpinset = row->par()->getInset(pos);
1222                         if (tmpinset) {
1223 #if 1 // this is needed for deep update on initialitation
1224                                 tmpinset->update(bview, tmpfont);
1225 #endif
1226                                 asc = tmpinset->ascent(bview, tmpfont);
1227                                 desc = tmpinset->descent(bview, tmpfont);
1228                                 maxwidth += tmpinset->width(bview, tmpfont);
1229                                 maxasc = max(maxasc, asc);
1230                                 maxdesc = max(maxdesc, desc);
1231                         }
1232                 } else {
1233                         maxwidth += singleWidth(bview, row->par(), pos);
1234                 }
1235         }
1236
1237         // Check if any custom fonts are larger (Asger)
1238         // This is not completely correct, but we can live with the small,
1239         // cosmetic error for now.
1240         LyXFont::FONT_SIZE maxsize =
1241                 row->par()->highestFontInRange(row->pos(), pos_end, size);
1242         if (maxsize > font.size()) {
1243                 font.setSize(maxsize);
1244
1245                 asc = font_metrics::maxAscent(font);
1246                 desc = font_metrics::maxDescent(font);
1247                 if (asc > maxasc)
1248                         maxasc = asc;
1249                 if (desc > maxdesc)
1250                         maxdesc = desc;
1251         }
1252
1253         // This is nicer with box insets:
1254         ++maxasc;
1255         ++maxdesc;
1256
1257         row->ascent_of_text(maxasc);
1258
1259         // is it a top line?
1260         if (!row->pos() && (row->par() == firstpar)) {
1261
1262                 // some parksips VERY EASY IMPLEMENTATION
1263                 if (bview->buffer()->params.paragraph_separation ==
1264                         BufferParams::PARSEP_SKIP)
1265                 {
1266                         if (layout->isParagraph()
1267                                 && firstpar->getDepth() == 0
1268                                 && firstpar->previous())
1269                         {
1270                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1271                         } else if (firstpar->previous() &&
1272                                    firstpar->previous()->layout()->isParagraph() &&
1273                                    firstpar->previous()->getDepth() == 0)
1274                         {
1275                                 // is it right to use defskip here too? (AS)
1276                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1277                         }
1278                 }
1279
1280                 // the top margin
1281                 if (!row->par()->previous() && isTopLevel())
1282                         maxasc += PAPER_MARGIN;
1283
1284                 // add the vertical spaces, that the user added
1285                 maxasc += getLengthMarkerHeight(bview, firstpar->params().spaceTop());
1286
1287                 // do not forget the DTP-lines!
1288                 // there height depends on the font of the nearest character
1289                 if (firstpar->params().lineTop())
1290
1291                         maxasc += 2 * font_metrics::ascent('x', getFont(bview->buffer(),
1292                                         firstpar, 0));
1293                 // and now the pagebreaks
1294                 if (firstpar->params().pagebreakTop())
1295                         maxasc += 3 * defaultRowHeight();
1296
1297                 // This is special code for the chapter, since the label of this
1298                 // layout is printed in an extra row
1299                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1300                         && bview->buffer()->params.secnumdepth >= 0)
1301                 {
1302                         float spacing_val = 1.0;
1303                         if (!row->par()->params().spacing().isDefault()) {
1304                                 spacing_val = row->par()->params().spacing().getValue();
1305                         } else {
1306                                 spacing_val = bview->buffer()->params.spacing.getValue();
1307                         }
1308
1309                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1310                                          layout->spacing.getValue() *
1311                                          spacing_val)
1312                                 + int(font_metrics::maxAscent(labelfont) *
1313                                       layout->spacing.getValue() *
1314                                       spacing_val);
1315                 }
1316
1317                 // special code for the top label
1318                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1319                      || layout->labeltype == LABEL_BIBLIO
1320                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1321                     && row->par()->isFirstInSequence()
1322                     && !row->par()->getLabelstring().empty())
1323                 {
1324                         float spacing_val = 1.0;
1325                         if (!row->par()->params().spacing().isDefault()) {
1326                                 spacing_val = row->par()->params().spacing().getValue();
1327                         } else {
1328                                 spacing_val = bview->buffer()->params.spacing.getValue();
1329                         }
1330
1331                         labeladdon = int(
1332                                 (font_metrics::maxAscent(labelfont) *
1333                                  layout->spacing.getValue() *
1334                                  spacing_val)
1335                                 +(font_metrics::maxDescent(labelfont) *
1336                                   layout->spacing.getValue() *
1337                                   spacing_val)
1338                                 + layout->topsep * defaultRowHeight()
1339                                 + layout->labelbottomsep * defaultRowHeight());
1340                 }
1341
1342                 // and now the layout spaces, for example before and after a section,
1343                 // or between the items of a itemize or enumerate environment
1344
1345                 if (!firstpar->params().pagebreakTop()) {
1346                         Paragraph * prev = row->par()->previous();
1347                         if (prev)
1348                                 prev = row->par()->depthHook(row->par()->getDepth());
1349                         if (prev && prev->layout() == firstpar->layout() &&
1350                                 prev->getDepth() == firstpar->getDepth() &&
1351                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1352                         {
1353                                 layoutasc = (layout->itemsep * defaultRowHeight());
1354                         } else if (row->previous()) {
1355                                 tmptop = layout->topsep;
1356
1357                                 if (row->previous()->par()->getDepth() >= row->par()->getDepth())
1358                                         tmptop -= row->previous()->par()->layout()->bottomsep;
1359
1360                                 if (tmptop > 0)
1361                                         layoutasc = (tmptop * defaultRowHeight());
1362                         } else if (row->par()->params().lineTop()) {
1363                                 tmptop = layout->topsep;
1364
1365                                 if (tmptop > 0)
1366                                         layoutasc = (tmptop * defaultRowHeight());
1367                         }
1368
1369                         prev = row->par()->outerHook();
1370                         if (prev)  {
1371                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1372                         } else {
1373                                 if (firstpar->previous() &&
1374                                         firstpar->previous()->getDepth() == 0 &&
1375                                         firstpar->previous()->layout() !=
1376                                         firstpar->layout())
1377                                 {
1378                                         // avoid parsep
1379                                 } else if (firstpar->previous()) {
1380                                         maxasc += int(layout->parsep * defaultRowHeight());
1381                                 }
1382                         }
1383                 }
1384         }
1385
1386         // is it a bottom line?
1387         if (row->par() == par
1388                 && (!row->next() || row->next()->par() != row->par()))
1389         {
1390                 // the bottom margin
1391                 if (!par->next() && isTopLevel())
1392                         maxdesc += PAPER_MARGIN;
1393
1394                 // add the vertical spaces, that the user added
1395                 maxdesc += getLengthMarkerHeight(bview, firstpar->params().spaceBottom());
1396
1397                 // do not forget the DTP-lines!
1398                 // there height depends on the font of the nearest character
1399                 if (firstpar->params().lineBottom())
1400                         maxdesc += 2 * font_metrics::ascent('x',
1401                                                        getFont(bview->buffer(),
1402                                                                par,
1403                                                                max(pos_type(0), par->size() - 1)));
1404
1405                 // and now the pagebreaks
1406                 if (firstpar->params().pagebreakBottom())
1407                         maxdesc += 3 * defaultRowHeight();
1408
1409                 // and now the layout spaces, for example before and after
1410                 // a section, or between the items of a itemize or enumerate
1411                 // environment
1412                 if (!firstpar->params().pagebreakBottom()
1413                     && row->par()->next()) {
1414                         Paragraph * nextpar = row->par()->next();
1415                         Paragraph * comparepar = row->par();
1416                         float usual = 0;
1417                         float unusual = 0;
1418
1419                         if (comparepar->getDepth() > nextpar->getDepth()) {
1420                                 usual = (comparepar->layout()->bottomsep * defaultRowHeight());
1421                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1422                                 if (comparepar->layout()!= nextpar->layout()
1423                                         || nextpar->getLabelWidthString() !=
1424                                         comparepar->getLabelWidthString())
1425                                 {
1426                                         unusual = (comparepar->layout()->bottomsep * defaultRowHeight());
1427                                 }
1428                                 if (unusual > usual)
1429                                         layoutdesc = unusual;
1430                                 else
1431                                         layoutdesc = usual;
1432                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1433
1434                                 if (comparepar->layout() != nextpar->layout()
1435                                         || nextpar->getLabelWidthString() !=
1436                                         comparepar->getLabelWidthString())
1437                                         layoutdesc = int(comparepar->layout()->bottomsep * defaultRowHeight());
1438                         }
1439                 }
1440         }
1441
1442         // incalculate the layout spaces
1443         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1444         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1445
1446         // calculate the new height of the text
1447         height -= row->height();
1448
1449         row->height(maxasc + maxdesc + labeladdon);
1450         row->baseline(maxasc + labeladdon);
1451
1452         height += row->height();
1453  
1454         row->top_of_text(row->baseline() - font_metrics::maxAscent(font));
1455
1456         float x = 0;
1457         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1458                 float dummy;
1459                 // this IS needed
1460                 row->width(maxwidth);
1461                 prepareToPrint(bview, row, x, dummy, dummy, dummy, false);
1462         }
1463         row->width(int(maxwidth + x));
1464         if (inset_owner) {
1465                 Row * r = firstrow;
1466                 width = max(0,workWidth(bview));
1467                 while (r) {
1468                         if (r->width() > width)
1469                                 width = r->width();
1470                         r = r->next();
1471                 }
1472         }
1473 }
1474
1475
1476 // Appends the implicit specified paragraph behind the specified row,
1477 // start at the implicit given position
1478 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1479 {
1480         bool not_ready = true;
1481
1482         // The last character position of a paragraph is an invariant so we can
1483         // safely get it here. (Asger)
1484         pos_type const lastposition = row->par()->size();
1485         do {
1486                 // Get the next breakpoint
1487                 pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1488
1489                 Row * tmprow = row;
1490
1491                 // Insert the new row
1492                 if (z < lastposition) {
1493                         ++z;
1494                         insertRow(row, row->par(), z);
1495                         row = row->next();
1496
1497                         row->height(0);
1498                 } else
1499                         not_ready = false;
1500
1501                 // Set the dimensions of the row
1502                 // fixed fill setting now by calling inset->update() in
1503                 // SingleWidth when needed!
1504                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1505                 setHeightOfRow(bview, tmprow);
1506
1507         } while (not_ready);
1508 }
1509
1510
1511 void LyXText::breakAgain(BufferView * bview, Row * row) const
1512 {
1513         bool not_ready = true;
1514
1515         do  {
1516                 // get the next breakpoint
1517                 pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1518                 Row * tmprow = row;
1519
1520                 if (z < row->par()->size()) {
1521                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1522                                 // insert a new row
1523                                 ++z;
1524                                 insertRow(row, row->par(), z);
1525                                 row = row->next();
1526                                 row->height(0);
1527                         } else  {
1528                                 row = row->next();
1529                                 ++z;
1530                                 if (row->pos() == z)
1531                                         not_ready = false;     // the rest will not change
1532                                 else {
1533                                         row->pos(z);
1534                                 }
1535                         }
1536                 } else {
1537                         // if there are some rows too much, delete them
1538                         // only if you broke the whole paragraph!
1539                         Row * tmprow2 = row;
1540                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1541                                 tmprow2 = tmprow2->next();
1542                         }
1543                         while (tmprow2 != row) {
1544                                 tmprow2 = tmprow2->previous();
1545                                 removeRow(tmprow2->next());
1546                         }
1547                         not_ready = false;
1548                 }
1549
1550                 // set the dimensions of the row
1551                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1552                 setHeightOfRow(bview, tmprow);
1553         } while (not_ready);
1554 }
1555
1556
1557 // this is just a little changed version of break again
1558 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1559 {
1560         // get the next breakpoint
1561         pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1562         Row * tmprow = row;
1563
1564         if (z < row->par()->size()) {
1565                 if (!row->next()
1566                     || (row->next() && row->next()->par() != row->par())) {
1567                         // insert a new row
1568                         ++z;
1569                         insertRow(row, row->par(), z);
1570                         row = row->next();
1571                         row->height(0);
1572                 } else  {
1573                         row = row->next();
1574                         ++z;
1575                         if (row->pos() != z)
1576                                 row->pos(z);
1577                 }
1578         } else {
1579                 // if there are some rows too much, delete them
1580                 // only if you broke the whole paragraph!
1581                 Row * tmprow2 = row;
1582                 while (tmprow2->next()
1583                        && tmprow2->next()->par() == row->par()) {
1584                         tmprow2 = tmprow2->next();
1585                 }
1586                 while (tmprow2 != row) {
1587                         tmprow2 = tmprow2->previous();
1588                         removeRow(tmprow2->next());
1589                 }
1590         }
1591
1592         // set the dimensions of the row
1593         tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1594         setHeightOfRow(bview, tmprow);
1595 }
1596
1597
1598 void LyXText::breakParagraph(BufferView * bview, char keep_layout)
1599 {
1600         // allow only if at start or end, or all previous is new text
1601         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1602                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1603                 return;
1604
1605         LyXTextClass const & tclass =
1606                 bview->buffer()->params.getLyXTextClass();
1607         LyXLayout_ptr const & layout = cursor.par()->layout();
1608
1609         // this is only allowed, if the current paragraph is not empty or caption
1610         // and if it has not the keepempty flag aktive
1611         if (cursor.par()->empty()
1612            && layout->labeltype != LABEL_SENSITIVE
1613            && !layout->keepempty)
1614                 return;
1615
1616         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1617
1618         // Always break behind a space
1619         //
1620         // It is better to erase the space (Dekel)
1621         if (cursor.pos() < cursor.par()->size()
1622              && cursor.par()->isLineSeparator(cursor.pos()))
1623            cursor.par()->erase(cursor.pos());
1624         // cursor.pos(cursor.pos() + 1);
1625
1626         // break the paragraph
1627         if (keep_layout)
1628                 keep_layout = 2;
1629         else
1630                 keep_layout = layout->isEnvironment();
1631
1632         // we need to set this before we insert the paragraph. IMO the
1633         // breakParagraph call should return a bool if it inserts the
1634         // paragraph before or behind and we should react on that one
1635         // but we can fix this in 1.3.0 (Jug 20020509)
1636         bool const isempty = (layout->keepempty && cursor.par()->empty());
1637         ::breakParagraph(bview->buffer()->params, cursor.par(), cursor.pos(),
1638                        keep_layout);
1639
1640         // well this is the caption hack since one caption is really enough
1641         if (layout->labeltype == LABEL_SENSITIVE) {
1642                 if (!cursor.pos())
1643                         // set to standard-layout
1644                         cursor.par()->applyLayout(tclass.defaultLayout());
1645                 else
1646                         // set to standard-layout
1647                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1648         }
1649
1650         // if the cursor is at the beginning of a row without prior newline,
1651         // move one row up!
1652         // This touches only the screen-update. Otherwise we would may have
1653         // an empty row on the screen
1654         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1655                          && cursor.row()->pos() == cursor.pos())
1656         {
1657                 cursorLeft(bview);
1658         }
1659
1660         status(bview, LyXText::NEED_MORE_REFRESH);
1661         refresh_row = cursor.row();
1662         refresh_y = cursor.y() - cursor.row()->baseline();
1663
1664         // Do not forget the special right address boxes
1665         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1666                 while (refresh_row->previous() &&
1667                        refresh_row->previous()->par() == refresh_row->par())
1668                 {
1669                         refresh_row = refresh_row->previous();
1670                         refresh_y -= refresh_row->height();
1671                 }
1672         }
1673         removeParagraph(cursor.row());
1674
1675         // set the dimensions of the cursor row
1676         cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1677
1678         setHeightOfRow(bview, cursor.row());
1679
1680         while (!cursor.par()->next()->empty()
1681           && cursor.par()->next()->isNewline(0))
1682            cursor.par()->next()->erase(0);
1683
1684         insertParagraph(bview, cursor.par()->next(), cursor.row());
1685
1686         updateCounters(bview);
1687
1688         // This check is necessary. Otherwise the new empty paragraph will
1689         // be deleted automatically. And it is more friendly for the user!
1690         if (cursor.pos() || isempty)
1691                 setCursor(bview, cursor.par()->next(), 0);
1692         else
1693                 setCursor(bview, cursor.par(), 0);
1694
1695         if (cursor.row()->next())
1696                 breakAgain(bview, cursor.row()->next());
1697
1698         need_break_row = 0;
1699 }
1700
1701
1702 // Just a macro to make some thing easier.
1703 void LyXText::redoParagraph(BufferView * bview) const
1704 {
1705         clearSelection();
1706         redoParagraphs(bview, cursor, cursor.par()->next());
1707         setCursorIntern(bview, cursor.par(), cursor.pos());
1708 }
1709
1710
1711 // insert a character, moves all the following breaks in the
1712 // same Paragraph one to the right and make a rebreak
1713 void LyXText::insertChar(BufferView * bview, char c)
1714 {
1715         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1716
1717         // When the free-spacing option is set for the current layout,
1718         // disable the double-space checking
1719
1720         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1721                 cursor.row()->par()->isFreeSpacing();
1722
1723         if (lyxrc.auto_number) {
1724                 static string const number_operators = "+-/*";
1725                 static string const number_unary_operators = "+-";
1726                 static string const number_seperators = ".,:";
1727
1728                 if (current_font.number() == LyXFont::ON) {
1729                         if (!IsDigit(c) && !contains(number_operators, c) &&
1730                             !(contains(number_seperators, c) &&
1731                               cursor.pos() >= 1 &&
1732                               cursor.pos() < cursor.par()->size() &&
1733                               getFont(bview->buffer(),
1734                                       cursor.par(),
1735                                       cursor.pos()).number() == LyXFont::ON &&
1736                               getFont(bview->buffer(),
1737                                       cursor.par(),
1738                                       cursor.pos() - 1).number() == LyXFont::ON)
1739                            )
1740                                 number(bview); // Set current_font.number to OFF
1741                 } else if (IsDigit(c) &&
1742                            real_current_font.isVisibleRightToLeft()) {
1743                         number(bview); // Set current_font.number to ON
1744
1745                         if (cursor.pos() > 0) {
1746                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1747                                 if (contains(number_unary_operators, c) &&
1748                                     (cursor.pos() == 1 ||
1749                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1750                                      cursor.par()->isNewline(cursor.pos() - 2))
1751                                   ) {
1752                                         setCharFont(bview->buffer(),
1753                                                     cursor.par(),
1754                                                     cursor.pos() - 1,
1755                                                     current_font);
1756                                 } else if (contains(number_seperators, c) &&
1757                                            cursor.pos() >= 2 &&
1758                                            getFont(bview->buffer(),
1759                                                    cursor.par(),
1760                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1761                                         setCharFont(bview->buffer(),
1762                                                     cursor.par(),
1763                                                     cursor.pos() - 1,
1764                                                     current_font);
1765                                 }
1766                         }
1767                 }
1768         }
1769
1770
1771         // First check, if there will be two blanks together or a blank at
1772         // the beginning of a paragraph.
1773         // I decided to handle blanks like normal characters, the main
1774         // difference are the special checks when calculating the row.fill
1775         // (blank does not count at the end of a row) and the check here
1776
1777         // The bug is triggered when we type in a description environment:
1778         // The current_font is not changed when we go from label to main text
1779         // and it should (along with realtmpfont) when we type the space.
1780         // CHECK There is a bug here! (Asger)
1781
1782         LyXFont realtmpfont = real_current_font;
1783         LyXFont rawtmpfont = current_font;
1784         // store the current font.  This is because of the use of cursor
1785         // movements. The moving cursor would refresh the current font
1786
1787         // Get the font that is used to calculate the baselineskip
1788         pos_type const lastpos = cursor.par()->size();
1789         LyXFont rawparfont =
1790                 cursor.par()->getFontSettings(bview->buffer()->params,
1791                                               lastpos - 1);
1792
1793         bool jumped_over_space = false;
1794
1795         if (!freeSpacing && IsLineSeparatorChar(c)) {
1796                 if ((cursor.pos() > 0
1797                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1798                     || (cursor.pos() > 0
1799                         && cursor.par()->isNewline(cursor.pos() - 1))
1800                     || (cursor.pos() == 0)) {
1801                         static bool sent_space_message = false;
1802                         if (!sent_space_message) {
1803                                 if (cursor.pos() == 0)
1804                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1805                                 else
1806                                         bview->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1807                                 sent_space_message = true;
1808                         }
1809                         charInserted();
1810                         return;
1811                 }
1812         } else if (IsNewlineChar(c)) {
1813                 if (cursor.pos() <= cursor.par()->beginningOfMainBody()) {
1814                         charInserted();
1815                         return;
1816                 }
1817                 // No newline at first position of a paragraph or behind labels.
1818                 // TeX does not allow that
1819
1820                 if (cursor.pos() < cursor.par()->size() &&
1821                     cursor.par()->isLineSeparator(cursor.pos()))
1822                         // newline always after a blank!
1823                         cursorRight(bview);
1824                 cursor.row()->fill(-1);        // to force a new break
1825         }
1826
1827         // the display inset stuff
1828         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1829                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1830                 if (inset && (inset->display() || inset->needFullRow())) {
1831                         // force a new break
1832                         cursor.row()->fill(-1); // to force a new break
1833                 }
1834         }
1835
1836         // get the cursor row fist
1837         Row * row = cursor.row();
1838         int y = cursor.y() - row->baseline();
1839         if (c != Paragraph::META_INSET) {
1840                 // Here case LyXText::InsertInset  already insertet the character
1841                 cursor.par()->insertChar(cursor.pos(), c);
1842         }
1843         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1844
1845         if (!jumped_over_space) {
1846                 // refresh the positions
1847                 Row * tmprow = row;
1848                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1849                         tmprow = tmprow->next();
1850                         tmprow->pos(tmprow->pos() + 1);
1851                 }
1852         }
1853
1854         // Is there a break one row above
1855         if (row->previous() && row->previous()->par() == row->par()
1856             && (cursor.par()->isLineSeparator(cursor.pos())
1857                 || cursor.par()->isNewline(cursor.pos())
1858                 || ((cursor.pos() < cursor.par()->size()) &&
1859                     cursor.par()->isInset(cursor.pos()+1))
1860                 || cursor.row()->fill() == -1))
1861         {
1862                 pos_type z = nextBreakPoint(bview,
1863                                                            row->previous(),
1864                                                            workWidth(bview));
1865                 if (z >= row->pos()) {
1866                         row->pos(z + 1);
1867
1868                         // set the dimensions of the row above
1869                         row->previous()->fill(fill(bview,
1870                                                    row->previous(),
1871                                                    workWidth(bview)));
1872
1873                         setHeightOfRow(bview, row->previous());
1874
1875                         y -= row->previous()->height();
1876                         refresh_y = y;
1877                         refresh_row = row->previous();
1878                         status(bview, LyXText::NEED_MORE_REFRESH);
1879
1880                         breakAgainOneRow(bview, row);
1881
1882                         current_font = rawtmpfont;
1883                         real_current_font = realtmpfont;
1884                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1885                                   false, cursor.boundary());
1886                         // cursor MUST be in row now.
1887
1888                         if (row->next() && row->next()->par() == row->par())
1889                                 need_break_row = row->next();
1890                         else
1891                                 need_break_row = 0;
1892
1893                         // check, wether the last characters font has changed.
1894                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1895                             && rawparfont != rawtmpfont)
1896                                 redoHeightOfParagraph(bview, cursor);
1897
1898                         charInserted();
1899                         return;
1900                 }
1901         }
1902
1903         // recalculate the fill of the row
1904         if (row->fill() >= 0) {
1905                 // needed because a newline will set fill to -1. Otherwise
1906                 // we would not get a rebreak!
1907                 row->fill(fill(bview, row, workWidth(bview)));
1908         }
1909
1910         if (c == Paragraph::META_INSET || row->fill() < 0) {
1911                 refresh_y = y;
1912                 refresh_row = row;
1913                 status(bview, LyXText::NEED_MORE_REFRESH);
1914                 breakAgainOneRow(bview, row);
1915                 // will the cursor be in another row now?
1916                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1917                         if (row->next() && row->next()->par() == row->par())
1918                                 // this should always be true
1919                                 row = row->next();
1920                         breakAgainOneRow(bview, row);
1921                 }
1922                 current_font = rawtmpfont;
1923                 real_current_font = realtmpfont;
1924
1925                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1926                           cursor.boundary());
1927                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1928                     != cursor.boundary())
1929                         setCursor(bview, cursor.par(), cursor.pos(), false,
1930                           !cursor.boundary());
1931                 if (row->next() && row->next()->par() == row->par())
1932                         need_break_row = row->next();
1933                 else
1934                         need_break_row = 0;
1935         } else {
1936                 refresh_y = y;
1937                 refresh_row = row;
1938
1939                 int const tmpheight = row->height();
1940                 setHeightOfRow(bview, row);
1941                 if (tmpheight == row->height())
1942                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1943                 else
1944                         status(bview, LyXText::NEED_MORE_REFRESH);
1945
1946                 current_font = rawtmpfont;
1947                 real_current_font = realtmpfont;
1948                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1949                           cursor.boundary());
1950         }
1951
1952         // check, wether the last characters font has changed.
1953         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1954             && rawparfont != rawtmpfont) {
1955                 redoHeightOfParagraph(bview, cursor);
1956         } else {
1957                 // now the special right address boxes
1958                 if (cursor.par()->layout()->margintype
1959                     == MARGIN_RIGHT_ADDRESS_BOX) {
1960                         redoDrawingOfParagraph(bview, cursor);
1961                 }
1962         }
1963
1964         charInserted();
1965 }
1966
1967
1968 void LyXText::charInserted()
1969 {
1970         // Here we could call FinishUndo for every 20 characters inserted.
1971         // This is from my experience how emacs does it.
1972         static unsigned int counter;
1973         if (counter < 20) {
1974                 ++counter;
1975         } else {
1976                 finishUndo();
1977                 counter = 0;
1978         }
1979 }
1980
1981
1982 void LyXText::prepareToPrint(BufferView * bview,
1983                              Row * row, float & x,
1984                              float & fill_separator,
1985                              float & fill_hfill,
1986                              float & fill_label_hfill,
1987                              bool bidi) const
1988 {
1989         float nlh;
1990         float ns;
1991
1992         float w = row->fill();
1993         fill_hfill = 0;
1994         fill_label_hfill = 0;
1995         fill_separator = 0;
1996         fill_label_hfill = 0;
1997
1998         bool const is_rtl =
1999                 row->par()->isRightToLeftPar(bview->buffer()->params);
2000         if (is_rtl) {
2001                 x = (workWidth(bview) > 0)
2002                         ? rightMargin(bview->buffer(), row) : 0;
2003         } else
2004                 x = (workWidth(bview) > 0)
2005                         ? leftMargin(bview, row) : 0;
2006
2007         // is there a manual margin with a manual label
2008         LyXLayout_ptr const & layout = row->par()->layout();
2009
2010         if (layout->margintype == MARGIN_MANUAL
2011             && layout->labeltype == LABEL_MANUAL) {
2012                 // one more since labels are left aligned
2013                 nlh = row->numberOfLabelHfills() + 1;
2014                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2015                         fill_label_hfill = labelFill(bview, row) / nlh;
2016                 }
2017         }
2018
2019         // are there any hfills in the row?
2020         float const nh = row->numberOfHfills();
2021
2022         if (nh) {
2023                 if (w > 0)
2024                         fill_hfill = w / nh;
2025         // we don't have to look at the alignment if it is ALIGN_LEFT and
2026         // if the row is already larger then the permitted width as then
2027         // we force the LEFT_ALIGN'edness!
2028         } else if (static_cast<int>(row->width()) < workWidth(bview)) {
2029                 // is it block, flushleft or flushright?
2030                 // set x how you need it
2031                 int align;
2032                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
2033                         align = layout->align;
2034                 } else {
2035                         align = row->par()->params().align();
2036                 }
2037
2038                 // center displayed insets
2039                 Inset * inset;
2040                 if (row->par()->isInset(row->pos())
2041                     && (inset=row->par()->getInset(row->pos()))
2042                     && (inset->display())) // || (inset->scroll() < 0)))
2043                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
2044                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2045                 // ERT insets should always be LEFT ALIGNED on screen
2046                 inset = row->par()->inInset();
2047                 if (inset && inset->owner() &&
2048                         inset->owner()->lyxCode() == Inset::ERT_CODE)
2049                 {
2050                         align = LYX_ALIGN_LEFT;
2051                 }
2052
2053                 switch (align) {
2054             case LYX_ALIGN_BLOCK:
2055                         ns = row->numberOfSeparators();
2056                         if (ns && row->next() && row->next()->par() == row->par() &&
2057                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
2058                             && !(row->next()->par()->isInset(row->next()->pos())
2059                                  && row->next()->par()->getInset(row->next()->pos())
2060                                  && row->next()->par()->getInset(row->next()->pos())->display())
2061                                 )
2062                         {
2063                                 fill_separator = w / ns;
2064                         } else if (is_rtl) {
2065                                 x += w;
2066                         }
2067                         break;
2068             case LYX_ALIGN_RIGHT:
2069                         x += w;
2070                         break;
2071             case LYX_ALIGN_CENTER:
2072                         x += w / 2;
2073                         break;
2074                 }
2075         }
2076         if (!bidi)
2077                 return;
2078
2079         computeBidiTables(bview->buffer(), row);
2080         if (is_rtl) {
2081                 pos_type main_body = row->par()->beginningOfMainBody();
2082                 pos_type last = row->lastPos();
2083
2084                 if (main_body > 0 &&
2085                     (main_body - 1 > last ||
2086                      !row->par()->isLineSeparator(main_body - 1))) {
2087                         x += font_metrics::width(layout->labelsep,
2088                                             getLabelFont(bview->buffer(), row->par()));
2089                         if (main_body - 1 <= last)
2090                                 x += fill_label_hfill;
2091                 }
2092         }
2093 }
2094
2095
2096 // important for the screen
2097
2098
2099 // the cursor set functions have a special mechanism. When they
2100 // realize, that you left an empty paragraph, they will delete it.
2101 // They also delete the corresponding row
2102
2103 void LyXText::cursorRightOneWord(BufferView * bview) const
2104 {
2105         // treat floats, HFills and Insets as words
2106         LyXCursor tmpcursor = cursor;
2107         // CHECK See comment on top of text.C
2108
2109         if (tmpcursor.pos() == tmpcursor.par()->size()
2110             && tmpcursor.par()->next()) {
2111                         tmpcursor.par(tmpcursor.par()->next());
2112                         tmpcursor.pos(0);
2113         } else {
2114                 int steps = 0;
2115
2116                 // Skip through initial nonword stuff.
2117                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2118                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2119                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2120                         tmpcursor.pos(tmpcursor.pos() + 1);
2121                         ++steps;
2122                 }
2123                 // Advance through word.
2124                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2125                         tmpcursor.par()->isWord(tmpcursor.pos())) {
2126                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2127                         tmpcursor.pos(tmpcursor.pos() + 1);
2128                         ++steps;
2129                 }
2130         }
2131         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2132 }
2133
2134
2135 void LyXText::cursorTab(BufferView * bview) const
2136 {
2137         LyXCursor tmpcursor = cursor;
2138         while (tmpcursor.pos() < tmpcursor.par()->size()
2139            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2140         tmpcursor.pos(tmpcursor.pos() + 1);
2141
2142         if (tmpcursor.pos() == tmpcursor.par()->size()) {
2143                 if (tmpcursor.par()->next()) {
2144                         tmpcursor.par(tmpcursor.par()->next());
2145                         tmpcursor.pos(0);
2146                 }
2147         } else
2148                 tmpcursor.pos(tmpcursor.pos() + 1);
2149         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2150 }
2151
2152
2153 // Skip initial whitespace at end of word and move cursor to *start*
2154 // of prior word, not to end of next prior word.
2155 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2156 {
2157         LyXCursor tmpcursor = cursor;
2158         cursorLeftOneWord(tmpcursor);
2159         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2160 }
2161
2162
2163 void LyXText::cursorLeftOneWord(LyXCursor & cur) const
2164 {
2165         // treat HFills, floats and Insets as words
2166         cur = cursor;
2167         while (cur.pos()
2168                && (cur.par()->isSeparator(cur.pos() - 1)
2169                    || cur.par()->isKomma(cur.pos() - 1))
2170                && !(cur.par()->isHfill(cur.pos() - 1)
2171                     || cur.par()->isInset(cur.pos() - 1)))
2172                 cur.pos(cur.pos() - 1);
2173
2174         if (cur.pos()
2175             && (cur.par()->isInset(cur.pos() - 1)
2176                 || cur.par()->isHfill(cur.pos() - 1))) {
2177                 cur.pos(cur.pos() - 1);
2178         } else if (!cur.pos()) {
2179                 if (cur.par()->previous()) {
2180                         cur.par(cur.par()->previous());
2181                         cur.pos(cur.par()->size());
2182                 }
2183         } else {                // Here, cur != 0
2184                 while (cur.pos() > 0 &&
2185                        cur.par()->isWord(cur.pos() - 1))
2186                         cur.pos(cur.pos() - 1);
2187         }
2188 }
2189
2190
2191 // Select current word. This depends on behaviour of
2192 // CursorLeftOneWord(), so it is patched as well.
2193 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
2194                       word_location const loc) const
2195 {
2196         // first put the cursor where we wana start to select the word
2197         from = cursor;
2198         switch (loc) {
2199         case WHOLE_WORD_STRICT:
2200                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2201                     || cursor.par()->isSeparator(cursor.pos())
2202                     || cursor.par()->isKomma(cursor.pos())
2203                     || cursor.par()->isSeparator(cursor.pos() - 1)
2204                     || cursor.par()->isKomma(cursor.pos() - 1)) {
2205                         to = from;
2206                         return;
2207                 }
2208                 // no break here, we go to the next
2209
2210         case WHOLE_WORD:
2211                 // Move cursor to the beginning, when not already there.
2212                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2213                     && !from.par()->isKomma(from.pos() - 1))
2214                         cursorLeftOneWord(from);
2215                 break;
2216         case PREVIOUS_WORD:
2217                 // always move the cursor to the beginning of previous word
2218                 cursorLeftOneWord(from);
2219                 break;
2220         case NEXT_WORD:
2221                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2222                 break;
2223         case PARTIAL_WORD:
2224                 break;
2225         }
2226         to = from;
2227         while (to.pos() < to.par()->size()
2228                && !to.par()->isSeparator(to.pos())
2229                && !to.par()->isKomma(to.pos())
2230                && !to.par()->isHfill(to.pos())
2231                && !to.par()->isInset(to.pos()))
2232         {
2233                 to.pos(to.pos() + 1);
2234         }
2235 }
2236
2237
2238 void LyXText::selectWord(BufferView * bview, word_location const loc)
2239 {
2240         LyXCursor from;
2241         LyXCursor to;
2242         getWord(from, to, loc);
2243         if (cursor != from)
2244                 setCursor(bview, from.par(), from.pos());
2245         if (to == from)
2246                 return;
2247         selection.cursor = cursor;
2248         setCursor(bview, to.par(), to.pos());
2249         setSelection(bview);
2250 }
2251
2252
2253 // Select the word currently under the cursor when no
2254 // selection is currently set
2255 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2256                                         word_location const loc)
2257 {
2258         if (!selection.set()) {
2259                 selectWord(bview, loc);
2260                 return selection.set();
2261         }
2262         return false;
2263 }
2264
2265
2266 void LyXText::acceptChange(BufferView * bv)
2267 {
2268         if (!selection.set() && cursor.par()->size())
2269                 return;
2270
2271         bv->hideCursor();
2272  
2273         if (selection.start.par() == selection.end.par()) {
2274                 LyXCursor & startc = selection.start;
2275                 LyXCursor & endc = selection.end;
2276                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2277                 startc.par()->acceptChange(startc.pos(), endc.pos());
2278                 finishUndo();
2279                 clearSelection();
2280                 redoParagraphs(bv, startc, startc.par()->next());
2281                 setCursorIntern(bv, startc.par(), 0);
2282         }
2283 #warning handle multi par selection
2284 }
2285
2286
2287 void LyXText::rejectChange(BufferView * bv)
2288 {
2289         if (!selection.set() && cursor.par()->size())
2290                 return;
2291  
2292         bv->hideCursor();
2293  
2294         if (selection.start.par() == selection.end.par()) {
2295                 LyXCursor & startc = selection.start;
2296                 LyXCursor & endc = selection.end;
2297                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2298                 startc.par()->rejectChange(startc.pos(), endc.pos());
2299                 finishUndo();
2300                 clearSelection();
2301                 redoParagraphs(bv, startc, startc.par()->next());
2302                 setCursorIntern(bv, startc.par(), 0);
2303         }
2304 #warning handle multi par selection
2305 }
2306
2307  
2308 // This function is only used by the spellchecker for NextWord().
2309 // It doesn't handle LYX_ACCENTs and probably never will.
2310 WordLangTuple const
2311 LyXText::selectNextWordToSpellcheck(BufferView * bview, float & value) const
2312 {
2313         if (the_locking_inset) {
2314                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2315                 if (!word.word().empty()) {
2316                         value += float(cursor.y());
2317                         value /= float(height);
2318                         return word;
2319                 }
2320                 // we have to go on checking so move cursor to the next char
2321                 if (cursor.pos() == cursor.par()->size()) {
2322                         if (!cursor.par()->next())
2323                                 return word;
2324                         cursor.par(cursor.par()->next());
2325                         cursor.pos(0);
2326                 } else
2327                         cursor.pos(cursor.pos() + 1);
2328         }
2329         Paragraph * tmppar = cursor.par();
2330
2331         // If this is not the very first word, skip rest of
2332         // current word because we are probably in the middle
2333         // of a word if there is text here.
2334         if (cursor.pos() || cursor.par()->previous()) {
2335                 while (cursor.pos() < cursor.par()->size()
2336                        && cursor.par()->isLetter(cursor.pos()))
2337                         cursor.pos(cursor.pos() + 1);
2338         }
2339
2340         // Now, skip until we have real text (will jump paragraphs)
2341         while (1) {
2342                 Paragraph * cpar(cursor.par());
2343                 pos_type const cpos(cursor.pos());
2344  
2345                 if (cpos == cpar->size()) {
2346                         if (cpar->next()) {
2347                                 cursor.par(cpar->next());
2348                                 cursor.pos(0);
2349                                 continue;
2350                         }
2351                         break;
2352                 }
2353
2354                 bool const is_bad_inset(cpar->isInset(cpos)
2355                         && !cpar->getInset(cpos)->allowSpellcheck()); 
2356  
2357                 if (cpar->isLetter(cpos) && !isDeletedText(cpar, cpos)
2358                         && !is_bad_inset)
2359                         break;
2360  
2361                 cursor.pos(cpos + 1);
2362         }
2363  
2364         // now check if we hit an inset so it has to be a inset containing text!
2365         if (cursor.pos() < cursor.par()->size() &&
2366             cursor.par()->isInset(cursor.pos())) {
2367                 // lock the inset!
2368                 cursor.par()->getInset(cursor.pos())->edit(bview);
2369                 // now call us again to do the above trick
2370                 // but obviously we have to start from down below ;)
2371                 return bview->text->selectNextWordToSpellcheck(bview, value);
2372         }
2373
2374         // Update the value if we changed paragraphs
2375         if (cursor.par() != tmppar) {
2376                 setCursor(bview, cursor.par(), cursor.pos());
2377                 value = float(cursor.y())/float(height);
2378         }
2379
2380         // Start the selection from here
2381         selection.cursor = cursor;
2382
2383         string lang_code(
2384                 getFont(bview->buffer(), cursor.par(), cursor.pos())
2385                         .language()->code());
2386         // and find the end of the word (insets like optional hyphens
2387         // and ligature break are part of a word)
2388         while (cursor.pos() < cursor.par()->size()
2389                && cursor.par()->isLetter(cursor.pos())
2390                && !isDeletedText(cursor.par(), cursor.pos()))
2391                 cursor.pos(cursor.pos() + 1);
2392
2393         // Finally, we copy the word to a string and return it
2394         string str;
2395         if (selection.cursor.pos() < cursor.pos()) {
2396                 pos_type i;
2397                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2398                         if (!cursor.par()->isInset(i))
2399                                 str += cursor.par()->getChar(i);
2400                 }
2401         }
2402         return WordLangTuple(str, lang_code);
2403 }
2404
2405
2406 // This one is also only for the spellchecker
2407 void LyXText::selectSelectedWord(BufferView * bview)
2408 {
2409         if (the_locking_inset) {
2410                 the_locking_inset->selectSelectedWord(bview);
2411                 return;
2412         }
2413         // move cursor to the beginning
2414         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2415
2416         // set the sel cursor
2417         selection.cursor = cursor;
2418
2419         // now find the end of the word
2420         while (cursor.pos() < cursor.par()->size()
2421                && (cursor.par()->isLetter(cursor.pos())))
2422                 cursor.pos(cursor.pos() + 1);
2423
2424         setCursor(bview, cursor.par(), cursor.pos());
2425
2426         // finally set the selection
2427         setSelection(bview);
2428 }
2429
2430
2431 // Delete from cursor up to the end of the current or next word.
2432 void LyXText::deleteWordForward(BufferView * bview)
2433 {
2434         if (cursor.par()->empty())
2435                 cursorRight(bview);
2436         else {
2437                 LyXCursor tmpcursor = cursor;
2438                 tmpcursor.row(0); // ??
2439                 selection.set(true); // to avoid deletion
2440                 cursorRightOneWord(bview);
2441                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2442                 selection.cursor = cursor;
2443                 cursor = tmpcursor;
2444                 setSelection(bview);
2445
2446                 // Great, CutSelection() gets rid of multiple spaces.
2447                 cutSelection(bview, true, false);
2448         }
2449 }
2450
2451
2452 // Delete from cursor to start of current or prior word.
2453 void LyXText::deleteWordBackward(BufferView * bview)
2454 {
2455         if (cursor.par()->empty())
2456                 cursorLeft(bview);
2457         else {
2458                 LyXCursor tmpcursor = cursor;
2459                 tmpcursor.row(0); // ??
2460                 selection.set(true); // to avoid deletion
2461                 cursorLeftOneWord(bview);
2462                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2463                 selection.cursor = cursor;
2464                 cursor = tmpcursor;
2465                 setSelection(bview);
2466                 cutSelection(bview, true, false);
2467         }
2468 }
2469
2470
2471 // Kill to end of line.
2472 void LyXText::deleteLineForward(BufferView * bview)
2473 {
2474         if (cursor.par()->empty())
2475                 // Paragraph is empty, so we just go to the right
2476                 cursorRight(bview);
2477         else {
2478                 LyXCursor tmpcursor = cursor;
2479                 // We can't store the row over a regular setCursor
2480                 // so we set it to 0 and reset it afterwards.
2481                 tmpcursor.row(0); // ??
2482                 selection.set(true); // to avoid deletion
2483                 cursorEnd(bview);
2484                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2485                 selection.cursor = cursor;
2486                 cursor = tmpcursor;
2487                 setSelection(bview);
2488                 // What is this test for ??? (JMarc)
2489                 if (!selection.set()) {
2490                         deleteWordForward(bview);
2491                 } else {
2492                         cutSelection(bview, true, false);
2493                 }
2494         }
2495 }
2496
2497
2498 // Change the case of a word at cursor position.
2499 // This function directly manipulates Paragraph::text because there
2500 // is no Paragraph::SetChar currently. I did what I could to ensure
2501 // that it is correct. I guess part of it should be moved to
2502 // Paragraph, but it will have to change for 1.1 anyway. At least
2503 // it does not access outside of the allocated array as the older
2504 // version did. (JMarc)
2505 void LyXText::changeCase(BufferView * bview, LyXText::TextCase action)
2506 {
2507         LyXCursor from;
2508         LyXCursor to;
2509
2510         if (selection.set()) {
2511                 from = selection.start;
2512                 to = selection.end;
2513         } else {
2514                 getWord(from, to, PARTIAL_WORD);
2515                 setCursor(bview, to.par(), to.pos() + 1);
2516         }
2517
2518         changeRegionCase(bview, from, to, action);
2519 }
2520
2521
2522 void LyXText::changeRegionCase(BufferView * bview,
2523                                LyXCursor const & from,
2524                                LyXCursor const & to,
2525                                LyXText::TextCase action)
2526 {
2527         lyx::Assert(from <= to);
2528
2529         setUndo(bview, Undo::FINISH, from.par(), to.par()->next());
2530
2531         pos_type pos = from.pos();
2532         Paragraph * par = from.par();
2533
2534         while (par && (pos != to.pos() || par != to.par())) {
2535                 if (pos == par->size()) {
2536                         par = par->next();
2537                         pos = 0;
2538                         continue;
2539                 }
2540                 unsigned char c = par->getChar(pos);
2541                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2542                         switch (action) {
2543                         case text_lowercase:
2544                                 c = lowercase(c);
2545                                 break;
2546                         case text_capitalization:
2547                                 c = uppercase(c);
2548                                 action = text_lowercase;
2549                                 break;
2550                         case text_uppercase:
2551                                 c = uppercase(c);
2552                                 break;
2553                         }
2554                 }
2555 #warning changes
2556                 par->setChar(pos, c);
2557                 checkParagraph(bview, par, pos);
2558
2559                 ++pos;
2560         }
2561         if (to.row() != from.row()) {
2562                 refresh_y = from.y() - from.row()->baseline();
2563                 refresh_row = from.row();
2564                 status(bview, LyXText::NEED_MORE_REFRESH);
2565         }
2566 }
2567
2568
2569 void LyXText::transposeChars(BufferView & bview)
2570 {
2571         Paragraph * tmppar = cursor.par();
2572
2573         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2574
2575         pos_type tmppos = cursor.pos();
2576
2577         // First decide if it is possible to transpose at all
2578  
2579         if (tmppos == 0 || tmppos == tmppar->size())
2580                 return;
2581
2582         if (isDeletedText(tmppar, tmppos - 1)
2583                 || isDeletedText(tmppar, tmppos))
2584                 return;
2585
2586         unsigned char c1 = tmppar->getChar(tmppos);
2587         unsigned char c2 = tmppar->getChar(tmppos - 1);
2588
2589         // We should have an implementation that handles insets
2590         // as well, but that will have to come later. (Lgb)
2591         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET) 
2592                 return;
2593  
2594         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2595         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2596
2597         tmppar->insertChar(ipos, c1);
2598         tmppar->insertChar(ipos + 1, c2);
2599
2600         /* fugly */
2601         BufferView * bv(const_cast<BufferView*>(&bview));
2602  
2603         checkParagraph(bv, tmppar, tmppos);
2604 }
2605
2606
2607 void LyXText::Delete(BufferView * bview)
2608 {
2609         // this is a very easy implementation
2610
2611         LyXCursor old_cursor = cursor;
2612         int const old_cur_par_id = old_cursor.par()->id();
2613         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2614                 old_cursor.par()->previous()->id() : -1;
2615
2616         // just move to the right
2617         cursorRight(bview);
2618
2619         // CHECK Look at the comment here.
2620         // This check is not very good...
2621         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2622         // and that can very well delete the par or par->previous in
2623         // old_cursor. Will a solution where we compare paragraph id's
2624         //work better?
2625         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2626             == old_cur_par_prev_id
2627             && cursor.par()->id() != old_cur_par_id) {
2628                 // delete-empty-paragraph-mechanism has done it
2629                 return;
2630         }
2631
2632         // if you had success make a backspace
2633         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2634                 LyXCursor tmpcursor = cursor;
2635                 // to make sure undo gets the right cursor position
2636                 cursor = old_cursor;
2637                 setUndo(bview, Undo::DELETE,
2638                         cursor.par(), cursor.par()->next());
2639                 cursor = tmpcursor;
2640                 backspace(bview);
2641         }
2642 }
2643
2644
2645 void LyXText::backspace(BufferView * bview)
2646 {
2647         // Get the font that is used to calculate the baselineskip
2648         pos_type lastpos = cursor.par()->size();
2649         LyXFont rawparfont =
2650                 cursor.par()->getFontSettings(bview->buffer()->params,
2651                                               lastpos - 1);
2652
2653         if (cursor.pos() == 0) {
2654                 // The cursor is at the beginning of a paragraph,
2655                 // so the the backspace will collapse two paragraphs into one.
2656
2657                 // but it's not allowed unless it's new
2658                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2659                         return;
2660  
2661                 // we may paste some paragraphs
2662
2663                 // is it an empty paragraph?
2664
2665                 if ((lastpos == 0
2666                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2667                         // This is an empty paragraph and we delete it just by moving the cursor one step
2668                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2669                         // of the paragraph.
2670
2671                         if (cursor.par()->previous()) {
2672                                 Paragraph * tmppar = cursor.par()->previous();
2673                                 if (cursor.par()->layout() == tmppar->layout()
2674                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2675                                         // Inherit bottom DTD from the paragraph below.
2676                                         // (the one we are deleting)
2677                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2678                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2679                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2680                                 }
2681
2682                                 cursorLeft(bview);
2683
2684                                 // the layout things can change the height of a row !
2685                                 int const tmpheight = cursor.row()->height();
2686                                 setHeightOfRow(bview, cursor.row());
2687                                 if (cursor.row()->height() != tmpheight) {
2688                                         refresh_y = cursor.y() - cursor.row()->baseline();
2689                                         refresh_row = cursor.row();
2690                                         status(bview, LyXText::NEED_MORE_REFRESH);
2691                                 }
2692                                 return;
2693                         }
2694                 }
2695
2696                 if (cursor.par()->previous()) {
2697                         setUndo(bview, Undo::DELETE,
2698                                 cursor.par()->previous(), cursor.par()->next());
2699                 }
2700
2701                 Paragraph * tmppar = cursor.par();
2702                 Row * tmprow = cursor.row();
2703
2704                 // We used to do cursorLeftIntern() here, but it is
2705                 // not a good idea since it triggers the auto-delete
2706                 // mechanism. So we do a cursorLeftIntern()-lite,
2707                 // without the dreaded mechanism. (JMarc)
2708                 if (cursor.par()->previous()) {
2709                         // steps into the above paragraph.
2710                         setCursorIntern(bview, cursor.par()->previous(),
2711                                         cursor.par()->previous()->size(),
2712                                         false);
2713                 }
2714
2715                 // Pasting is not allowed, if the paragraphs have different
2716                 // layout. I think it is a real bug of all other
2717                 // word processors to allow it. It confuses the user.
2718                 // Even so with a footnote paragraph and a non-footnote
2719                 // paragraph. I will not allow pasting in this case,
2720                 // because the user would be confused if the footnote behaves
2721                 // different wether it is open or closed.
2722
2723                 //      Correction: Pasting is always allowed with standard-layout
2724                 LyXTextClass const & tclass =
2725                         bview->buffer()->params.getLyXTextClass();
2726
2727                 if (cursor.par() != tmppar
2728                     && (cursor.par()->layout() == tmppar->layout()
2729                         || tmppar->layout() == tclass.defaultLayout())
2730                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2731                         removeParagraph(tmprow);
2732                         removeRow(tmprow);
2733                         mergeParagraph(bview->buffer()->params, cursor.par());
2734
2735                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2736                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2737                         // strangely enough it seems that commenting out the line above removes
2738                         // most or all of the segfaults. I will however also try to move the
2739                         // two Remove... lines in front of the PasteParagraph too.
2740                         else
2741                                 if (cursor.pos())
2742                                         cursor.pos(cursor.pos() - 1);
2743
2744                         status(bview, LyXText::NEED_MORE_REFRESH);
2745                         refresh_row = cursor.row();
2746                         refresh_y = cursor.y() - cursor.row()->baseline();
2747
2748                         // remove the lost paragraph
2749                         // This one is not safe, since the paragraph that the tmprow and the
2750                         // following rows belong to has been deleted by the PasteParagraph
2751                         // above. The question is... could this be moved in front of the
2752                         // PasteParagraph?
2753                         //RemoveParagraph(tmprow);
2754                         //RemoveRow(tmprow);
2755
2756                         // This rebuilds the rows.
2757                         appendParagraph(bview, cursor.row());
2758                         updateCounters(bview);
2759
2760                         // the row may have changed, block, hfills etc.
2761                         setCursor(bview, cursor.par(), cursor.pos(), false);
2762                 }
2763         } else {
2764                 // this is the code for a normal backspace, not pasting
2765                 // any paragraphs
2766                 setUndo(bview, Undo::DELETE,
2767                         cursor.par(), cursor.par()->next());
2768                 // We used to do cursorLeftIntern() here, but it is
2769                 // not a good idea since it triggers the auto-delete
2770                 // mechanism. So we do a cursorLeftIntern()-lite,
2771                 // without the dreaded mechanism. (JMarc)
2772                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2773                                 false, cursor.boundary());
2774
2775                 if (cursor.par()->isInset(cursor.pos())) {
2776                         // force complete redo when erasing display insets
2777                         // this is a cruel method but safe..... Matthias
2778                         if (cursor.par()->getInset(cursor.pos())->display() ||
2779                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2780                                 cursor.par()->erase(cursor.pos());
2781                                 redoParagraph(bview);
2782                                 return;
2783                         }
2784                 }
2785
2786                 Row * row = cursor.row();
2787                 int y = cursor.y() - row->baseline();
2788                 pos_type z;
2789                 // remember that a space at the end of a row doesnt count
2790                 // when calculating the fill
2791                 if (cursor.pos() < row->lastPos() ||
2792                     !cursor.par()->isLineSeparator(cursor.pos())) {
2793                         row->fill(row->fill() + singleWidth(bview,
2794                                                             cursor.par(),
2795                                                             cursor.pos()));
2796                 }
2797
2798                 // some special code when deleting a newline. This is similar
2799                 // to the behavior when pasting paragraphs
2800                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2801                         cursor.par()->erase(cursor.pos());
2802                         // refresh the positions
2803                         Row * tmprow = row;
2804                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2805                                 tmprow = tmprow->next();
2806                                 tmprow->pos(tmprow->pos() - 1);
2807                         }
2808                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2809                                 cursor.pos(cursor.pos() - 1);
2810
2811                         if (cursor.pos() < cursor.par()->size()
2812                             && !cursor.par()->isSeparator(cursor.pos())) {
2813                                 cursor.par()->insertChar(cursor.pos(), ' ');
2814                                 setCharFont(bview->buffer(), cursor.par(),
2815                                             cursor.pos(), current_font);
2816                                 // refresh the positions
2817                                 tmprow = row;
2818                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2819                                         tmprow = tmprow->next();
2820                                         tmprow->pos(tmprow->pos() + 1);
2821                                 }
2822                         }
2823                 } else {
2824                         cursor.par()->erase(cursor.pos());
2825
2826                         // refresh the positions
2827                         Row * tmprow = row;
2828                         while (tmprow->next()
2829                                && tmprow->next()->par() == row->par()) {
2830                                 tmprow = tmprow->next();
2831                                 tmprow->pos(tmprow->pos() - 1);
2832                         }
2833
2834                         // delete newlines at the beginning of paragraphs
2835                         while (!cursor.par()->empty() &&
2836                                cursor.par()->isNewline(cursor.pos()) &&
2837                                cursor.pos() == cursor.par()->beginningOfMainBody()) {
2838                                 cursor.par()->erase(cursor.pos());
2839                                 // refresh the positions
2840                                 tmprow = row;
2841                                 while (tmprow->next() &&
2842                                        tmprow->next()->par() == row->par()) {
2843                                         tmprow = tmprow->next();
2844                                         tmprow->pos(tmprow->pos() - 1);
2845                                 }
2846                         }
2847                 }
2848
2849                 // is there a break one row above
2850                 if (row->previous() && row->previous()->par() == row->par()) {
2851                         z = nextBreakPoint(bview, row->previous(),
2852                                            workWidth(bview));
2853                         if (z >= row->pos()) {
2854                                 row->pos(z + 1);
2855
2856                                 Row * tmprow = row->previous();
2857
2858                                 // maybe the current row is now empty
2859                                 if (row->pos() >= row->par()->size()) {
2860                                         // remove it
2861                                         removeRow(row);
2862                                         need_break_row = 0;
2863                                 } else {
2864                                         breakAgainOneRow(bview, row);
2865                                         if (row->next() && row->next()->par() == row->par())
2866                                                 need_break_row = row->next();
2867                                         else
2868                                                 need_break_row = 0;
2869                                 }
2870
2871                                 // set the dimensions of the row above
2872                                 y -= tmprow->height();
2873                                 tmprow->fill(fill(bview, tmprow,
2874                                                   workWidth(bview)));
2875                                 setHeightOfRow(bview, tmprow);
2876
2877                                 refresh_y = y;
2878                                 refresh_row = tmprow;
2879                                 status(bview, LyXText::NEED_MORE_REFRESH);
2880                                 setCursor(bview, cursor.par(), cursor.pos(),
2881                                           false, cursor.boundary());
2882                                 //current_font = rawtmpfont;
2883                                 //real_current_font = realtmpfont;
2884                                 // check, whether the last character's font has changed.
2885                                 if (rawparfont !=
2886                                     cursor.par()->getFontSettings(bview->buffer()->params,
2887                                                                   cursor.par()->size() - 1))
2888                                         redoHeightOfParagraph(bview, cursor);
2889                                 return;
2890                         }
2891                 }
2892
2893                 // break the cursor row again
2894                 if (row->next() && row->next()->par() == row->par() &&
2895                     (row->lastPos() == row->par()->size() - 1 ||
2896                      nextBreakPoint(bview, row, workWidth(bview)) != row->lastPos())) {
2897
2898                         // it can happen that a paragraph loses one row
2899                         // without a real breakup. This is when a word
2900                         // is to long to be broken. Well, I don t care this
2901                         // hack ;-)
2902                         if (row->lastPos() == row->par()->size() - 1)
2903                                 removeRow(row->next());
2904
2905                         refresh_y = y;
2906                         refresh_row = row;
2907                         status(bview, LyXText::NEED_MORE_REFRESH);
2908
2909                         breakAgainOneRow(bview, row);
2910                         // will the cursor be in another row now?
2911                         if (row->next() && row->next()->par() == row->par() &&
2912                             row->lastPos() <= cursor.pos()) {
2913                                 row = row->next();
2914                                 breakAgainOneRow(bview, row);
2915                         }
2916
2917                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2918
2919                         if (row->next() && row->next()->par() == row->par())
2920                                 need_break_row = row->next();
2921                         else
2922                                 need_break_row = 0;
2923                 } else  {
2924                         // set the dimensions of the row
2925                         row->fill(fill(bview, row, workWidth(bview)));
2926                         int const tmpheight = row->height();
2927                         setHeightOfRow(bview, row);
2928                         if (tmpheight == row->height())
2929                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2930                         else
2931                                 status(bview, LyXText::NEED_MORE_REFRESH);
2932                         refresh_y = y;
2933                         refresh_row = row;
2934                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2935                 }
2936         }
2937
2938         // current_font = rawtmpfont;
2939         // real_current_font = realtmpfont;
2940
2941         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2942             != cursor.boundary())
2943                 setCursor(bview, cursor.par(), cursor.pos(), false,
2944                           !cursor.boundary());
2945
2946         lastpos = cursor.par()->size();
2947         if (cursor.pos() == lastpos)
2948                 setCurrentFont(bview);
2949
2950         // check, whether the last characters font has changed.
2951         if (rawparfont !=
2952             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2953                 redoHeightOfParagraph(bview, cursor);
2954         } else {
2955                 // now the special right address boxes
2956                 if (cursor.par()->layout()->margintype
2957                     == MARGIN_RIGHT_ADDRESS_BOX) {
2958                         redoDrawingOfParagraph(bview, cursor);
2959                 }
2960         }
2961 }
2962
2963
2964 bool LyXText::paintRowBackground(DrawRowParams & p)
2965 {
2966         bool clear_area = true;
2967         Inset * inset = 0;
2968         LyXFont font(LyXFont::ALL_SANE);
2969
2970         pos_type const last = p.row->lastPrintablePos();
2971
2972         if (!p.bv->screen().forceClear() && last == p.row->pos()
2973                 && p.row->par()->isInset(p.row->pos())) {
2974                 inset = p.row->par()->getInset(p.row->pos());
2975                 if (inset) {
2976                         clear_area = inset->doClearArea();
2977                 }
2978         }
2979
2980         if (p.cleared) {
2981                 return true;
2982         }
2983
2984         if (clear_area) {
2985                 int const x = p.xo;
2986                 int const y = p.yo < 0 ? 0 : p.yo;
2987                 int const h = p.yo < 0 ? p.row->height() + p.yo : p.row->height();
2988                 p.pain->fillRectangle(x, y, p.width, h, backgroundColor());
2989                 return true;
2990         }
2991
2992         if (inset == 0)
2993                 return false;
2994
2995         int h = p.row->baseline() - inset->ascent(p.bv, font);
2996
2997         // first clear the whole row above the inset!
2998         if (h > 0) {
2999                 p.pain->fillRectangle(p.xo, p.yo, p.width, h, backgroundColor());
3000         }
3001
3002         // clear the space below the inset!
3003         h += inset->ascent(p.bv, font) + inset->descent(p.bv, font);
3004         if ((p.row->height() - h) > 0) {
3005                 p.pain->fillRectangle(p.xo, p.yo + h,
3006                         p.width, p.row->height() - h, backgroundColor());
3007         }
3008
3009         // clear the space behind the inset, if needed
3010         if (!inset->display() && !inset->needFullRow()) {
3011                 int const xp = int(p.x) + inset->width(p.bv, font);
3012                 if (p.width - xp > 0) {
3013                         p.pain->fillRectangle(xp, p.yo, p.width - xp,
3014                                 p.row->height(), backgroundColor());
3015                 }
3016         }
3017
3018         return false;
3019 }
3020
3021
3022 void LyXText::paintRowSelection(DrawRowParams & p)
3023 {
3024         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3025
3026         // the current selection
3027         int const startx = selection.start.x();
3028         int const endx = selection.end.x();
3029         int const starty = selection.start.y();
3030         int const endy = selection.end.y();
3031         Row const * startrow = selection.start.row();
3032         Row const * endrow = selection.end.row();
3033
3034         Row * row = p.row;
3035
3036         if (bidi_same_direction) {
3037                 int x;
3038                 int y = p.yo;
3039                 int w;
3040                 int h = row->height();
3041
3042                 if (startrow == row && endrow == row) {
3043                         if (startx < endx) {
3044                                 x = p.xo + startx;
3045                                 w = endx - startx;
3046                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3047                         } else {
3048                                 x = p.xo + endx;
3049                                 w = startx - endx;
3050                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3051                         }
3052                 } else if (startrow == row) {
3053                         int const x = (is_rtl) ? p.xo : (p.xo + startx);
3054                         int const w = (is_rtl) ? startx : (p.width - startx);
3055                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3056                 } else if (endrow == row) {
3057                         int const x = (is_rtl) ? (p.xo + endx) : p.xo;
3058                         int const w = (is_rtl) ? (p.width - endx) : endx;
3059                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3060                 } else if (p.y > starty && p.y < endy) {
3061                         p.pain->fillRectangle(p.xo, y, p.width, h, LColor::selection);
3062                 }
3063                 return;
3064         } else if (startrow != row && endrow != row) {
3065                 if (p.y > starty && p.y < endy) {
3066                         int w = p.width;
3067                         int h = row->height();
3068                         p.pain->fillRectangle(p.xo, p.yo, w, h, LColor::selection);
3069                 }
3070                 return;
3071         }
3072
3073         if ((startrow != row && !is_rtl) || (endrow != row && is_rtl))
3074                 p.pain->fillRectangle(p.xo, p.yo, int(p.x), row->height(), LColor::selection);
3075
3076         Buffer const * buffer = p.bv->buffer();
3077         Paragraph * par = row->par();
3078         pos_type const main_body = par->beginningOfMainBody();
3079         pos_type const last = row->lastPrintablePos();
3080         float tmpx = p.x;
3081
3082         for (pos_type vpos = row->pos(); vpos <= last; ++vpos)  {
3083                 pos_type pos = vis2log(vpos);
3084                 float const old_tmpx = tmpx;
3085                 if (main_body > 0 && pos == main_body - 1) {
3086                         LyXLayout_ptr const & layout = par->layout();
3087                         LyXFont const lfont = getLabelFont(buffer, par);
3088
3089                         tmpx += p.label_hfill + font_metrics::width(layout->labelsep, lfont);
3090
3091                         if (par->isLineSeparator(main_body - 1))
3092                                 tmpx -= singleWidth(p.bv, par, main_body - 1);
3093                 }
3094
3095                 if (row->hfillExpansion(pos)) {
3096                         tmpx += singleWidth(p.bv, par, pos);
3097                         if (pos >= main_body)
3098                                 tmpx += p.hfill;
3099                         else
3100                                 tmpx += p.label_hfill;
3101                 }
3102
3103                 else if (par->isSeparator(pos)) {
3104                         tmpx += singleWidth(p.bv, par, pos);
3105                         if (pos >= main_body)
3106                                 tmpx += p.separator;
3107                 } else {
3108                         tmpx += singleWidth(p.bv, par, pos);
3109                 }
3110
3111                 if ((startrow != row || selection.start.pos() <= pos) &&
3112                         (endrow != row || pos < selection.end.pos())) {
3113                         // Here we do not use p.x as p.xo was added to p.x.
3114                         p.pain->fillRectangle(int(old_tmpx), p.yo,
3115                                 int(tmpx - old_tmpx + 1),
3116                                 row->height(), LColor::selection);
3117                 }
3118         }
3119
3120         if ((startrow != row && is_rtl) || (endrow != row && !is_rtl)) {
3121                 p.pain->fillRectangle(p.xo + int(tmpx),
3122                                       p.yo, int(p.bv->workWidth() - tmpx),
3123                                       row->height(), LColor::selection);
3124         }
3125 }
3126
3127
3128 void LyXText::paintChangeBar(DrawRowParams & p)
3129 {
3130         pos_type const start = p.row->pos();
3131         pos_type const end = p.row->lastPrintablePos();
3132
3133         if (!p.row->par()->isChanged(start, end)) 
3134                 return;
3135  
3136         int const height = (p.row->next()
3137                 ? p.row->height() + p.row->next()->top_of_text() 
3138                 : p.row->baseline());
3139  
3140         p.pain->fillRectangle(4, p.yo, 5,
3141                 height, LColor::changebar); 
3142 }
3143
3144  
3145 void LyXText::paintRowAppendix(DrawRowParams & p)
3146 {
3147         // FIXME: can be just p.width ?
3148         int const ww = p.bv->workWidth();
3149         Paragraph * firstpar = p.row->par();
3150
3151         if (firstpar->params().appendix()) {
3152                 p.pain->line(1, p.yo, 1, p.yo + p.row->height(), LColor::appendixline);
3153                 p.pain->line(ww - 2, p.yo, ww - 2, p.yo + p.row->height(), LColor::appendixline);
3154         }
3155 }
3156
3157
3158 void LyXText::paintRowDepthBar(DrawRowParams & p)
3159 {
3160         Paragraph::depth_type const depth = p.row->par()->getDepth();
3161
3162         if (depth <= 0)
3163                 return;
3164
3165         Paragraph::depth_type prev_depth = 0;
3166         if (p.row->previous())
3167                 prev_depth = p.row->previous()->par()->getDepth();
3168         Paragraph::depth_type next_depth = 0;
3169         if (p.row->next())
3170                 next_depth = p.row->next()->par()->getDepth();
3171
3172         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3173                 int x = (PAPER_MARGIN / 5) * i + p.xo;
3174                 // only consider the changebar space if we're drawing outer left
3175                 if (!p.xo)
3176                         x += CHANGEBAR_MARGIN;
3177                 int const h = p.yo + p.row->height() - 1 - (i - next_depth - 1) * 3;
3178
3179                 p.pain->line(x, p.yo, x, h, LColor::depthbar);
3180
3181                 int const w = PAPER_MARGIN / 5;
3182
3183                 if (i > prev_depth) {
3184                         p.pain->fillRectangle(x, p.yo, w, 2, LColor::depthbar);
3185                 }
3186                 if (i > next_depth) {
3187                         p.pain->fillRectangle(x, h, w, 2, LColor::depthbar);
3188                 }
3189         }
3190 }
3191
3192
3193 int LyXText::getLengthMarkerHeight(BufferView * bv, VSpace const & vsp) const
3194 {
3195         if (vsp.kind() == VSpace::NONE)
3196                 return 0;
3197
3198         int const arrow_size = 4;
3199         int const space_size = int(vsp.inPixels(bv));
3200
3201         LyXFont font;
3202         font.decSize();
3203         int const min_size = max(3 * arrow_size,
3204                                       font_metrics::maxAscent(font)
3205                                       + font_metrics::maxDescent(font));
3206
3207         if (vsp.length().len().value() < 0.0)
3208                 return min_size;
3209         else
3210                 return max(min_size, space_size);
3211 }
3212
3213
3214 int LyXText::drawLengthMarker(DrawRowParams & p, string const & prefix,
3215                               VSpace const & vsp, int start)
3216 {
3217         if (vsp.kind() == VSpace::NONE)
3218                 return 0;
3219
3220         int const arrow_size = 4;
3221         int const size = getLengthMarkerHeight(p.bv, vsp);
3222         int const end = start + size;
3223
3224         // the label to display (if any)
3225         string str;
3226         // y-values for top arrow
3227         int ty1, ty2;
3228         // y-values for bottom arrow
3229         int by1, by2;
3230
3231         str = prefix + " (" + vsp.asLyXCommand() + ")";
3232
3233         if (vsp.kind() == VSpace::VFILL ) {
3234                 ty1 = ty2 = start;
3235                 by1 = by2 = end;
3236         } else {
3237                 // adding or removing space
3238                 bool const added = vsp.kind() != VSpace::LENGTH ||
3239                                    vsp.length().len().value() > 0.0;
3240                 ty1 = added ? (start + arrow_size) : start;
3241                 ty2 = added ? start : (start + arrow_size);
3242                 by1 = added ? (end - arrow_size) : end;
3243                 by2 = added ? end : (end - arrow_size);
3244         }
3245
3246         int const leftx = p.xo + leftMargin(p.bv, p.row);
3247         int const midx = leftx + arrow_size;
3248         int const rightx = midx + arrow_size;
3249
3250         // first the string
3251         int w = 0;
3252         int a = 0;
3253         int d = 0;
3254
3255         LyXFont font;
3256         font.setColor(LColor::added_space).decSize().decSize();
3257         font_metrics::rectText(str, font, w, a, d);
3258
3259         p.pain->rectText(leftx + 2 * arrow_size + 5,
3260                          start + ((end - start) / 2) + d,
3261                          str, font);
3262
3263         // top arrow
3264         p.pain->line(leftx, ty1, midx, ty2, LColor::added_space);
3265         p.pain->line(midx, ty2, rightx, ty1, LColor::added_space);
3266
3267         // bottom arrow
3268         p.pain->line(leftx, by1, midx, by2, LColor::added_space);
3269         p.pain->line(midx, by2, rightx, by1, LColor::added_space);
3270
3271         // joining line
3272         p.pain->line(midx, ty2, midx, by2, LColor::added_space);
3273
3274         return size;
3275 }
3276
3277
3278 int LyXText::paintPageBreak(string const & label, int y, DrawRowParams & p)
3279 {
3280         LyXFont pb_font;
3281         pb_font.setColor(LColor::pagebreak).decSize();
3282
3283         int w = 0;
3284         int a = 0;
3285         int d = 0;
3286         font_metrics::rectText(label, pb_font, w, a, d);
3287
3288         int const text_start = p.xo + ((p.width - w) / 2);
3289         int const text_end = text_start + w;
3290
3291         p.pain->rectText(text_start, y + d, label, pb_font);
3292
3293         p.pain->line(p.xo, y, text_start, y,
3294                 LColor::pagebreak, Painter::line_onoffdash);
3295         p.pain->line(text_end, y, p.xo + p.width, y,
3296                 LColor::pagebreak, Painter::line_onoffdash);
3297
3298         return 3 * defaultRowHeight();
3299 }
3300
3301
3302 void LyXText::paintFirstRow(DrawRowParams & p)
3303 {
3304         Paragraph * par = p.row->par();
3305         ParagraphParameters const & parparams = par->params();
3306
3307         // start of appendix?
3308         if (parparams.startOfAppendix()) {
3309                 p.pain->line(1, p.yo, p.width - 2, p.yo, LColor::appendixline);
3310         }
3311
3312         int y_top = 0;
3313
3314         // the top margin
3315         if (!p.row->previous() && isTopLevel())
3316                 y_top += PAPER_MARGIN;
3317
3318         // draw a top pagebreak
3319         if (parparams.pagebreakTop()) {
3320                 y_top += paintPageBreak(_("Page Break (top)"),
3321                         p.yo + y_top + 2 * defaultRowHeight(), p);
3322         }
3323
3324         // draw the additional space if needed:
3325         y_top += drawLengthMarker(p, _("Space above"),
3326                                   parparams.spaceTop(), p.yo + y_top);
3327
3328         Buffer const * buffer = p.bv->buffer();
3329
3330         LyXLayout_ptr const & layout = par->layout();
3331
3332         // think about the parskip
3333         // some parskips VERY EASY IMPLEMENTATION
3334         if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3335                 if (par->previous()) {
3336                         if (layout->latextype == LATEX_PARAGRAPH
3337                                 && !par->getDepth()) {
3338                                 y_top += buffer->params.getDefSkip().inPixels(p.bv);
3339                         } else {
3340                                 LyXLayout_ptr const & playout =
3341                                         par->previous()->layout();
3342                                 if (playout->latextype == LATEX_PARAGRAPH
3343                                         && !par->previous()->getDepth()) {
3344                                         // is it right to use defskip here, too? (AS)
3345                                         y_top += buffer->params.getDefSkip().inPixels(p.bv);
3346                                 }
3347                         }
3348                 }
3349         }
3350
3351         int const ww = p.bv->workWidth();
3352
3353         // draw a top line
3354         if (parparams.lineTop()) {
3355                 LyXFont font(LyXFont::ALL_SANE);
3356                 int const asc = font_metrics::ascent('x', getFont(buffer, par, 0));
3357
3358                 y_top += asc;
3359
3360                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3361                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3362                 p.pain->line(xp, p.yo + y_top, xp + w, p.yo + y_top,
3363                         LColor::topline, Painter::line_solid,
3364                         Painter::line_thick);
3365
3366                 y_top += asc;
3367         }
3368
3369         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3370
3371         // should we print a label?
3372         if (layout->labeltype >= LABEL_STATIC
3373             && (layout->labeltype != LABEL_STATIC
3374                 || layout->latextype != LATEX_ENVIRONMENT
3375                 || par->isFirstInSequence())) {
3376
3377                 LyXFont font = getLabelFont(buffer, par);
3378                 if (!par->getLabelstring().empty()) {
3379                         float x = p.x;
3380                         string const str = par->getLabelstring();
3381
3382                         // this is special code for the chapter layout. This is
3383                         // printed in an extra row and has a pagebreak at
3384                         // the top.
3385                         if (layout->labeltype == LABEL_COUNTER_CHAPTER) {
3386                                 if (buffer->params.secnumdepth >= 0) {
3387                                         float spacing_val = 1.0;
3388                                         if (!parparams.spacing().isDefault()) {
3389                                                 spacing_val = parparams.spacing().getValue();
3390                                         } else {
3391                                                 spacing_val = buffer->params.spacing.getValue();
3392                                         }
3393
3394                                         int const maxdesc =
3395                                                 int(font_metrics::maxDescent(font) * layout->spacing.getValue() * spacing_val)
3396                                                 + int(layout->parsep) * defaultRowHeight();
3397
3398                                         if (is_rtl) {
3399                                                 x = ww - leftMargin(p.bv, p.row) -
3400                                                         font_metrics::width(str, font);
3401                                         }
3402
3403                                         p.pain->text(int(x),
3404                                                 p.yo + p.row->baseline() -
3405                                                 p.row->ascent_of_text() - maxdesc,
3406                                                 str, font);
3407                                 }
3408                         } else {
3409                                 if (is_rtl) {
3410                                         x = ww - leftMargin(p.bv, p.row)
3411                                                 + font_metrics::width(layout->labelsep, font);
3412                                 } else {
3413                                         x = p.x - font_metrics::width(layout->labelsep, font)
3414                                                 - font_metrics::width(str, font);
3415                                 }
3416
3417                                 p.pain->text(int(x), p.yo + p.row->baseline(), str, font);
3418                         }
3419                 }
3420         // the labels at the top of an environment.
3421         // More or less for bibliography
3422         } else if (par->isFirstInSequence() &&
3423                 (layout->labeltype == LABEL_TOP_ENVIRONMENT ||
3424                 layout->labeltype == LABEL_BIBLIO ||
3425                 layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
3426                 LyXFont font = getLabelFont(buffer, par);
3427                 if (!par->getLabelstring().empty()) {
3428                         string const str = par->getLabelstring();
3429                         float spacing_val = 1.0;
3430                         if (!parparams.spacing().isDefault()) {
3431                                 spacing_val = parparams.spacing().getValue();
3432                         } else {
3433                                 spacing_val = buffer->params.spacing.getValue();
3434                         }
3435
3436                         int maxdesc =
3437                                 int(font_metrics::maxDescent(font) * layout->spacing.getValue() * spacing_val
3438                                 + (layout->labelbottomsep * defaultRowHeight()));
3439
3440                         float x = p.x;
3441                         if (layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3442                                 x = ((is_rtl ? leftMargin(p.bv, p.row) : p.x)
3443                                          + ww - rightMargin(buffer, p.row)) / 2;
3444                                 x -= font_metrics::width(str, font) / 2;
3445                         } else if (is_rtl) {
3446                                 x = ww - leftMargin(p.bv, p.row) -
3447                                         font_metrics::width(str, font);
3448                         }
3449                         p.pain->text(int(x), p.yo + p.row->baseline()
3450                                   - p.row->ascent_of_text() - maxdesc,
3451                                   str, font);
3452                 }
3453         }
3454 }
3455
3456
3457 void LyXText::paintLastRow(DrawRowParams & p)
3458 {
3459         Paragraph * par = p.row->par();
3460         ParagraphParameters const & parparams = par->params();
3461         int y_bottom = p.row->height() - 1;
3462
3463         // the bottom margin
3464         if (!p.row->next() && isTopLevel())
3465                 y_bottom -= PAPER_MARGIN;
3466
3467         int const ww = p.bv->workWidth();
3468
3469         // draw a bottom pagebreak
3470         if (parparams.pagebreakBottom()) {
3471                 y_bottom -= paintPageBreak(_("Page Break (bottom)"),
3472                         p.yo + y_bottom - 2 * defaultRowHeight(), p);
3473         }
3474
3475         // draw the additional space if needed:
3476         int const height =  getLengthMarkerHeight(p.bv,
3477                                                   parparams.spaceBottom());
3478         y_bottom -= drawLengthMarker(p, _("Space below"),
3479                                      parparams.spaceBottom(),
3480                                      p.yo + y_bottom - height);
3481
3482         Buffer const * buffer = p.bv->buffer();
3483
3484         // draw a bottom line
3485         if (parparams.lineBottom()) {
3486                 LyXFont font(LyXFont::ALL_SANE);
3487                 int const asc = font_metrics::ascent('x',
3488                         getFont(buffer, par,
3489                         max(pos_type(0), par->size() - 1)));
3490
3491                 y_bottom -= asc;
3492
3493                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3494                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3495                 int const y = p.yo + y_bottom;
3496                 p.pain->line(xp, y, xp + w, y, LColor::topline, Painter::line_solid,
3497                           Painter::line_thick);
3498
3499                 y_bottom -= asc;
3500         }
3501
3502         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3503         int const endlabel = par->getEndLabel();
3504
3505         // draw an endlabel
3506         switch (endlabel) {
3507         case END_LABEL_BOX:
3508         case END_LABEL_FILLED_BOX:
3509         {
3510                 LyXFont const font = getLabelFont(buffer, par);
3511                 int const size = int(0.75 * font_metrics::maxAscent(font));
3512                 int const y = (p.yo + p.row->baseline()) - size;
3513                 int x = is_rtl ? LEFT_MARGIN : ww - PAPER_MARGIN - size;
3514
3515                 if (p.row->fill() <= size)
3516                         x += (size - p.row->fill() + 1) * (is_rtl ? -1 : 1);
3517
3518                 if (endlabel == END_LABEL_BOX) {
3519                         p.pain->rectangle(x, y, size, size, LColor::eolmarker);
3520                 } else {
3521                         p.pain->fillRectangle(x, y, size, size,
3522                                               LColor::eolmarker);
3523                 }
3524                 break;
3525         }
3526         case END_LABEL_STATIC:
3527         {
3528 #if 0
3529                 LyXFont font(LyXFont::ALL_SANE);
3530                 font = getLabelFont(buffer, par);
3531 #else
3532                 LyXFont font = getLabelFont(buffer, par);
3533 #endif
3534                 string const & str = par->layout()->endlabelstring();
3535                 int const x = is_rtl ?
3536                         int(p.x) - font_metrics::width(str, font)
3537                         : ww - rightMargin(buffer, p.row) - p.row->fill();
3538                 p.pain->text(x, p.yo + p.row->baseline(), str, font);
3539                 break;
3540         }
3541         case END_LABEL_NO_LABEL:
3542                 break;
3543         }
3544 }
3545
3546
3547 void LyXText::paintRowText(DrawRowParams & p)
3548 {
3549         Paragraph * par = p.row->par();
3550         Buffer const * buffer = p.bv->buffer();
3551
3552         pos_type const last = p.row->lastPrintablePos();
3553         pos_type main_body = par->beginningOfMainBody();
3554         if (main_body > 0 &&
3555                 (main_body - 1 > last ||
3556                 !par->isLineSeparator(main_body - 1))) {
3557                 main_body = 0;
3558         }
3559
3560         LyXLayout_ptr const & layout = par->layout();
3561
3562         bool running_strikeout = false;
3563         bool is_struckout = false;
3564         float last_strikeout_x = 0.0;
3565  
3566         pos_type vpos = p.row->pos();
3567         while (vpos <= last) {
3568                 if (p.x > p.bv->workWidth())
3569                         break;
3570                 pos_type pos = vis2log(vpos);
3571  
3572                 if (p.x + singleWidth(p.bv, par, pos) < 0) {
3573                         p.x += singleWidth(p.bv, par, pos);
3574                         ++vpos;
3575                         continue;
3576                 }
3577  
3578                 is_struckout = isDeletedText(par, pos);
3579
3580                 if (is_struckout && !running_strikeout) {
3581                         running_strikeout = true;
3582                         last_strikeout_x = p.x;
3583                 }
3584  
3585                 bool const highly_editable_inset = par->isInset(pos)
3586                         && isHighlyEditableInset(par->getInset(pos));
3587
3588                 // if we reach the end of a struck out range, paint it
3589                 // we also don't paint across things like tables
3590                 if (running_strikeout && (highly_editable_inset || !is_struckout)) {
3591                         int const middle = p.yo + p.row->top_of_text()
3592                                 + ((p.row->baseline() - p.row->top_of_text()) / 2);
3593                         p.pain->line(int(last_strikeout_x), middle, int(p.x), middle,
3594                                 LColor::strikeout, Painter::line_solid, Painter::line_thin);
3595                         running_strikeout = false;
3596                 }
3597  
3598                 if (main_body > 0 && pos == main_body - 1) {
3599                         int const lwidth = font_metrics::width(layout->labelsep,
3600                                 getLabelFont(buffer, par));
3601
3602                         p.x += p.label_hfill + lwidth
3603                                 - singleWidth(p.bv, par, main_body - 1);
3604                 }
3605
3606                 if (par->isHfill(pos)) {
3607                         p.x += 1;
3608
3609                         int const y0 = p.yo + p.row->baseline();
3610                         int const y1 = y0 - defaultRowHeight() / 2;
3611
3612                         p.pain->line(int(p.x), y1, int(p.x), y0,
3613                                      LColor::added_space);
3614
3615                         if (p.row->hfillExpansion(pos)) {
3616                                 int const y2 = (y0 + y1) / 2;
3617
3618                                 if (pos >= main_body) {
3619                                         p.pain->line(int(p.x), y2,
3620                                                   int(p.x + p.hfill), y2,
3621                                                   LColor::added_space,
3622                                                   Painter::line_onoffdash);
3623                                         p.x += p.hfill;
3624                                 } else {
3625                                         p.pain->line(int(p.x), y2,
3626                                                   int(p.x + p.label_hfill), y2,
3627                                                   LColor::added_space,
3628                                                   Painter::line_onoffdash);
3629                                         p.x += p.label_hfill;
3630                                 }
3631                                 p.pain->line(int(p.x), y1,
3632                                              int(p.x), y0,
3633                                              LColor::added_space);
3634                         }
3635                         p.x += 2;
3636                         ++vpos;
3637                 } else if (par->isSeparator(pos)) {
3638                         p.x += singleWidth(p.bv, par, pos);
3639                         if (pos >= main_body)
3640                                 p.x += p.separator;
3641                         ++vpos;
3642                 } else {
3643                         if (!draw(p, vpos))
3644                                 break;
3645                 }
3646         }
3647  
3648         // if we reach the end of a struck out range, paint it
3649         if (running_strikeout) {
3650                 int const middle = p.yo + p.row->top_of_text()
3651                         + ((p.row->baseline() - p.row->top_of_text()) / 2);
3652                 p.pain->line(int(last_strikeout_x), middle, int(p.x), middle,
3653                         LColor::strikeout, Painter::line_solid, Painter::line_thin);
3654                 running_strikeout = false;
3655         }
3656 }
3657
3658
3659 void LyXText::getVisibleRow(BufferView * bv, int y_offset, int x_offset,
3660                             Row * row, int y, bool cleared)
3661 {
3662         if (row->height() <= 0) {
3663                 lyxerr << "LYX_ERROR: row.height: "
3664                        << row->height() << endl;
3665                 return;
3666         }
3667
3668         DrawRowParams p;
3669
3670         // set up drawing parameters
3671         p.bv = bv;
3672         p.pain = &bv->painter();
3673         p.row = row;
3674         p.xo = x_offset;
3675         p.yo = y_offset;
3676         prepareToPrint(bv, row, p.x, p.separator, p.hfill, p.label_hfill);
3677         if (inset_owner && (p.x < 0))
3678                 p.x = 0;
3679         p.x += p.xo;
3680         p.y = y;
3681         p.width = inset_owner ? inset_owner->textWidth(bv, true) : bv->workWidth();
3682         p.cleared = cleared;
3683
3684         // start painting
3685
3686         // clear to background if necessary
3687         p.cleared = paintRowBackground(p);
3688
3689         // paint the selection background
3690         if (selection.set()) {
3691                 paintRowSelection(p);
3692         }
3693
3694         // vertical lines for appendix
3695         paintRowAppendix(p);
3696
3697         // environment depth brackets
3698         paintRowDepthBar(p);
3699
3700         // changebar
3701         paintChangeBar(p);
3702  
3703         // draw any stuff wanted for a first row of a paragraph
3704         if (!row->pos()) {
3705                 paintFirstRow(p);
3706         }
3707
3708         // draw any stuff wanted for the last row of a paragraph
3709         if (!row->next() || (row->next()->par() != row->par())) {
3710                 paintLastRow(p);
3711         }
3712
3713         // paint text
3714         paintRowText(p);
3715 }
3716
3717
3718 // returns the column near the specified x-coordinate of the row
3719 // x is set to the real beginning of this column
3720 pos_type
3721 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3722                         bool & boundary) const
3723 {
3724         float tmpx = 0.0;
3725         float fill_separator;
3726         float fill_hfill;
3727         float fill_label_hfill;
3728
3729         prepareToPrint(bview, row, tmpx, fill_separator,
3730                        fill_hfill, fill_label_hfill);
3731
3732         pos_type vc = row->pos();
3733         pos_type last = row->lastPrintablePos();
3734         pos_type c = 0;
3735
3736         LyXLayout_ptr const & layout = row->par()->layout();
3737
3738         bool left_side = false;
3739
3740         pos_type main_body = row->par()->beginningOfMainBody();
3741         float last_tmpx = tmpx;
3742
3743         if (main_body > 0 &&
3744             (main_body - 1 > last ||
3745              !row->par()->isLineSeparator(main_body - 1)))
3746                 main_body = 0;
3747
3748         // check for empty row
3749         if (!row->par()->size()) {
3750                 x = int(tmpx);
3751                 return 0;
3752         }
3753  
3754         while (vc <= last && tmpx <= x) {
3755                 c = vis2log(vc);
3756                 last_tmpx = tmpx;
3757                 if (main_body > 0 && c == main_body-1) {
3758                         tmpx += fill_label_hfill +
3759                                 font_metrics::width(layout->labelsep,
3760                                                getLabelFont(bview->buffer(), row->par()));
3761                         if (row->par()->isLineSeparator(main_body - 1))
3762                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3763                 }
3764
3765                 if (row->hfillExpansion(c)) {
3766                         tmpx += singleWidth(bview, row->par(), c);
3767                         if (c >= main_body)
3768                                 tmpx += fill_hfill;
3769                         else
3770                                 tmpx += fill_label_hfill;
3771                 } else if (row->par()->isSeparator(c)) {
3772                         tmpx += singleWidth(bview, row->par(), c);
3773                         if (c >= main_body)
3774                                 tmpx+= fill_separator;
3775                 } else {
3776                         tmpx += singleWidth(bview, row->par(), c);
3777                 }
3778                 ++vc;
3779         }
3780
3781         if ((tmpx + last_tmpx) / 2 > x) {
3782                 tmpx = last_tmpx;
3783                 left_side = true;
3784         }
3785
3786         if (vc > last + 1)  // This shouldn't happen.
3787                 vc = last + 1;
3788
3789         boundary = false;
3790         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3791                                          // some speedup if rtl_support=false
3792                 && (!row->next() || row->next()->par() != row->par());
3793         bool const rtl = (lastrow)
3794                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3795                 : false; // If lastrow is false, we don't need to compute
3796                          // the value of rtl.
3797
3798         if (lastrow &&
3799                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3800                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
3801                 c = last + 1;
3802         else if (vc == row->pos()) {
3803                 c = vis2log(vc);
3804                 if (bidi_level(c) % 2 == 1)
3805                         ++c;
3806         } else {
3807                 c = vis2log(vc - 1);
3808                 bool const rtl = (bidi_level(c) % 2 == 1);
3809                 if (left_side == rtl) {
3810                         ++c;
3811                         boundary = isBoundary(bview->buffer(), row->par(), c);
3812                 }
3813         }
3814
3815         if (row->pos() <= last && c > last
3816             && row->par()->isNewline(last)) {
3817                 if (bidi_level(last) % 2 == 0)
3818                         tmpx -= singleWidth(bview, row->par(), last);
3819                 else
3820                         tmpx += singleWidth(bview, row->par(), last);
3821                 c = last;
3822         }
3823
3824         c -= row->pos();
3825         x = int(tmpx);
3826         return c;
3827 }
3828
3829
3830 // returns pointer to a specified row
3831 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
3832 {
3833         if (!firstrow)
3834                 return 0;
3835
3836         Row * tmprow = firstrow;
3837         y = 0;
3838
3839         // find the first row of the specified paragraph
3840         while (tmprow->next() && tmprow->par() != par) {
3841                 y += tmprow->height();
3842                 tmprow = tmprow->next();
3843         }
3844
3845         // now find the wanted row
3846         while (tmprow->pos() < pos
3847                && tmprow->next()
3848                && tmprow->next()->par() == par
3849                && tmprow->next()->pos() <= pos) {
3850                 y += tmprow->height();
3851                 tmprow = tmprow->next();
3852         }
3853
3854         return tmprow;
3855 }
3856
3857
3858 Row * LyXText::getRowNearY(int & y) const
3859 {
3860 #if 1
3861         // If possible we should optimize this method. (Lgb)
3862         Row * tmprow = firstrow;
3863         int tmpy = 0;
3864
3865         while (tmprow->next() && tmpy + tmprow->height() <= y) {
3866                 tmpy += tmprow->height();
3867                 tmprow = tmprow->next();
3868         }
3869
3870         y = tmpy;   // return the real y
3871
3872         //lyxerr << "returned y = " << y << endl;
3873
3874         return tmprow;
3875 #else
3876         // Search from the current cursor position.
3877
3878         Row * tmprow = cursor.row();
3879         int tmpy = cursor.y() - tmprow->baseline();
3880
3881         lyxerr << "cursor.y() = " << tmpy << endl;
3882         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
3883         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
3884         lyxerr << "first = " << first << endl;
3885         lyxerr << "y = " << y << endl;
3886
3887         if (y < tmpy) {
3888                 lyxerr << "up" << endl;
3889                 do {
3890                         tmpy -= tmprow->height();
3891                         tmprow = tmprow->previous();
3892                 } while (tmprow && tmpy - tmprow->height() >= y);
3893         } else if (y > tmpy) {
3894                 lyxerr << "down" << endl;
3895
3896                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
3897                         tmpy += tmprow->height();
3898                         tmprow = tmprow->next();
3899                 }
3900         } else {
3901                 lyxerr << "equal" << endl;
3902         }
3903
3904         y = tmpy; // return the real y
3905
3906         lyxerr << "returned y = " << y << endl;
3907
3908         return tmprow;
3909
3910 #endif
3911 }
3912
3913
3914 int LyXText::getDepth() const
3915 {
3916         return cursor.par()->getDepth();
3917 }