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