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