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