]> git.lyx.org Git - lyx.git/blob - src/text.C
white space changes
[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                 // Because of the representation as vertical lines 
219                 return 3;
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                 // just the beginning of the main body 
955                 return leftMargin(bview, &tmprow);
956         } else {
957                 // LabelEnd is only needed,
958                 // if the layout fills a flushleft label. 
959                 return 0; 
960         }
961 }
962
963
964 // get the next breakpoint in a given paragraph
965 pos_type
966 LyXText::nextBreakPoint(BufferView * bview, Row const * row, int width) const
967 {
968         Paragraph * par = row->par();
969
970         if (width < 0)
971                 return par->size();
972
973         pos_type const pos = row->pos();
974
975         // position of the last possible breakpoint
976         // -1 isn't a suitable value, but a flag
977         pos_type last_separator = -1;
978         width -= rightMargin(bview->buffer(), row);
979
980         pos_type const main_body =
981                 beginningOfMainBody(bview->buffer(), par);
982         LyXLayout const & layout =
983                 textclasslist[bview->buffer()->params.textclass][par->layout()];
984         pos_type i = pos;
985
986         if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
987                 // special code for right address boxes, only newlines count
988                 while (i < par->size()) {
989                         if (par->isNewline(i)) {
990                                 last_separator = i;
991                                 i = par->size() - 1; // this means break
992                                 //x = width;
993                         } else if (par->isInset(i) && par->getInset(i)
994                                 && par->getInset(i)->display()) {
995                                 par->getInset(i)->display(false);
996                         }
997                         ++i;
998                 }
999         } else {
1000                 // Last position is an invariant
1001                 pos_type const last =
1002                         par->size();
1003                 // this is the usual handling
1004                 int x = leftMargin(bview, row);
1005                 bool doitonetime = true;
1006                 while (doitonetime || ((x < width) && (i < last))) {
1007                         doitonetime = false;
1008                         char const c = par->getChar(i);
1009                         Inset * in = 0;
1010                         if (c == Paragraph::META_INSET)
1011                                 in = par->getInset(i);
1012                         if (IsNewlineChar(c)) {
1013                                 last_separator = i;
1014                                 x = width; // this means break
1015                         } else if (in && !in->isChar()) {
1016                                 // check wether a Display() inset is
1017                                 // valid here. if not, change it to
1018                                 // non-display
1019                                 if (in->display() &&
1020                                     (layout.isCommand() ||
1021                                      (layout.labeltype == LABEL_MANUAL
1022                                       && i < beginningOfMainBody(bview->buffer(), par))))
1023                                 {
1024                                         // display istn't allowd
1025                                         in->display(false);
1026                                         x += singleWidth(bview, par, i, c);
1027                                 } else if (in->display() || in->needFullRow()) {
1028                                         // So break the line here
1029                                         if (i == pos) {
1030                                                 if (pos < last-1) {
1031                                                         last_separator = i;
1032                                                         if (par->isLineSeparator(i+1))
1033                                                                 ++last_separator;
1034                                                 } else
1035                                                         last_separator = last; // to avoid extra rows
1036                                         } else
1037                                                 last_separator = i - 1;
1038                                         x = width;  // this means break
1039                                 } else {
1040                                         x += singleWidth(bview, par, i, c);
1041                                         // we have to check this separately as we could have a
1042                                         // lineseparator and then the algorithm below would prefer
1043                                         // that which IS wrong! We should always break on an inset
1044                                         // if it's too long and not on the last separator.
1045                                         // Maybe the only exeption is insets used as chars but
1046                                         // then we would have to have a special function inside
1047                                         // the inset to tell us this. Till then we leave it as
1048                                         // it is now. (Jug 20020106)
1049                                         if (pos < i && x >= width && last_separator >= 0)
1050                                                 last_separator = i - 1;
1051                                 }
1052                         } else  {
1053                                 if (par->isLineSeparator(i))
1054                                         last_separator = i;
1055                                 x += singleWidth(bview, par, i, c);
1056                         }
1057                         ++i;
1058                         if (i == main_body) {
1059                                 x += font_metrics::width(layout.labelsep,
1060                                                     getLabelFont(bview->buffer(), par));
1061                                 if (par->isLineSeparator(i - 1))
1062                                         x-= singleWidth(bview, par, i - 1);
1063                                 int left_margin = labelEnd(bview, row);
1064                                 if (x < left_margin)
1065                                         x = left_margin;
1066                         }
1067                 }
1068                 if ((pos+1 < i) && (last_separator < 0) && (x >= width))
1069                         last_separator = i - 2;
1070                 else if ((pos < i) && (last_separator < 0) && (x >= width))
1071                         last_separator = i - 1;
1072                 // end of paragraph is always a suitable separator
1073                 else if (i == last && x < width)
1074                         last_separator = i;
1075         }
1076
1077         // well, if last_separator is still 0, the line isn't breakable.
1078         // don't care and cut simply at the end
1079         if (last_separator < 0) {
1080                 last_separator = i;
1081         }
1082
1083         // manual labels cannot be broken in LaTeX, do not care
1084         if (main_body && last_separator < main_body)
1085                 last_separator = main_body - 1;
1086
1087         return last_separator;
1088 }
1089
1090
1091 // returns the minimum space a row needs on the screen in pixel
1092 int LyXText::fill(BufferView * bview, Row * row, int paper_width) const
1093 {
1094         if (paper_width < 0)
1095                 return 0;
1096
1097         int w;
1098         // get the pure distance
1099         pos_type const last = rowLastPrintable(row);
1100
1101         // special handling of the right address boxes
1102         if (textclasslist[bview->buffer()->params.textclass][row->par()->layout()].margintype
1103             == MARGIN_RIGHT_ADDRESS_BOX)
1104         {
1105                 int const tmpfill = row->fill();
1106                 row->fill(0); // the minfill in MarginLeft()
1107                 w = leftMargin(bview, row);
1108                 row->fill(tmpfill);
1109         } else
1110                 w = leftMargin(bview, row);
1111
1112         LyXLayout const & layout = textclasslist[bview->buffer()->params.textclass][row->par()->layout()];
1113         pos_type const main_body =
1114                 beginningOfMainBody(bview->buffer(), row->par());
1115         pos_type i = row->pos();
1116
1117         while (i <= last) {
1118                 if (main_body > 0 && i == main_body) {
1119                         w += font_metrics::width(layout.labelsep, getLabelFont(bview->buffer(), row->par()));
1120                         if (row->par()->isLineSeparator(i - 1))
1121                                 w -= singleWidth(bview, row->par(), i - 1);
1122                         int left_margin = labelEnd(bview, row);
1123                         if (w < left_margin)
1124                                 w = left_margin;
1125                 }
1126                 w += singleWidth(bview, row->par(), i);
1127                 ++i;
1128         }
1129         if (main_body > 0 && main_body > last) {
1130                 w += font_metrics::width(layout.labelsep, getLabelFont(bview->buffer(), row->par()));
1131                 if (last >= 0 && row->par()->isLineSeparator(last))
1132                         w -= singleWidth(bview, row->par(), last);
1133                 int const left_margin = labelEnd(bview, row);
1134                 if (w < left_margin)
1135                         w = left_margin;
1136         }
1137
1138         int const fill = paper_width - w - rightMargin(bview->buffer(), row);
1139         return fill;
1140 }
1141
1142
1143 // returns the minimum space a manual label needs on the screen in pixel
1144 int LyXText::labelFill(BufferView * bview, Row const * row) const
1145 {
1146         pos_type last = beginningOfMainBody(bview->buffer(), row->par()) - 1;
1147         // -1 because a label ends either with a space that is in the label,
1148         // or with the beginning of a footnote that is outside the label.
1149
1150         // I don't understand this code in depth, but sometimes "last" is
1151         // less than 0 and this causes a crash. This fix seems to work
1152         // correctly, but I bet the real error is elsewhere.  The bug is
1153         // triggered when you have an open footnote in a paragraph
1154         // environment with a manual label. (Asger)
1155         if (last < 0) last = 0;
1156
1157         // a separator at this end does not count
1158         if (row->par()->isLineSeparator(last))
1159                 --last;
1160
1161         int w = 0;
1162         pos_type i = row->pos();
1163         while (i <= last) {
1164                 w += singleWidth(bview, row->par(), i);
1165                 ++i;
1166         }
1167
1168         int fill = 0;
1169         if (!row->par()->params().labelWidthString().empty()) {
1170                 fill = max(font_metrics::width(row->par()->params().labelWidthString(),
1171                                           getLabelFont(bview->buffer(), row->par())) - w,
1172                            0);
1173         }
1174
1175         return fill;
1176 }
1177
1178
1179 // returns the number of separators in the specified row. The separator
1180 // on the very last column doesnt count
1181 int LyXText::numberOfSeparators(Buffer const * buf, Row const * row) const
1182 {
1183         pos_type last = rowLastPrintable(row);
1184         pos_type p = max(row->pos(), beginningOfMainBody(buf, row->par()));
1185
1186         int n = 0;
1187         for (; p <= last; ++p) {
1188                 if (row->par()->isSeparator(p)) {
1189                         ++n;
1190                 }
1191         }
1192         return n;
1193 }
1194
1195
1196 // returns the number of hfills in the specified row. The LyX-Hfill is
1197 // a LaTeX \hfill so that the hfills at the beginning and at the end were
1198 // ignored. This is *MUCH* more usefull than not to ignore!
1199 int LyXText::numberOfHfills(Buffer const * buf, Row const * row) const
1200 {
1201         pos_type const last = rowLast(row);
1202         pos_type first = row->pos();
1203
1204         if (first) {
1205                 // hfill *DO* count at the beginning of paragraphs!
1206                 while (first <= last && row->par()->isHfill(first)) {
1207                         ++first;
1208                 }
1209         }
1210
1211         first = max(first, beginningOfMainBody(buf, row->par()));
1212         int n = 0;
1213         for (pos_type p = first; p <= last; ++p) {
1214                 // last, because the end is ignored!
1215
1216                 if (row->par()->isHfill(p)) {
1217                         ++n;
1218                 }
1219         }
1220         return n;
1221 }
1222
1223
1224 // like NumberOfHfills, but only those in the manual label!
1225 int LyXText::numberOfLabelHfills(Buffer const * buf, Row const * row) const
1226 {
1227         pos_type last = rowLast(row);
1228         pos_type first = row->pos();
1229         if (first) {
1230                 // hfill *DO* count at the beginning of paragraphs!
1231                 while (first < last && row->par()->isHfill(first))
1232                         ++first;
1233         }
1234
1235         last = min(last, beginningOfMainBody(buf, row->par()));
1236         int n = 0;
1237         for (pos_type p = first; p < last; ++p) {
1238                 // last, because the end is ignored!
1239                 if (row->par()->isHfill(p)) {
1240                         ++n;
1241                 }
1242         }
1243         return n;
1244 }
1245
1246
1247 // returns true, if a expansion is needed.
1248 // Rules are given by LaTeX
1249 bool LyXText::hfillExpansion(Buffer const * buf, Row const * row_ptr,
1250                              pos_type pos) const
1251 {
1252         // by the way, is it a hfill?
1253         if (!row_ptr->par()->isHfill(pos))
1254                 return false;
1255
1256         // at the end of a row it does not count
1257         // unless another hfill exists on the line
1258         if (pos >= rowLast(row_ptr)) {
1259                 pos_type i = row_ptr->pos();
1260                 while (i < pos && !row_ptr->par()->isHfill(i)) {
1261                         ++i;
1262                 }
1263                 if (i == pos) {
1264                         return false;
1265                 }
1266         }
1267
1268         // at the beginning of a row it does not count, if it is not
1269         // the first row of a paragaph
1270         if (!row_ptr->pos())
1271                 return true;
1272
1273         // in some labels  it does not count
1274         if (textclasslist[buf->params.textclass][row_ptr->par()->layout()].margintype
1275             != MARGIN_MANUAL
1276             && pos < beginningOfMainBody(buf, row_ptr->par()))
1277                 return false;
1278
1279         // if there is anything between the first char of the row and
1280         // the sepcified position that is not a newline and not a hfill,
1281         // the hfill will count, otherwise not
1282         pos_type i = row_ptr->pos();
1283         while (i < pos && (row_ptr->par()->isNewline(i)
1284                            || row_ptr->par()->isHfill(i)))
1285                 ++i;
1286
1287         return i != pos;
1288 }
1289
1290
1291 LColor::color LyXText::backgroundColor()
1292 {
1293         if (inset_owner)
1294                 return inset_owner->backgroundColor();
1295         else
1296                 return LColor::background;
1297 }
1298
1299 void LyXText::setHeightOfRow(BufferView * bview, Row * row_ptr) const
1300 {
1301         // get the maximum ascent and the maximum descent
1302         int asc = 0;
1303         int desc = 0;
1304         float layoutasc = 0;
1305         float layoutdesc = 0;
1306         float tmptop = 0;
1307         LyXFont tmpfont;
1308         Inset * tmpinset = 0;
1309
1310         // ok , let us initialize the maxasc and maxdesc value.
1311         // This depends in LaTeX of the font of the last character
1312         // in the paragraph. The hack below is necessary because
1313         // of the possibility of open footnotes 
1314
1315         // Correction: only the fontsize count. The other properties
1316         //  are taken from the layoutfont. Nicer on the screen :) 
1317         Paragraph * par = row_ptr->par();
1318         Paragraph * firstpar = row_ptr->par();
1319
1320         LyXLayout const & layout
1321                 = textclasslist[bview->buffer()->params.textclass][firstpar->layout()];
1322
1323         // as max get the first character of this row then it can increes but not
1324         // decrees the height. Just some point to start with so we don't have to
1325         // do the assignment below too often.
1326         LyXFont font = getFont(bview->buffer(), par, row_ptr->pos());
1327         LyXFont::FONT_SIZE const tmpsize = font.size();
1328         font = getLayoutFont(bview->buffer(), par);
1329         LyXFont::FONT_SIZE const size = font.size();
1330         font.setSize(tmpsize);
1331
1332         LyXFont labelfont = getLabelFont(bview->buffer(), par);
1333
1334         float spacing_val = 1.0;
1335         if (!row_ptr->par()->params().spacing().isDefault()) {
1336                 spacing_val = row_ptr->par()->params().spacing().getValue();
1337         } else {
1338                 spacing_val = bview->buffer()->params.spacing.getValue();
1339         }
1340         //lyxerr << "spacing_val = " << spacing_val << endl;
1341
1342         int maxasc = int(font_metrics::maxAscent(font) *
1343                          layout.spacing.getValue() *
1344                          spacing_val);
1345         int maxdesc = int(font_metrics::maxDescent(font) *
1346                           layout.spacing.getValue() *
1347                           spacing_val);
1348
1349         pos_type const pos_end = rowLast(row_ptr);
1350         int labeladdon = 0;
1351         int maxwidth = 0;
1352
1353         // Check if any insets are larger
1354         for (pos_type pos = row_ptr->pos(); pos <= pos_end; ++pos) {
1355                 if (row_ptr->par()->isInset(pos)) {
1356                         tmpfont = getFont(bview->buffer(), row_ptr->par(), pos);
1357                         tmpinset = row_ptr->par()->getInset(pos);
1358                         if (tmpinset) {
1359 #if 1 // this is needed for deep update on initialitation
1360                                 tmpinset->update(bview, tmpfont);
1361 #endif
1362                                 asc = tmpinset->ascent(bview, tmpfont);
1363                                 desc = tmpinset->descent(bview, tmpfont);
1364                                 maxwidth += tmpinset->width(bview, tmpfont);
1365                                 maxasc = max(maxasc, asc);
1366                                 maxdesc = max(maxdesc, desc);
1367                         }
1368                 } else {
1369                         maxwidth += singleWidth(bview, row_ptr->par(), pos);
1370                 }
1371         }
1372
1373         // Check if any custom fonts are larger (Asger)
1374         // This is not completely correct, but we can live with the small,
1375         // cosmetic error for now.
1376         LyXFont::FONT_SIZE maxsize =
1377                 row_ptr->par()->highestFontInRange(row_ptr->pos(), pos_end, size);
1378         if (maxsize > font.size()) {
1379                 font.setSize(maxsize);
1380
1381                 asc = font_metrics::maxAscent(font);
1382                 desc = font_metrics::maxDescent(font);
1383                 if (asc > maxasc)
1384                         maxasc = asc;
1385                 if (desc > maxdesc)
1386                         maxdesc = desc;
1387         }
1388
1389         // This is nicer with box insets:
1390         ++maxasc;
1391         ++maxdesc;
1392
1393         row_ptr->ascent_of_text(maxasc);
1394
1395         // is it a top line?
1396         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
1397
1398                 // some parksips VERY EASY IMPLEMENTATION
1399                 if (bview->buffer()->params.paragraph_separation ==
1400                         BufferParams::PARSEP_SKIP)
1401                 {
1402                         if (layout.isParagraph()
1403                                 && firstpar->getDepth() == 0
1404                                 && firstpar->previous())
1405                         {
1406                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1407                         } else if (firstpar->previous() &&
1408                                    textclasslist[bview->buffer()->params.textclass][firstpar->previous()->layout()].isParagraph() &&
1409                                    firstpar->previous()->getDepth() == 0)
1410                         {
1411                                 // is it right to use defskip here too? (AS)
1412                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1413                         }
1414                 }
1415
1416                 // the paper margins
1417                 if (!row_ptr->par()->previous() && bv_owner)
1418                         maxasc += LYX_PAPER_MARGIN;
1419
1420                 // add the vertical spaces, that the user added
1421                 maxasc += getLengthMarkerHeight(bview, firstpar->params().spaceTop());
1422
1423                 // do not forget the DTP-lines!
1424                 // there height depends on the font of the nearest character
1425                 if (firstpar->params().lineTop())
1426
1427                         maxasc += 2 * font_metrics::ascent('x', getFont(bview->buffer(),
1428                                         firstpar, 0));
1429                 // and now the pagebreaks
1430                 if (firstpar->params().pagebreakTop())
1431                         maxasc += 3 * defaultHeight();
1432
1433                 // This is special code for the chapter, since the label of this
1434                 // layout is printed in an extra row
1435                 if (layout.labeltype == LABEL_COUNTER_CHAPTER
1436                         && bview->buffer()->params.secnumdepth >= 0)
1437                 {
1438                         float spacing_val = 1.0;
1439                         if (!row_ptr->par()->params().spacing().isDefault()) {
1440                                 spacing_val = row_ptr->par()->params().spacing().getValue();
1441                         } else {
1442                                 spacing_val = bview->buffer()->params.spacing.getValue();
1443                         }
1444
1445                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1446                                          layout.spacing.getValue() *
1447                                          spacing_val)
1448                                 + int(font_metrics::maxAscent(labelfont) *
1449                                       layout.spacing.getValue() *
1450                                       spacing_val);
1451                 }
1452
1453                 // special code for the top label
1454                 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1455                      || layout.labeltype == LABEL_BIBLIO
1456                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1457                     && row_ptr->par()->isFirstInSequence()
1458                     && !row_ptr->par()->getLabelstring().empty())
1459                 {
1460                         float spacing_val = 1.0;
1461                         if (!row_ptr->par()->params().spacing().isDefault()) {
1462                                 spacing_val = row_ptr->par()->params().spacing().getValue();
1463                         } else {
1464                                 spacing_val = bview->buffer()->params.spacing.getValue();
1465                         }
1466
1467                         labeladdon = int(
1468                                 (font_metrics::maxAscent(labelfont) *
1469                                  layout.spacing.getValue() *
1470                                  spacing_val)
1471                                 +(font_metrics::maxDescent(labelfont) *
1472                                   layout.spacing.getValue() *
1473                                   spacing_val)
1474                                 + layout.topsep * defaultHeight()
1475                                 + layout.labelbottomsep *  defaultHeight());
1476                 }
1477
1478                 // and now the layout spaces, for example before and after a section,
1479                 // or between the items of a itemize or enumerate environment
1480
1481                 if (!firstpar->params().pagebreakTop()) {
1482                         Paragraph * prev = row_ptr->par()->previous();
1483                         if (prev)
1484                                 prev = row_ptr->par()->depthHook(row_ptr->par()->getDepth());
1485                         if (prev && prev->layout() == firstpar->layout() &&
1486                                 prev->getDepth() == firstpar->getDepth() &&
1487                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1488                         {
1489                                 layoutasc = (layout.itemsep * defaultHeight());
1490                         } else if (row_ptr->previous()) {
1491                                 tmptop = layout.topsep;
1492
1493                                 if (row_ptr->previous()->par()->getDepth() >= row_ptr->par()->getDepth())
1494                                         tmptop -= textclasslist[bview->buffer()->params.textclass][row_ptr->previous()->par()->layout()].bottomsep;
1495
1496                                 if (tmptop > 0)
1497                                         layoutasc = (tmptop * defaultHeight());
1498                         } else if (row_ptr->par()->params().lineTop()) {
1499                                 tmptop = layout.topsep;
1500
1501                                 if (tmptop > 0)
1502                                         layoutasc = (tmptop * defaultHeight());
1503                         }
1504
1505                         prev = row_ptr->par()->outerHook();
1506                         if (prev)  {
1507                                 maxasc += int(textclasslist[bview->buffer()->params.textclass][prev->layout()].parsep * defaultHeight());
1508                         } else {
1509                                 if (firstpar->previous() &&
1510                                         firstpar->previous()->getDepth() == 0 &&
1511                                         firstpar->previous()->layout() !=
1512                                         firstpar->layout())
1513                                 {
1514                                         // avoid parsep
1515                                 } else if (firstpar->previous()) {
1516                                         maxasc += int(layout.parsep * defaultHeight());
1517                                 }
1518                         }
1519                 }
1520         }
1521
1522         // is it a bottom line?
1523         if (row_ptr->par() == par
1524                 && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par()))
1525         {
1526                 // the paper margins
1527                 if (!par->next() && bv_owner)
1528                         maxdesc += LYX_PAPER_MARGIN;
1529
1530                 // add the vertical spaces, that the user added
1531                 maxdesc += getLengthMarkerHeight(bview, firstpar->params().spaceBottom());
1532
1533                 // do not forget the DTP-lines!
1534                 // there height depends on the font of the nearest character
1535                 if (firstpar->params().lineBottom())
1536                         maxdesc += 2 * font_metrics::ascent('x',
1537                                                        getFont(bview->buffer(),
1538                                                                par,
1539                                                                max(pos_type(0), par->size() - 1)));
1540
1541                 // and now the pagebreaks
1542                 if (firstpar->params().pagebreakBottom())
1543                         maxdesc += 3 * defaultHeight();
1544
1545                 // and now the layout spaces, for example before and after
1546                 // a section, or between the items of a itemize or enumerate
1547                 // environment
1548                 if (!firstpar->params().pagebreakBottom()
1549                     && row_ptr->par()->next()) {
1550                         Paragraph * nextpar = row_ptr->par()->next();
1551                         Paragraph * comparepar = row_ptr->par();
1552                         float usual = 0;
1553                         float unusual = 0;
1554
1555                         if (comparepar->getDepth() > nextpar->getDepth()) {
1556                                 usual = (textclasslist[bview->buffer()->params.textclass][comparepar->layout()].bottomsep * defaultHeight());
1557                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1558                                 if (comparepar->layout()!= nextpar->layout()
1559                                         || nextpar->getLabelWidthString() !=
1560                                         comparepar->getLabelWidthString())
1561                                 {
1562                                         unusual = (textclasslist[bview->buffer()->params.textclass][comparepar->layout()].bottomsep * defaultHeight());
1563                                 }
1564                                 if (unusual > usual)
1565                                         layoutdesc = unusual;
1566                                 else
1567                                         layoutdesc = usual;
1568                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1569
1570                                 if (comparepar->layout() != nextpar->layout()
1571                                         || nextpar->getLabelWidthString() !=
1572                                         comparepar->getLabelWidthString())
1573                                         layoutdesc = int(textclasslist[bview->buffer()->params.textclass][comparepar->layout()].bottomsep * defaultHeight());
1574                         }
1575                 }
1576         }
1577
1578         // incalculate the layout spaces
1579         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1580         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1581
1582         // calculate the new height of the text
1583         height -= row_ptr->height();
1584
1585         row_ptr->height(maxasc + maxdesc + labeladdon);
1586         row_ptr->baseline(maxasc + labeladdon);
1587
1588         height += row_ptr->height();
1589         float x = 0;
1590         if (layout.margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1591                 float dummy;
1592                 // this IS needed
1593                 row_ptr->width(maxwidth);
1594                 prepareToPrint(bview, row_ptr, x, dummy, dummy, dummy, false);
1595         }
1596         row_ptr->width(int(maxwidth + x));
1597         if (inset_owner) {
1598                 Row * r = firstrow;
1599                 width = max(0,workWidth(bview));
1600                 while (r) {
1601                         if (r->width() > width)
1602                                 width = r->width();
1603                         r = r->next();
1604                 }
1605         }
1606 }
1607
1608
1609 // Appends the implicit specified paragraph behind the specified row,
1610 // start at the implicit given position 
1611 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1612 {
1613         bool not_ready = true;
1614
1615         // The last character position of a paragraph is an invariant so we can
1616         // safely get it here. (Asger)
1617         pos_type const lastposition = row->par()->size();
1618         do {
1619                 // Get the next breakpoint
1620                 pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1621
1622                 Row * tmprow = row;
1623
1624                 // Insert the new row
1625                 if (z < lastposition) {
1626                         ++z;
1627                         insertRow(row, row->par(), z);
1628                         row = row->next();
1629
1630                         row->height(0);
1631                 } else
1632                         not_ready = false;
1633
1634                 // Set the dimensions of the row
1635                 // fixed fill setting now by calling inset->update() in
1636                 // SingleWidth when needed!
1637                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1638                 setHeightOfRow(bview, tmprow);
1639
1640         } while (not_ready);
1641 }
1642
1643
1644 void LyXText::breakAgain(BufferView * bview, Row * row) const
1645 {
1646         bool not_ready = true;
1647
1648         do  {
1649                 // get the next breakpoint
1650                 pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1651                 Row * tmprow = row;
1652
1653                 if (z < row->par()->size()) {
1654                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1655                                 // insert a new row
1656                                 ++z;
1657                                 insertRow(row, row->par(), z);
1658                                 row = row->next();
1659                                 row->height(0);
1660                         } else  {
1661                                 row = row->next();
1662                                 ++z;
1663                                 if (row->pos() == z)
1664                                         not_ready = false;     // the rest will not change
1665                                 else {
1666                                         row->pos(z);
1667                                 }
1668                         }
1669                 } else {
1670                         // if there are some rows too much, delete them
1671                         // only if you broke the whole paragraph!
1672                         Row * tmprow2 = row;
1673                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1674                                 tmprow2 = tmprow2->next();
1675                         }
1676                         while (tmprow2 != row) {
1677                                 tmprow2 = tmprow2->previous();
1678                                 removeRow(tmprow2->next());
1679                         }
1680                         not_ready = false;
1681                 }
1682
1683                 // set the dimensions of the row 
1684                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1685                 setHeightOfRow(bview, tmprow);
1686         } while (not_ready);
1687 }
1688
1689
1690 // this is just a little changed version of break again
1691 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1692 {
1693         // get the next breakpoint
1694         pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1695         Row * tmprow = row;
1696
1697         if (z < row->par()->size()) {
1698                 if (!row->next()
1699                     || (row->next() && row->next()->par() != row->par())) {
1700                         // insert a new row 
1701                         ++z;
1702                         insertRow(row, row->par(), z);
1703                         row = row->next();
1704                         row->height(0);
1705                 } else  {
1706                         row = row->next();
1707                         ++z;
1708                         if (row->pos() != z)
1709                                 row->pos(z);
1710                 }
1711         } else {
1712                 // if there are some rows too much, delete them
1713                 // only if you broke the whole paragraph!
1714                 Row * tmprow2 = row;
1715                 while (tmprow2->next()
1716                        && tmprow2->next()->par() == row->par()) {
1717                         tmprow2 = tmprow2->next();
1718                 }
1719                 while (tmprow2 != row) {
1720                         tmprow2 = tmprow2->previous();
1721                         removeRow(tmprow2->next());
1722                 }
1723         }
1724
1725         // set the dimensions of the row
1726         tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1727         setHeightOfRow(bview, tmprow);
1728 }
1729
1730
1731 void LyXText::breakParagraph(BufferView * bview, char keep_layout)
1732 {
1733         LyXTextClass const & tclass =
1734                 textclasslist[bview->buffer()->params.textclass];
1735         LyXLayout const & layout = tclass[cursor.par()->layout()];
1736
1737         // this is only allowed, if the current paragraph is not empty or caption
1738         // and if it has not the keepempty flag aktive
1739         if ((cursor.par()->size() <= 0)
1740            && layout.labeltype != LABEL_SENSITIVE
1741            && !layout.keepempty)
1742                 return;
1743
1744         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1745
1746         // Always break behind a space
1747         //
1748         // It is better to erase the space (Dekel)
1749         if (cursor.pos() < cursor.par()->size()
1750              && cursor.par()->isLineSeparator(cursor.pos()))
1751            cursor.par()->erase(cursor.pos());
1752         // cursor.pos(cursor.pos() + 1);
1753
1754         // break the paragraph
1755         if (keep_layout)
1756                 keep_layout = 2;
1757         else
1758                 keep_layout = layout.isEnvironment();
1759
1760         // we need to set this before we insert the paragraph. IMO the
1761         // breakParagraph call should return a bool if it inserts the
1762         // paragraph before or behind and we should react on that one
1763         // but we can fix this in 1.3.0 (Jug 20020509)
1764         bool const isempty = (layout.keepempty && !cursor.par()->size());
1765         cursor.par()->breakParagraph(bview->buffer()->params, cursor.pos(),
1766                                 keep_layout);
1767
1768         // well this is the caption hack since one caption is really enough
1769         if (layout.labeltype == LABEL_SENSITIVE) {
1770                 if (!cursor.pos())
1771                         // set to standard-layout
1772                         cursor.par()->applyLayout(tclass.defaultLayoutName());
1773                 else
1774                         // set to standard-layout
1775                         cursor.par()->next()->applyLayout(tclass.defaultLayoutName());
1776         }
1777
1778         // if the cursor is at the beginning of a row without prior newline,
1779         // move one row up!
1780         // This touches only the screen-update. Otherwise we would may have
1781         // an empty row on the screen 
1782         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1783                          && cursor.row()->pos() == cursor.pos())
1784         {
1785                 cursorLeft(bview);
1786         }
1787
1788         status(bview, LyXText::NEED_MORE_REFRESH);
1789         refresh_row = cursor.row();
1790         refresh_y = cursor.y() - cursor.row()->baseline();
1791
1792         // Do not forget the special right address boxes
1793         if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1794                 while (refresh_row->previous() &&
1795                        refresh_row->previous()->par() == refresh_row->par())
1796                 {
1797                         refresh_row = refresh_row->previous();
1798                         refresh_y -= refresh_row->height();
1799                 }
1800         }
1801         removeParagraph(cursor.row());
1802
1803         // set the dimensions of the cursor row
1804         cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1805
1806         setHeightOfRow(bview, cursor.row());
1807
1808         while (cursor.par()->next()->size()
1809           && cursor.par()->next()->isNewline(0))
1810            cursor.par()->next()->erase(0);
1811
1812         insertParagraph(bview, cursor.par()->next(), cursor.row());
1813
1814         updateCounters(bview, cursor.row()->previous());
1815
1816         // This check is necessary. Otherwise the new empty paragraph will
1817         // be deleted automatically. And it is more friendly for the user!
1818         if (cursor.pos() || isempty)
1819                 setCursor(bview, cursor.par()->next(), 0);
1820         else
1821                 setCursor(bview, cursor.par(), 0);
1822
1823         if (cursor.row()->next())
1824                 breakAgain(bview, cursor.row()->next());
1825
1826         need_break_row = 0;
1827 }
1828
1829
1830 // Just a macro to make some thing easier.
1831 void LyXText::redoParagraph(BufferView * bview) const
1832 {
1833         clearSelection();
1834         redoParagraphs(bview, cursor, cursor.par()->next());
1835         setCursorIntern(bview, cursor.par(), cursor.pos());
1836 }
1837
1838
1839 // insert a character, moves all the following breaks in the
1840 // same Paragraph one to the right and make a rebreak 
1841 void LyXText::insertChar(BufferView * bview, char c)
1842 {
1843         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1844
1845         // When the free-spacing option is set for the current layout,
1846         // disable the double-space checking
1847
1848         bool const freeSpacing =
1849                 textclasslist[bview->buffer()->params.textclass][cursor.row()->par()->layout()].free_spacing ||
1850                 cursor.row()->par()->isFreeSpacing();
1851
1852         if (lyxrc.auto_number) {
1853                 static string const number_operators = "+-/*";
1854                 static string const number_unary_operators = "+-";
1855                 static string const number_seperators = ".,:";
1856
1857                 if (current_font.number() == LyXFont::ON) {
1858                         if (!IsDigit(c) && !contains(number_operators, c) &&
1859                             !(contains(number_seperators, c) &&
1860                               cursor.pos() >= 1 &&
1861                               cursor.pos() < cursor.par()->size() &&
1862                               getFont(bview->buffer(),
1863                                       cursor.par(),
1864                                       cursor.pos()).number() == LyXFont::ON &&
1865                               getFont(bview->buffer(),
1866                                       cursor.par(),
1867                                       cursor.pos() - 1).number() == LyXFont::ON)
1868                            )
1869                                 number(bview); // Set current_font.number to OFF
1870                 } else if (IsDigit(c) &&
1871                            real_current_font.isVisibleRightToLeft()) {
1872                         number(bview); // Set current_font.number to ON
1873
1874                         if (cursor.pos() > 0) {
1875                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1876                                 if (contains(number_unary_operators, c) &&
1877                                     (cursor.pos() == 1 ||
1878                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1879                                      cursor.par()->isNewline(cursor.pos() - 2))
1880                                   ) {
1881                                         setCharFont(bview->buffer(),
1882                                                     cursor.par(),
1883                                                     cursor.pos() - 1,
1884                                                     current_font);
1885                                 } else if (contains(number_seperators, c) &&
1886                                            cursor.pos() >= 2 &&
1887                                            getFont(bview->buffer(),
1888                                                    cursor.par(),
1889                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1890                                         setCharFont(bview->buffer(),
1891                                                     cursor.par(),
1892                                                     cursor.pos() - 1,
1893                                                     current_font);
1894                                 }
1895                         }
1896                 }
1897         }
1898
1899
1900         // First check, if there will be two blanks together or a blank at
1901         // the beginning of a paragraph.
1902         // I decided to handle blanks like normal characters, the main
1903         // difference are the special checks when calculating the row.fill
1904         // (blank does not count at the end of a row) and the check here
1905
1906         // The bug is triggered when we type in a description environment:
1907         // The current_font is not changed when we go from label to main text
1908         // and it should (along with realtmpfont) when we type the space.
1909         // CHECK There is a bug here! (Asger)
1910
1911         LyXFont realtmpfont = real_current_font;
1912         LyXFont rawtmpfont = current_font; 
1913         // store the current font.  This is because of the use of cursor
1914         // movements. The moving cursor would refresh the current font 
1915
1916         // Get the font that is used to calculate the baselineskip
1917         pos_type const lastpos = cursor.par()->size();
1918         LyXFont rawparfont =
1919                 cursor.par()->getFontSettings(bview->buffer()->params,
1920                                               lastpos - 1);
1921
1922         bool jumped_over_space = false;
1923
1924         if (!freeSpacing && IsLineSeparatorChar(c)) {
1925                 if ((cursor.pos() > 0
1926                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1927                     || (cursor.pos() > 0
1928                         && cursor.par()->isNewline(cursor.pos() - 1))
1929                     || (cursor.pos() == 0)) {
1930                         static bool sent_space_message = false;
1931                         if (!sent_space_message) {
1932                                 if (cursor.pos() == 0)
1933                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1934                                 else
1935                                         bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1936                                 sent_space_message = true;
1937                         }
1938                         charInserted();
1939                         return;
1940                 }
1941         } else if (IsNewlineChar(c)) {
1942                 if (cursor.pos() <= beginningOfMainBody(bview->buffer(),
1943                                                         cursor.par()))
1944                 {
1945                         charInserted();
1946                         return;
1947                 }
1948                 // No newline at first position 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) {
1971                 // Here case LyXText::InsertInset  already insertet the character
1972                 cursor.par()->insertChar(cursor.pos(), c);
1973         }
1974         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1975
1976         if (!jumped_over_space) {
1977                 // refresh the positions
1978                 Row * tmprow = row;
1979                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1980                         tmprow = tmprow->next();
1981                         tmprow->pos(tmprow->pos() + 1);
1982                 }
1983         }
1984
1985         // Is there a break one row above
1986         if (row->previous() && row->previous()->par() == row->par()
1987             && (cursor.par()->isLineSeparator(cursor.pos())
1988                 || cursor.par()->isNewline(cursor.pos())
1989                 || ((cursor.pos() < cursor.par()->size()) &&
1990                     cursor.par()->isInset(cursor.pos()+1))
1991                 || cursor.row()->fill() == -1))
1992         {
1993                 pos_type z = nextBreakPoint(bview,
1994                                                            row->previous(),
1995                                                            workWidth(bview));
1996                 if (z >= row->pos()) {
1997                         row->pos(z + 1);
1998
1999                         // set the dimensions of the row above
2000                         row->previous()->fill(fill(bview,
2001                                                    row->previous(),
2002                                                    workWidth(bview)));
2003
2004                         setHeightOfRow(bview, row->previous());
2005
2006                         y -= row->previous()->height();
2007                         refresh_y = y;
2008                         refresh_row = row->previous();
2009                         status(bview, LyXText::NEED_MORE_REFRESH);
2010
2011                         breakAgainOneRow(bview, row);
2012
2013                         current_font = rawtmpfont;
2014                         real_current_font = realtmpfont;
2015                         setCursor(bview, cursor.par(), cursor.pos() + 1,
2016                                   false, cursor.boundary());
2017                         // cursor MUST be in row now.
2018
2019                         if (row->next() && row->next()->par() == row->par())
2020                                 need_break_row = row->next();
2021                         else
2022                                 need_break_row = 0;
2023
2024                         // check, wether the last characters font has changed.
2025                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2026                             && rawparfont != rawtmpfont)
2027                                 redoHeightOfParagraph(bview, cursor);
2028
2029                         charInserted();
2030                         return;
2031                 }
2032         }
2033
2034         // recalculate the fill of the row
2035         if (row->fill() >= 0) {
2036                 // needed because a newline will set fill to -1. Otherwise
2037                 // we would not get a rebreak!
2038                 row->fill(fill(bview, row, workWidth(bview)));
2039         }
2040         if (c == Paragraph::META_INSET || row->fill() < 0) {
2041                 refresh_y = y;
2042                 refresh_row = row;
2043                 refresh_x = cursor.x();
2044                 refresh_pos = cursor.pos();
2045                 status(bview, LyXText::NEED_MORE_REFRESH);
2046                 breakAgainOneRow(bview, row);
2047                 // will the cursor be in another row now?
2048                 if (rowLast(row) <= cursor.pos() + 1 && row->next()) {
2049                         if (row->next() && row->next()->par() == row->par())
2050                                 // this should always be true
2051                                 row = row->next();
2052                         breakAgainOneRow(bview, row);
2053                 }
2054                 current_font = rawtmpfont;
2055                 real_current_font = realtmpfont;
2056
2057                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2058                           cursor.boundary());
2059                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2060                     != cursor.boundary())
2061                         setCursor(bview, cursor.par(), cursor.pos(), false,
2062                           !cursor.boundary());
2063                 if (row->next() && row->next()->par() == row->par())
2064                         need_break_row = row->next();
2065                 else
2066                         need_break_row = 0;
2067         } else {
2068                 refresh_y = y;
2069                 refresh_x = cursor.x();
2070                 refresh_row = row;
2071                 refresh_pos = cursor.pos();
2072
2073                 int const tmpheight = row->height();
2074                 setHeightOfRow(bview, row);
2075                 if (tmpheight == row->height())
2076                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2077                 else
2078                         status(bview, LyXText::NEED_MORE_REFRESH);
2079
2080                 current_font = rawtmpfont;
2081                 real_current_font = realtmpfont;
2082                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2083                           cursor.boundary());
2084         }
2085
2086         // check, wether the last characters font has changed.
2087         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2088             && rawparfont != rawtmpfont) {
2089                 redoHeightOfParagraph(bview, cursor);
2090         } else {
2091                 // now the special right address boxes
2092                 if (textclasslist[bview->buffer()->params.textclass][cursor.par()->layout()].margintype
2093                     == MARGIN_RIGHT_ADDRESS_BOX) {
2094                         redoDrawingOfParagraph(bview, cursor);
2095                 }
2096         }
2097
2098         charInserted();
2099 }
2100
2101
2102 void LyXText::charInserted()
2103 {
2104         // Here we could call FinishUndo for every 20 characters inserted.
2105         // This is from my experience how emacs does it.
2106         static unsigned int counter;
2107         if (counter < 20) {
2108                 ++counter;
2109         } else {
2110                 finishUndo();
2111                 counter = 0;
2112         }
2113 }
2114
2115
2116 void LyXText::prepareToPrint(BufferView * bview,
2117                              Row * row, float & x,
2118                              float & fill_separator,
2119                              float & fill_hfill,
2120                              float & fill_label_hfill,
2121                              bool bidi) const
2122 {
2123         float nlh;
2124         float ns;
2125
2126         float w = row->fill();
2127         fill_hfill = 0;
2128         fill_label_hfill = 0;
2129         fill_separator = 0;
2130         fill_label_hfill = 0;
2131
2132         bool const is_rtl =
2133                 row->par()->isRightToLeftPar(bview->buffer()->params);
2134         if (is_rtl) {
2135                 x = (workWidth(bview) > 0)
2136                         ? rightMargin(bview->buffer(), row) : 0;
2137         } else
2138                 x = (workWidth(bview) > 0)
2139                         ? leftMargin(bview, row) : 0;
2140
2141         // is there a manual margin with a manual label
2142         LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2143         LyXLayout const & layout = tclass[row->par()->layout()];
2144
2145         if (layout.margintype == MARGIN_MANUAL
2146             && layout.labeltype == LABEL_MANUAL) {
2147                 // one more since labels are left aligned
2148                 nlh = numberOfLabelHfills(bview->buffer(), row) + 1;
2149                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2150                         fill_label_hfill = labelFill(bview, row) / nlh;
2151                 }
2152         }
2153
2154         // are there any hfills in the row?
2155         float const nh = numberOfHfills(bview->buffer(), row);
2156
2157         if (nh) {
2158                 if (w > 0)
2159                         fill_hfill = w / nh;
2160         // we don't have to look at the alignment if it is ALIGN_LEFT and
2161         // if the row is already larger then the permitted width as then
2162         // we force the LEFT_ALIGN'edness!
2163         } else if (static_cast<int>(row->width()) < workWidth(bview)) {
2164                 // is it block, flushleft or flushright?
2165                 // set x how you need it
2166                 int align;
2167                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
2168                         align = layout.align;
2169                 } else {
2170                         align = row->par()->params().align();
2171                 }
2172
2173                 // center displayed insets
2174                 Inset * inset;
2175                 if (row->par()->isInset(row->pos())
2176                     && (inset=row->par()->getInset(row->pos()))
2177                     && (inset->display())) // || (inset->scroll() < 0)))
2178                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
2179                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2180                 // ERT insets should always be LEFT ALIGNED on screen
2181                 inset = row->par()->inInset();
2182                 if (inset && inset->owner() &&
2183                         inset->owner()->lyxCode() == Inset::ERT_CODE)
2184                 {
2185                         align = LYX_ALIGN_LEFT;
2186                 }
2187
2188                 switch (align) {
2189             case LYX_ALIGN_BLOCK:
2190                         ns = numberOfSeparators(bview->buffer(), row);
2191                         if (ns && row->next() && row->next()->par() == row->par() &&
2192                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
2193                             && !(row->next()->par()->isInset(row->next()->pos())
2194                                  && row->next()->par()->getInset(row->next()->pos())
2195                                  && row->next()->par()->getInset(row->next()->pos())->display())
2196                                 )
2197                         {
2198                                 fill_separator = w / ns;
2199                         } else if (is_rtl) {
2200                                 x += w;
2201                         }
2202                         break;
2203             case LYX_ALIGN_RIGHT:
2204                         x += w;
2205                         break;
2206             case LYX_ALIGN_CENTER:
2207                         x += w / 2;
2208                         break;
2209                 }
2210         }
2211         if (!bidi)
2212                 return;
2213
2214         computeBidiTables(bview->buffer(), row);
2215         if (is_rtl) {
2216                 pos_type main_body =
2217                         beginningOfMainBody(bview->buffer(), row->par());
2218                 pos_type last = rowLast(row);
2219
2220                 if (main_body > 0 &&
2221                     (main_body - 1 > last ||
2222                      !row->par()->isLineSeparator(main_body - 1))) {
2223                         x += font_metrics::width(layout.labelsep,
2224                                             getLabelFont(bview->buffer(), row->par()));
2225                         if (main_body - 1 <= last)
2226                                 x += fill_label_hfill;
2227                 }
2228         }
2229 }
2230
2231
2232 // important for the screen 
2233
2234
2235 // the cursor set functions have a special mechanism. When they
2236 // realize, that you left an empty paragraph, they will delete it.
2237 // They also delete the corresponding row 
2238
2239 void LyXText::cursorRightOneWord(BufferView * bview) const
2240 {
2241         // treat floats, HFills and Insets as words
2242         LyXCursor tmpcursor = cursor;
2243         // CHECK See comment on top of text.C
2244
2245         if (tmpcursor.pos() == tmpcursor.par()->size()
2246             && tmpcursor.par()->next()) {
2247                         tmpcursor.par(tmpcursor.par()->next());
2248                         tmpcursor.pos(0);
2249         } else {
2250                 int steps = 0;
2251
2252                 // Skip through initial nonword stuff.
2253                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2254                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2255                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2256                         tmpcursor.pos(tmpcursor.pos() + 1);
2257                         ++steps;
2258                 }
2259                 // Advance through word.
2260                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2261                         tmpcursor.par()->isWord(tmpcursor.pos())) {
2262                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2263                         tmpcursor.pos(tmpcursor.pos() + 1);
2264                         ++steps;
2265                 }
2266         }
2267         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2268 }
2269
2270
2271 void LyXText::cursorTab(BufferView * bview) const
2272 {
2273         LyXCursor tmpcursor = cursor;
2274         while (tmpcursor.pos() < tmpcursor.par()->size()
2275            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2276         tmpcursor.pos(tmpcursor.pos() + 1);
2277
2278         if (tmpcursor.pos() == tmpcursor.par()->size()) {
2279                 if (tmpcursor.par()->next()) {
2280                         tmpcursor.par(tmpcursor.par()->next());
2281                         tmpcursor.pos(0);
2282                 }
2283         } else
2284                 tmpcursor.pos(tmpcursor.pos() + 1);
2285         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2286 }
2287
2288
2289 // Skip initial whitespace at end of word and move cursor to *start*
2290 // of prior word, not to end of next prior word. 
2291 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2292 {
2293         LyXCursor tmpcursor = cursor;
2294         cursorLeftOneWord(tmpcursor);
2295         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2296 }
2297
2298
2299 void LyXText::cursorLeftOneWord(LyXCursor  & cur)  const
2300 {
2301         // treat HFills, floats and Insets as words
2302         cur = cursor;
2303         while (cur.pos()
2304                && (cur.par()->isSeparator(cur.pos() - 1)
2305                    || cur.par()->isKomma(cur.pos() - 1))
2306                && !(cur.par()->isHfill(cur.pos() - 1)
2307                     || cur.par()->isInset(cur.pos() - 1)))
2308                 cur.pos(cur.pos() - 1);
2309
2310         if (cur.pos()
2311             && (cur.par()->isInset(cur.pos() - 1)
2312                 || cur.par()->isHfill(cur.pos() - 1))) {
2313                 cur.pos(cur.pos() - 1);
2314         } else if (!cur.pos()) {
2315                 if (cur.par()->previous()) {
2316                         cur.par(cur.par()->previous());
2317                         cur.pos(cur.par()->size());
2318                 }
2319         } else {                // Here, cur != 0
2320                 while (cur.pos() > 0 &&
2321                        cur.par()->isWord(cur.pos()-1))
2322                         cur.pos(cur.pos() - 1);
2323         }
2324 }
2325
2326
2327 // Select current word. This depends on behaviour of
2328 // CursorLeftOneWord(), so it is patched as well. 
2329 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
2330                       word_location const loc) const
2331 {
2332         // first put the cursor where we wana start to select the word
2333         from = cursor;
2334         switch (loc) {
2335         case WHOLE_WORD_STRICT:
2336                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2337                     || cursor.par()->isSeparator(cursor.pos())
2338                     || cursor.par()->isKomma(cursor.pos())
2339                     || cursor.par()->isSeparator(cursor.pos() -1)
2340                     || cursor.par()->isKomma(cursor.pos() -1)) {
2341                         to = from;
2342                         return;
2343                 }
2344                 // no break here, we go to the next
2345
2346         case WHOLE_WORD:
2347                 // Move cursor to the beginning, when not already there.
2348                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2349                     && !from.par()->isKomma(from.pos() - 1))
2350                         cursorLeftOneWord(from);
2351                 break;
2352         case PREVIOUS_WORD:
2353                 // always move the cursor to the beginning of previous word
2354                 cursorLeftOneWord(from);
2355                 break;
2356         case NEXT_WORD:
2357                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2358                 break;
2359         case PARTIAL_WORD:
2360                 break;
2361         }
2362         to = from;
2363         while (to.pos() < to.par()->size()
2364                && !to.par()->isSeparator(to.pos())
2365                && !to.par()->isKomma(to.pos())
2366                && !to.par()->isHfill(to.pos()))
2367         {
2368                 to.pos(to.pos() + 1);
2369         }
2370 }
2371
2372
2373 void LyXText::selectWord(BufferView * bview, word_location const loc)
2374 {
2375         LyXCursor from;
2376         LyXCursor to;
2377         getWord(from, to, loc);
2378         if (cursor != from)
2379                 setCursor(bview, from.par(), from.pos());
2380         if (to == from)
2381                 return;
2382         selection.cursor = cursor;
2383         setCursor(bview, to.par(), to.pos());
2384         setSelection(bview);
2385 }
2386
2387
2388 // Select the word currently under the cursor when no
2389 // selection is currently set 
2390 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2391                                         word_location const loc)
2392 {
2393         if (!selection.set()) {
2394                 selectWord(bview, loc);
2395                 return selection.set();
2396         }
2397         return false;
2398 }
2399
2400
2401 // This function is only used by the spellchecker for NextWord().
2402 // It doesn't handle LYX_ACCENTs and probably never will.
2403 string const LyXText::selectNextWordToSpellcheck(BufferView * bview,
2404                                                  float & value) const
2405 {
2406         if (the_locking_inset) {
2407                 string str = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2408                 if (!str.empty()) {
2409                         value += float(cursor.y())/float(height);
2410                         return str;
2411                 }
2412                 // we have to go on checking so move cusor to the next char
2413                 if (cursor.pos() == cursor.par()->size()) {
2414                         if (!cursor.par()->next())
2415                                 return str;
2416                         cursor.par(cursor.par()->next());
2417                         cursor.pos(0);
2418                 } else
2419                         cursor.pos(cursor.pos() + 1);
2420         }
2421         Paragraph * tmppar = cursor.par();
2422
2423         // If this is not the very first word, skip rest of
2424         // current word because we are probably in the middle
2425         // of a word if there is text here.
2426         if (cursor.pos() || cursor.par()->previous()) {
2427                 while (cursor.pos() < cursor.par()->size()
2428                        && cursor.par()->isLetter(cursor.pos()))
2429                         cursor.pos(cursor.pos() + 1);
2430         }
2431
2432         // Now, skip until we have real text (will jump paragraphs)
2433         while ((cursor.par()->size() > cursor.pos()
2434                && (!cursor.par()->isLetter(cursor.pos()))
2435                && (!cursor.par()->isInset(cursor.pos()) ||
2436                            !cursor.par()->getInset(cursor.pos())->allowSpellcheck()))
2437                || (cursor.par()->size() == cursor.pos()
2438                    && cursor.par()->next()))
2439         {
2440                 if (cursor.pos() == cursor.par()->size()) {
2441                         cursor.par(cursor.par()->next());
2442                         cursor.pos(0);
2443                 } else
2444                         cursor.pos(cursor.pos() + 1);
2445         }
2446
2447         // now check if we hit an inset so it has to be a inset containing text!
2448         if (cursor.pos() < cursor.par()->size() &&
2449             cursor.par()->isInset(cursor.pos()))
2450         {
2451                 // lock the inset!
2452                 cursor.par()->getInset(cursor.pos())->edit(bview);
2453                 // now call us again to do the above trick
2454                 // but obviously we have to start from down below ;)
2455                 return bview->text->selectNextWordToSpellcheck(bview, value);
2456         }
2457
2458         // Update the value if we changed paragraphs
2459         if (cursor.par() != tmppar) {
2460                 setCursor(bview, cursor.par(), cursor.pos());
2461                 value = float(cursor.y())/float(height);
2462         }
2463
2464         // Start the selection from here
2465         selection.cursor = cursor;
2466
2467         // and find the end of the word (insets like optional hyphens
2468         // and ligature break are part of a word)
2469         while (cursor.pos() < cursor.par()->size()
2470                && (cursor.par()->isLetter(cursor.pos())))
2471                 cursor.pos(cursor.pos() + 1);
2472
2473         // Finally, we copy the word to a string and return it
2474         string str;
2475         if (selection.cursor.pos() < cursor.pos()) {
2476                 pos_type i;
2477                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2478                         if (!cursor.par()->isInset(i))
2479                                 str += cursor.par()->getChar(i);
2480                 }
2481         }
2482         return str;
2483 }
2484
2485
2486 // This one is also only for the spellchecker
2487 void LyXText::selectSelectedWord(BufferView * bview)
2488 {
2489         if (the_locking_inset) {
2490                 the_locking_inset->selectSelectedWord(bview);
2491                 return;
2492         }
2493         // move cursor to the beginning
2494         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2495
2496         // set the sel cursor
2497         selection.cursor = cursor;
2498
2499         // now find the end of the word
2500         while (cursor.pos() < cursor.par()->size()
2501                && (cursor.par()->isLetter(cursor.pos())))
2502                 cursor.pos(cursor.pos() + 1);
2503
2504         setCursor(bview, cursor.par(), cursor.pos());
2505
2506         // finally set the selection
2507         setSelection(bview);
2508 }
2509
2510
2511 // Delete from cursor up to the end of the current or next word.
2512 void LyXText::deleteWordForward(BufferView * bview)
2513 {
2514         if (!cursor.par()->size())
2515                 cursorRight(bview);
2516         else {
2517                 LyXCursor tmpcursor = cursor;
2518                 tmpcursor.row(0); // ??
2519                 selection.set(true); // to avoid deletion
2520                 cursorRightOneWord(bview);
2521                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2522                 selection.cursor = cursor;
2523                 cursor = tmpcursor;
2524                 setSelection(bview);
2525
2526                 // Great, CutSelection() gets rid of multiple spaces.
2527                 cutSelection(bview, true, false);
2528         }
2529 }
2530
2531
2532 // Delete from cursor to start of current or prior word.
2533 void LyXText::deleteWordBackward(BufferView * bview)
2534 {
2535         if (!cursor.par()->size())
2536                 cursorLeft(bview);
2537         else {
2538                 LyXCursor tmpcursor = cursor;
2539                 tmpcursor.row(0); // ??
2540                 selection.set(true); // to avoid deletion
2541                 cursorLeftOneWord(bview);
2542                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2543                 selection.cursor = cursor;
2544                 cursor = tmpcursor;
2545                 setSelection(bview);
2546                 cutSelection(bview, true, false);
2547         }
2548 }
2549
2550
2551 // Kill to end of line. 
2552 void LyXText::deleteLineForward(BufferView * bview)
2553 {
2554         if (!cursor.par()->size())
2555                 // Paragraph is empty, so we just go to the right
2556                 cursorRight(bview);
2557         else {
2558                 LyXCursor tmpcursor = cursor;
2559                 // We can't store the row over a regular setCursor
2560                 // so we set it to 0 and reset it afterwards.
2561                 tmpcursor.row(0); // ??
2562                 selection.set(true); // to avoid deletion
2563                 cursorEnd(bview);
2564                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2565                 selection.cursor = cursor;
2566                 cursor = tmpcursor;
2567                 setSelection(bview);
2568                 // What is this test for ??? (JMarc)
2569                 if (!selection.set()) {
2570                         deleteWordForward(bview);
2571                 } else {
2572                         cutSelection(bview, true, false);
2573                 }
2574         }
2575 }
2576
2577
2578 // Change the case of a word at cursor position.
2579 // This function directly manipulates Paragraph::text because there
2580 // is no Paragraph::SetChar currently. I did what I could to ensure
2581 // that it is correct. I guess part of it should be moved to
2582 // Paragraph, but it will have to change for 1.1 anyway. At least
2583 // it does not access outside of the allocated array as the older
2584 // version did. (JMarc)
2585 void LyXText::changeCase(BufferView * bview, LyXText::TextCase action)
2586 {
2587         LyXCursor from;
2588         LyXCursor to;
2589
2590         if (selection.set()) {
2591                 from = selection.start;
2592                 to = selection.end;
2593         } else {
2594                 getWord(from, to, PARTIAL_WORD);
2595                 setCursor(bview, to.par(), to.pos() + 1);
2596         }
2597
2598         changeRegionCase(bview, from, to, action);
2599 }
2600
2601
2602 void LyXText::changeRegionCase(BufferView * bview,
2603                                LyXCursor const & from,
2604                                LyXCursor const & to,
2605                                LyXText::TextCase action)
2606 {
2607         lyx::Assert(from <= to);
2608
2609         setUndo(bview, Undo::FINISH, from.par(), to.par()->next());
2610
2611         pos_type pos = from.pos();
2612         Paragraph * par = from.par();
2613
2614         while (par && (pos != to.pos() || par != to.par())) {
2615                 unsigned char c = par->getChar(pos);
2616                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2617                         switch (action) {
2618                         case text_lowercase:
2619                                 c = lowercase(c);
2620                                 break;
2621                         case text_capitalization:
2622                                 c = uppercase(c);
2623                                 action = text_lowercase;
2624                                 break;
2625                         case text_uppercase:
2626                                 c = uppercase(c);
2627                                 break;
2628                         }
2629                 }
2630                 par->setChar(pos, c);
2631                 checkParagraph(bview, par, pos);
2632
2633                 ++pos;
2634                 if (pos == par->size()) {
2635                         par = par->next();
2636                         pos = 0;
2637                 }
2638         }
2639         if (to.row() != from.row()) {
2640                 refresh_y = from.y() - from.row()->baseline();
2641                 refresh_row = from.row();
2642                 status(bview, LyXText::NEED_MORE_REFRESH);
2643         }
2644 }
2645
2646
2647 void LyXText::transposeChars(BufferView & bview)
2648 {
2649         Paragraph * tmppar = cursor.par();
2650
2651         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2652
2653         pos_type tmppos = cursor.pos();
2654
2655         // First decide if it is possible to transpose at all
2656
2657         // We are at the beginning of a paragraph.
2658         if (tmppos == 0) return;
2659
2660         // We are at the end of a paragraph.
2661         if (tmppos == tmppar->size() - 1) return;
2662
2663         unsigned char c1 = tmppar->getChar(tmppos);
2664         unsigned char c2 = tmppar->getChar(tmppos - 1);
2665
2666         if (c1 != Paragraph::META_INSET
2667             && c2 != Paragraph::META_INSET) {
2668                 tmppar->setChar(tmppos, c2);
2669                 tmppar->setChar(tmppos - 1, c1);
2670         }
2671         // We should have an implementation that handles insets
2672         // as well, but that will have to come later. (Lgb)
2673         checkParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2674 }
2675
2676
2677 void LyXText::Delete(BufferView * bview)
2678 {
2679         // this is a very easy implementation
2680
2681         LyXCursor old_cursor = cursor;
2682         int const old_cur_par_id = old_cursor.par()->id();
2683         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2684                 old_cursor.par()->previous()->id() : 0;
2685
2686         // just move to the right
2687         cursorRight(bview);
2688
2689         // CHECK Look at the comment here.
2690         // This check is not very good...
2691         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2692         // and that can very well delete the par or par->previous in
2693         // old_cursor. Will a solution where we compare paragraph id's
2694         //work better?
2695         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2696             == old_cur_par_prev_id
2697             && cursor.par()->id() != old_cur_par_id) {
2698                 // delete-empty-paragraph-mechanism has done it
2699                 return;
2700         }
2701
2702         // if you had success make a backspace
2703         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2704                 LyXCursor tmpcursor = cursor;
2705                 // to make sure undo gets the right cursor position
2706                 cursor = old_cursor;
2707                 setUndo(bview, Undo::DELETE,
2708                         cursor.par(), cursor.par()->next());
2709                 cursor = tmpcursor;
2710                 backspace(bview);
2711         }
2712 }
2713
2714
2715 void LyXText::backspace(BufferView * bview)
2716 {
2717         // Get the font that is used to calculate the baselineskip
2718         pos_type lastpos = cursor.par()->size();
2719         LyXFont rawparfont =
2720                 cursor.par()->getFontSettings(bview->buffer()->params,
2721                                               lastpos - 1);
2722
2723         if (cursor.pos() == 0) {
2724                 // The cursor is at the beginning of a paragraph,
2725                 // so the the backspace will collapse two paragraphs into one.
2726
2727                 // we may paste some paragraphs
2728
2729                 // is it an empty paragraph?
2730
2731                 if ((lastpos == 0
2732                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2733                         // This is an empty paragraph and we delete it just by moving the cursor one step
2734                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2735                         // of the paragraph.
2736
2737                         if (cursor.par()->previous()) {
2738                                 Paragraph * tmppar = cursor.par()->previous();
2739                                 if (cursor.par()->layout() == tmppar->layout()
2740                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2741                                         // Inherit bottom DTD from the paragraph below.
2742                                         // (the one we are deleting)
2743                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2744                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2745                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2746                                 }
2747
2748                                 cursorLeft(bview);
2749
2750                                 // the layout things can change the height of a row !
2751                                 int const tmpheight = cursor.row()->height();
2752                                 setHeightOfRow(bview, cursor.row());
2753                                 if (cursor.row()->height() != tmpheight) {
2754                                         refresh_y = cursor.y() - cursor.row()->baseline();
2755                                         refresh_row = cursor.row();
2756                                         status(bview, LyXText::NEED_MORE_REFRESH);
2757                                 }
2758                                 return;
2759                         }
2760                 }
2761
2762                 if (cursor.par()->previous()) {
2763                         setUndo(bview, Undo::DELETE,
2764                                 cursor.par()->previous(), cursor.par()->next());
2765                 }
2766
2767                 Paragraph * tmppar = cursor.par();
2768                 Row * tmprow = cursor.row();
2769
2770                 // We used to do cursorLeftIntern() here, but it is
2771                 // not a good idea since it triggers the auto-delete
2772                 // mechanism. So we do a cursorLeftIntern()-lite,
2773                 // without the dreaded mechanism. (JMarc)
2774                 if (cursor.par()->previous()) {
2775                         // steps into the above paragraph.
2776                         setCursorIntern(bview, cursor.par()->previous(),
2777                                         cursor.par()->previous()->size(),
2778                                         false);
2779                 }
2780
2781                 // Pasting is not allowed, if the paragraphs have different
2782                 // layout. I think it is a real bug of all other
2783                 // word processors to allow it. It confuses the user.
2784                 // Even so with a footnote paragraph and a non-footnote
2785                 // paragraph. I will not allow pasting in this case,
2786                 // because the user would be confused if the footnote behaves
2787                 // different wether it is open or closed.
2788
2789                 //      Correction: Pasting is always allowed with standard-layout
2790                 LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2791
2792                 if (cursor.par() != tmppar
2793                     && (cursor.par()->layout() == tmppar->layout()
2794                         || tmppar->layout() == tclass.defaultLayoutName())
2795                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2796                         removeParagraph(tmprow);
2797                         removeRow(tmprow);
2798                         cursor.par()->pasteParagraph(bview->buffer()->params);
2799
2800                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2801                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2802                         // strangely enough it seems that commenting out the line above removes
2803                         // most or all of the segfaults. I will however also try to move the
2804                         // two Remove... lines in front of the PasteParagraph too.
2805                         else
2806                                 if (cursor.pos())
2807                                         cursor.pos(cursor.pos() - 1);
2808
2809                         status(bview, LyXText::NEED_MORE_REFRESH);
2810                         refresh_row = cursor.row();
2811                         refresh_y = cursor.y() - cursor.row()->baseline();
2812
2813                         // remove the lost paragraph
2814                         // This one is not safe, since the paragraph that the tmprow and the
2815                         // following rows belong to has been deleted by the PasteParagraph
2816                         // above. The question is... could this be moved in front of the
2817                         // PasteParagraph?
2818                         //RemoveParagraph(tmprow);
2819                         //RemoveRow(tmprow);
2820
2821                         // This rebuilds the rows.
2822                         appendParagraph(bview, cursor.row());
2823                         updateCounters(bview, cursor.row());
2824
2825                         // the row may have changed, block, hfills etc.
2826                         setCursor(bview, cursor.par(), cursor.pos(), false);
2827                 }
2828         } else {
2829                 // this is the code for a normal backspace, not pasting
2830                 // any paragraphs 
2831                 setUndo(bview, Undo::DELETE,
2832                         cursor.par(), cursor.par()->next());
2833                 // We used to do cursorLeftIntern() here, but it is
2834                 // not a good idea since it triggers the auto-delete
2835                 // mechanism. So we do a cursorLeftIntern()-lite,
2836                 // without the dreaded mechanism. (JMarc)
2837                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2838                                 false, cursor.boundary());
2839
2840                 // some insets are undeletable here
2841                 if (cursor.par()->isInset(cursor.pos())) {
2842                         if (!cursor.par()->getInset(cursor.pos())->deletable())
2843                                 return;
2844                         // force complete redo when erasing display insets
2845                         // this is a cruel method but safe..... Matthias
2846                         if (cursor.par()->getInset(cursor.pos())->display() ||
2847                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2848                                 cursor.par()->erase(cursor.pos());
2849                                 redoParagraph(bview);
2850                                 return;
2851                         }
2852                 }
2853
2854                 Row * row = cursor.row();
2855                 int y = cursor.y() - row->baseline();
2856                 pos_type z;
2857                 // remember that a space at the end of a row doesnt count
2858                 // when calculating the fill 
2859                 if (cursor.pos() < rowLast(row) ||
2860                     !cursor.par()->isLineSeparator(cursor.pos())) {
2861                         row->fill(row->fill() + singleWidth(bview,
2862                                                             cursor.par(),
2863                                                             cursor.pos()));
2864                 }
2865
2866                 // some special code when deleting a newline. This is similar
2867                 // to the behavior when pasting paragraphs 
2868                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2869                         cursor.par()->erase(cursor.pos());
2870                         // refresh the positions
2871                         Row * tmprow = row;
2872                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2873                                 tmprow = tmprow->next();
2874                                 tmprow->pos(tmprow->pos() - 1);
2875                         }
2876                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2877                                 cursor.pos(cursor.pos() - 1);
2878
2879                         if (cursor.pos() < cursor.par()->size()
2880                             && !cursor.par()->isSeparator(cursor.pos())) {
2881                                 cursor.par()->insertChar(cursor.pos(), ' ');
2882                                 setCharFont(bview->buffer(), cursor.par(),
2883                                             cursor.pos(), current_font);
2884                                 // refresh the positions
2885                                 tmprow = row;
2886                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2887                                         tmprow = tmprow->next();
2888                                         tmprow->pos(tmprow->pos() + 1);
2889                                 }
2890                         }
2891                 } else {
2892                         cursor.par()->erase(cursor.pos());
2893
2894                         // refresh the positions
2895                         Row * tmprow = row;
2896                         while (tmprow->next()
2897                                && tmprow->next()->par() == row->par()) {
2898                                 tmprow = tmprow->next();
2899                                 tmprow->pos(tmprow->pos() - 1);
2900                         }
2901
2902                         // delete newlines at the beginning of paragraphs
2903                         while (cursor.par()->size() &&
2904                                cursor.par()->isNewline(cursor.pos()) &&
2905                                cursor.pos() == beginningOfMainBody(bview->buffer(),
2906                                                                    cursor.par())) {
2907                                 cursor.par()->erase(cursor.pos());
2908                                 // refresh the positions
2909                                 tmprow = row;
2910                                 while (tmprow->next() &&
2911                                        tmprow->next()->par() == row->par()) {
2912                                         tmprow = tmprow->next();
2913                                         tmprow->pos(tmprow->pos() - 1);
2914                                 }
2915                         }
2916                 }
2917
2918                 // is there a break one row above
2919                 if (row->previous() && row->previous()->par() == row->par()) {
2920                         z = nextBreakPoint(bview, row->previous(),
2921                                            workWidth(bview));
2922                         if (z >= row->pos()) {
2923                                 row->pos(z + 1);
2924
2925                                 Row * tmprow = row->previous();
2926
2927                                 // maybe the current row is now empty
2928                                 if (row->pos() >= row->par()->size()) {
2929                                         // remove it
2930                                         removeRow(row);
2931                                         need_break_row = 0;
2932                                 } else {
2933                                         breakAgainOneRow(bview, row);
2934                                         if (row->next() && row->next()->par() == row->par())
2935                                                 need_break_row = row->next();
2936                                         else
2937                                                 need_break_row = 0;
2938                                 }
2939
2940                                 // set the dimensions of the row above
2941                                 y -= tmprow->height();
2942                                 tmprow->fill(fill(bview, tmprow,
2943                                                   workWidth(bview)));
2944                                 setHeightOfRow(bview, tmprow);
2945
2946                                 refresh_y = y;
2947                                 refresh_row = tmprow;
2948                                 status(bview, LyXText::NEED_MORE_REFRESH);
2949                                 setCursor(bview, cursor.par(), cursor.pos(),
2950                                           false, cursor.boundary());
2951                                 //current_font = rawtmpfont;
2952                                 //real_current_font = realtmpfont;
2953                                 // check, whether the last character's font has changed.
2954                                 if (rawparfont !=
2955                                     cursor.par()->getFontSettings(bview->buffer()->params,
2956                                                                   cursor.par()->size() - 1))
2957                                         redoHeightOfParagraph(bview, cursor);
2958                                 return;
2959                         }
2960                 }
2961
2962                 // break the cursor row again
2963                 if (row->next() && row->next()->par() == row->par() &&
2964                     (rowLast(row) == row->par()->size() - 1 ||
2965                      nextBreakPoint(bview, row, workWidth(bview)) != rowLast(row))) {
2966
2967                         // it can happen that a paragraph loses one row
2968                         // without a real breakup. This is when a word
2969                         // is to long to be broken. Well, I don t care this
2970                         // hack ;-) 
2971                         if (rowLast(row) == row->par()->size() - 1)
2972                                 removeRow(row->next());
2973
2974                         refresh_y = y;
2975                         refresh_row = row;
2976                         status(bview, LyXText::NEED_MORE_REFRESH);
2977
2978                         breakAgainOneRow(bview, row);
2979                         // will the cursor be in another row now?
2980                         if (row->next() && row->next()->par() == row->par() &&
2981                             rowLast(row) <= cursor.pos()) {
2982                                 row = row->next();
2983                                 breakAgainOneRow(bview, row);
2984                         }
2985
2986                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2987
2988                         if (row->next() && row->next()->par() == row->par())
2989                                 need_break_row = row->next();
2990                         else
2991                                 need_break_row = 0;
2992                 } else  {
2993                         // set the dimensions of the row
2994                         row->fill(fill(bview, row, workWidth(bview)));
2995                         int const tmpheight = row->height();
2996                         setHeightOfRow(bview, row);
2997                         if (tmpheight == row->height())
2998                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2999                         else
3000                                 status(bview, LyXText::NEED_MORE_REFRESH);
3001                         refresh_y = y;
3002                         refresh_row = row;
3003                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3004                 }
3005         }
3006
3007         // current_font = rawtmpfont;
3008         // real_current_font = realtmpfont;
3009
3010         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
3011             != cursor.boundary())
3012                 setCursor(bview, cursor.par(), cursor.pos(), false,
3013                           !cursor.boundary());
3014
3015         lastpos = cursor.par()->size();
3016         if (cursor.pos() == lastpos)
3017                 setCurrentFont(bview);
3018
3019         // check, whether the last characters font has changed.
3020         if (rawparfont !=
3021             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
3022                 redoHeightOfParagraph(bview, cursor);
3023         } else {
3024                 // now the special right address boxes
3025                 if (textclasslist
3026                     [bview->buffer()->params.textclass]
3027                     [cursor.par()->layout()].margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3028                         redoDrawingOfParagraph(bview, cursor);
3029                 }
3030         }
3031 }
3032
3033
3034 bool LyXText::paintRowBackground(DrawRowParams & p)
3035 {
3036         bool clear_area = true;
3037         Inset * inset = 0;
3038         LyXFont font(LyXFont::ALL_SANE);
3039
3040         pos_type const last = rowLastPrintable(p.row);
3041
3042         if (!p.bv->screen()->forceClear() && last == p.row->pos()
3043                 && p.row->par()->isInset(p.row->pos())) {
3044                 inset = p.row->par()->getInset(p.row->pos());
3045                 if (inset) {
3046                         clear_area = inset->doClearArea();
3047                 }
3048         }
3049
3050         if (p.cleared) {
3051                 return true;
3052         }
3053
3054         if (clear_area) {
3055                 int const x = p.xo;
3056                 int const y = p.yo < 0 ? 0 : p.yo;
3057                 int const h = p.yo < 0 ? p.row->height() + p.yo : p.row->height();
3058                 p.pain->fillRectangle(x, y, p.width, h, backgroundColor());
3059                 return true;
3060         }
3061
3062         if (inset == 0)
3063                 return false;
3064
3065         int h = p.row->baseline() - inset->ascent(p.bv, font);
3066
3067         // first clear the whole row above the inset!
3068         if (h > 0) {
3069                 p.pain->fillRectangle(p.xo, p.yo, p.width, h, backgroundColor());
3070         }
3071
3072         // clear the space below the inset!
3073         h += inset->ascent(p.bv, font) + inset->descent(p.bv, font);
3074         if ((p.row->height() - h) > 0) {
3075                 p.pain->fillRectangle(p.xo, p.yo + h,
3076                         p.width, p.row->height() - h, backgroundColor());
3077         }
3078
3079         // clear the space behind the inset, if needed
3080         if (!inset->display() && !inset->needFullRow()) {
3081                 int const xp = int(p.x) + inset->width(p.bv, font);
3082                 if (p.width - xp > 0) {
3083                         p.pain->fillRectangle(xp, p.yo, p.width - xp,
3084                                 p.row->height(), backgroundColor());
3085                 }
3086         }
3087
3088         return false;
3089 }
3090
3091
3092 void LyXText::paintRowSelection(DrawRowParams & p)
3093 {
3094         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3095
3096         // the current selection
3097         int const startx = selection.start.x();
3098         int const endx = selection.end.x();
3099         int const starty = selection.start.y();
3100         int const endy = selection.end.y();
3101         Row const * startrow = selection.start.row();
3102         Row const * endrow = selection.end.row();
3103
3104         Row * row = p.row;
3105
3106         if (bidi_same_direction) {
3107                 int x;
3108                 int y = p.yo;
3109                 int w;
3110                 int h = row->height();
3111
3112                 if (startrow == row && endrow == row) {
3113                         if (startx < endx) {
3114                                 x = p.xo + startx;
3115                                 w = endx - startx;
3116                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3117                         } else {
3118                                 x = p.xo + endx;
3119                                 w = startx - endx;
3120                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3121                         }
3122                 } else if (startrow == row) {
3123                         int const x = (is_rtl) ? p.xo : (p.xo + startx);
3124                         int const w = (is_rtl) ? startx : (p.width - startx);
3125                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3126                 } else if (endrow == row) {
3127                         int const x = (is_rtl) ? (p.xo + endx) : p.xo;
3128                         int const w = (is_rtl) ? (p.width - endx) : endx;
3129                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3130                 } else if (p.y > starty && p.y < endy) {
3131                         p.pain->fillRectangle(p.xo, y, p.width, h, LColor::selection);
3132                 }
3133                 return;
3134         } else if (startrow != row && endrow != row) {
3135                 int w = p.width;
3136                 int h = row->height();
3137                 if (p.y > starty && p.y < endy) {
3138                         p.pain->fillRectangle(p.xo, p.yo, w, h, LColor::selection);
3139                 }
3140                 return;
3141         }
3142
3143         if (!((startrow != row && !is_rtl) || (endrow != row && is_rtl))) {
3144                 return;
3145         }
3146
3147         float tmpx = p.x;
3148
3149         p.pain->fillRectangle(p.xo, p.yo, int(p.x), row->height(), LColor::selection);
3150
3151         Buffer const * buffer = p.bv->buffer();
3152         Paragraph * par = row->par();
3153         pos_type main_body = beginningOfMainBody(buffer, par);
3154         pos_type const last = rowLastPrintable(row);
3155
3156         for (pos_type vpos = row->pos(); vpos <= last; ++vpos)  {
3157                 pos_type pos = vis2log(vpos);
3158                 float const old_tmpx = tmpx;
3159                 if (main_body > 0 && pos == main_body - 1) {
3160                         LyXLayout const & layout =
3161                                 textclasslist
3162                                 [buffer->params.textclass]
3163                                 [par->layout()];
3164                         LyXFont const lfont = getLabelFont(buffer, par);
3165
3166                         tmpx += p.label_hfill + font_metrics::width(layout.labelsep, lfont);
3167
3168                         if (par->isLineSeparator(main_body - 1))
3169                                 tmpx -= singleWidth(p.bv, par, main_body - 1);
3170                 }
3171
3172                 if (hfillExpansion(buffer, row, pos)) {
3173                         tmpx += singleWidth(p.bv, par, pos);
3174                         if (pos >= main_body)
3175                                 tmpx += p.hfill;
3176                         else
3177                                 tmpx += p.label_hfill;
3178                 }
3179
3180                 else if (par->isSeparator(pos)) {
3181                         tmpx += singleWidth(p.bv, par, pos);
3182                         if (pos >= main_body)
3183                                 tmpx += p.separator;
3184                 } else {
3185                         tmpx += singleWidth(p.bv, par, pos);
3186                 }
3187
3188                 if ((startrow != row || selection.start.pos() <= pos) &&
3189                         (endrow != row || pos < selection.end.pos())) {
3190                         // Here we do not use p.x as p.xo was added to p.x.
3191                         p.pain->fillRectangle(int(old_tmpx), p.yo,
3192                                 int(tmpx - old_tmpx + 1),
3193                                 row->height(), LColor::selection);
3194                 }
3195
3196                 if ((startrow != row && is_rtl) || (endrow != row && !is_rtl)) {
3197                         p.pain->fillRectangle(p.xo + int(tmpx),
3198                                 p.yo, int(p.bv->workWidth() - tmpx),
3199                                 row->height(), LColor::selection);
3200                 }
3201         }
3202 }
3203
3204
3205 void LyXText::paintRowAppendix(DrawRowParams & p)
3206 {
3207         // FIXME: can be just p.width ?
3208         int const ww = p.bv->workWidth();
3209         Paragraph * firstpar = p.row->par();
3210
3211         if (firstpar->params().appendix()) {
3212                 p.pain->line(1, p.yo, 1, p.yo + p.row->height(), LColor::appendixline);
3213                 p.pain->line(ww - 2, p.yo, ww - 2, p.yo + p.row->height(), LColor::appendixline);
3214         }
3215 }
3216
3217
3218 void LyXText::paintRowDepthBar(DrawRowParams & p)
3219 {
3220         Paragraph::depth_type const depth = p.row->par()->getDepth();
3221
3222         if (depth <= 0)
3223                 return;
3224
3225         Paragraph::depth_type prev_depth = 0;
3226         if (p.row->previous())
3227                 prev_depth = p.row->previous()->par()->getDepth();
3228         Paragraph::depth_type next_depth = 0;
3229         if (p.row->next())
3230                 next_depth = p.row->next()->par()->getDepth();
3231
3232         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3233                 int const x = (LYX_PAPER_MARGIN / 5) * i + p.xo;
3234                 int const h = p.yo + p.row->height() - 1 - (i - next_depth - 1) * 3;
3235
3236                 p.pain->line(x, p.yo, x, h, LColor::depthbar);
3237
3238                 int const w = LYX_PAPER_MARGIN / 5;
3239
3240                 if (i > prev_depth) {
3241                         p.pain->fillRectangle(x, p.yo, w, 2, LColor::depthbar);
3242                 }
3243                 if (i > next_depth) {
3244                         p.pain->fillRectangle(x, h, w, 2, LColor::depthbar);
3245                 }
3246         }
3247 }
3248
3249
3250 int LyXText::getLengthMarkerHeight(BufferView * bv, VSpace const & vsp) const
3251 {
3252         int const arrow_size = 4;
3253         int const space_size = int(vsp.inPixels(bv));
3254
3255         if (vsp.kind() != VSpace::LENGTH) {
3256                 return space_size;
3257         }
3258
3259         LyXFont font;
3260         font.decSize();
3261         int const min_size = max(3 * arrow_size,
3262                                       font_metrics::maxAscent(font)
3263                                       + font_metrics::maxDescent(font));
3264
3265         if (vsp.length().len().value() < 0.0)
3266                 return min_size;
3267         else
3268                 return max(min_size, space_size);
3269 }
3270
3271
3272 int LyXText::drawLengthMarker(DrawRowParams & p, string const & prefix,
3273                               VSpace const & vsp, int start)
3274 {
3275         int const arrow_size = 4;
3276         int const size = getLengthMarkerHeight(p.bv, vsp);
3277         int const end = start + size;
3278
3279         // the label to display (if any)
3280         string str;
3281         // y-values for top arrow
3282         int ty1, ty2;
3283         // y-values for bottom arrow
3284         int by1, by2;
3285         switch (vsp.kind()) {
3286         case VSpace::LENGTH:
3287         {
3288                 str = prefix + " (" + vsp.asLyXCommand() + ")";
3289                 // adding or removing space
3290                 bool const added = !(vsp.length().len().value() < 0.0);
3291                 ty1 = added ? (start + arrow_size) : start;
3292                 ty2 = added ? start : (start + arrow_size);
3293                 by1 = added ? (end - arrow_size) : end;
3294                 by2 = added ? end : (end - arrow_size);
3295                 break;
3296         }
3297         case VSpace:: VFILL:
3298                 str = prefix + " (vertical fill)";
3299                 ty1 = ty2 = start;
3300                 by1 = by2 = end;
3301                 break;
3302         default:
3303                 // nothing to draw here
3304                 return size;
3305         }
3306
3307         int const leftx = p.xo + leftMargin(p.bv, p.row);
3308         int const midx = leftx + arrow_size;
3309         int const rightx = midx + arrow_size;
3310
3311         // first the string
3312         int w = 0;
3313         int a = 0;
3314         int d = 0;
3315
3316         LyXFont font;
3317         font.setColor(LColor::added_space).decSize();
3318         font_metrics::rectText(str, font, w, a, d);
3319
3320         p.pain->rectText(leftx + 2 * arrow_size + 5,
3321                          start + ((end - start) / 2) + d,
3322                          str, font,
3323                          backgroundColor(),
3324                          backgroundColor());
3325
3326         // top arrow
3327         p.pain->line(leftx, ty1, midx, ty2, LColor::added_space);
3328         p.pain->line(midx, ty2, rightx, ty1, LColor::added_space);
3329
3330         // bottom arrow
3331         p.pain->line(leftx, by1, midx, by2, LColor::added_space);
3332         p.pain->line(midx, by2, rightx, by1, LColor::added_space);
3333
3334         // joining line
3335         p.pain->line(midx, ty2, midx, by2, LColor::added_space);
3336
3337         return size;
3338 }
3339
3340
3341 void LyXText::paintFirstRow(DrawRowParams & p)
3342 {
3343         Paragraph * par = p.row->par();
3344         ParagraphParameters const & parparams = par->params();
3345
3346         // start of appendix?
3347         if (parparams.startOfAppendix()) {
3348                 p.pain->line(1, p.yo, p.width - 2, p.yo, LColor::appendixline);
3349         }
3350
3351         int y_top = 0;
3352
3353         // think about the margins
3354         if (!p.row->previous() && bv_owner)
3355                 y_top += LYX_PAPER_MARGIN;
3356
3357         // draw a top pagebreak
3358         if (parparams.pagebreakTop()) {
3359                 int const y = p.yo + y_top + 2*defaultHeight();
3360                 p.pain->line(p.xo, y, p.xo + p.width, y,
3361                         LColor::pagebreak, Painter::line_onoffdash);
3362
3363                 int w = 0;
3364                 int a = 0;
3365                 int d = 0;
3366
3367                 LyXFont pb_font;
3368                 pb_font.setColor(LColor::pagebreak).decSize();
3369                 font_metrics::rectText(_("Page Break (top)"), pb_font, w, a, d);
3370                 p.pain->rectText((p.width - w)/2, y + d,
3371                               _("Page Break (top)"), pb_font,
3372                               backgroundColor(),
3373                               backgroundColor());
3374                 y_top += 3 * defaultHeight();
3375         }
3376
3377         // draw the additional space if needed:
3378         y_top += drawLengthMarker(p, _("Space above"),
3379                                   parparams.spaceTop(), p.yo + y_top);
3380
3381         Buffer const * buffer = p.bv->buffer();
3382
3383         LyXTextClass const & tclass = textclasslist[buffer->params.textclass];
3384         LyXLayout const & layout = tclass[par->layout()];
3385
3386         // think about the parskip
3387         // some parskips VERY EASY IMPLEMENTATION
3388         if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3389                 if (par->previous()) {
3390                         if (layout.latextype == LATEX_PARAGRAPH
3391                                 && !par->getDepth()) {
3392                                 y_top += buffer->params.getDefSkip().inPixels(p.bv);
3393                         } else {
3394                                 LyXLayout const & playout =
3395                                         tclass[par->previous()->layout()];
3396                                 if (playout.latextype == LATEX_PARAGRAPH
3397                                         && !par->previous()->getDepth()) {
3398                                         // is it right to use defskip here, too? (AS)
3399                                         y_top += buffer->params.getDefSkip().inPixels(p.bv);
3400                                 }
3401                         }
3402                 }
3403         }
3404
3405         int const ww = p.bv->workWidth();
3406
3407         // draw a top line
3408         if (parparams.lineTop()) {
3409                 LyXFont font(LyXFont::ALL_SANE);
3410                 int const asc = font_metrics::ascent('x', getFont(buffer, par, 0));
3411
3412                 y_top += asc;
3413
3414                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3415                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3416                 p.pain->line(xp, p.yo + y_top, xp + w, p.yo + y_top,
3417                         LColor::topline, Painter::line_solid,
3418                         Painter::line_thick);
3419
3420                 y_top += asc;
3421         }
3422
3423         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3424
3425         // should we print a label?
3426         if (layout.labeltype >= LABEL_STATIC
3427             && (layout.labeltype != LABEL_STATIC
3428                 || layout.latextype != LATEX_ENVIRONMENT
3429                 || par->isFirstInSequence())) {
3430
3431                 LyXFont font = getLabelFont(buffer, par);
3432                 if (!par->getLabelstring().empty()) {
3433                         float x = p.x;
3434                         string const str = par->getLabelstring();
3435
3436                         // this is special code for the chapter layout. This is
3437                         // printed in an extra row and has a pagebreak at
3438                         // the top.
3439                         if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3440                                 if (buffer->params.secnumdepth >= 0) {
3441                                         float spacing_val = 1.0;
3442                                         if (!parparams.spacing().isDefault()) {
3443                                                 spacing_val = parparams.spacing().getValue();
3444                                         } else {
3445                                                 spacing_val = buffer->params.spacing.getValue();
3446                                         }
3447
3448                                         int const maxdesc =
3449                                                 int(font_metrics::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3450                                                 + int(layout.parsep) * defaultHeight();
3451
3452                                         if (is_rtl) {
3453                                                 x = ww - leftMargin(p.bv, p.row) -
3454                                                         font_metrics::width(str, font);
3455                                         }
3456
3457                                         p.pain->text(int(x),
3458                                                 p.yo + p.row->baseline() -
3459                                                 p.row->ascent_of_text() - maxdesc,
3460                                                 str, font);
3461                                 }
3462                         } else {
3463                                 if (is_rtl) {
3464                                         x = ww - leftMargin(p.bv, p.row)
3465                                                 + font_metrics::width(layout.labelsep, font);
3466                                 } else {
3467                                         x = p.x - font_metrics::width(layout.labelsep, font)
3468                                                 - font_metrics::width(str, font);
3469                                 }
3470
3471                                 p.pain->text(int(x), p.yo + p.row->baseline(), str, font);
3472                         }
3473                 }
3474         // the labels at the top of an environment.
3475         // More or less for bibliography
3476         } else if (par->isFirstInSequence() &&
3477                 (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3478                 layout.labeltype == LABEL_BIBLIO ||
3479                 layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
3480                 LyXFont font = getLabelFont(buffer, par);
3481                 if (!par->getLabelstring().empty()) {
3482                         string const str = par->getLabelstring();
3483                         float spacing_val = 1.0;
3484                         if (!parparams.spacing().isDefault()) {
3485                                 spacing_val = parparams.spacing().getValue();
3486                         } else {
3487                                 spacing_val = buffer->params.spacing.getValue();
3488                         }
3489
3490                         int maxdesc =
3491                                 int(font_metrics::maxDescent(font) * layout.spacing.getValue() * spacing_val
3492                                 + (layout.labelbottomsep * defaultHeight()));
3493
3494                         float x = p.x;
3495                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3496                                 x = ((is_rtl ? leftMargin(p.bv, p.row) : p.x)
3497                                          + ww - rightMargin(buffer, p.row)) / 2;
3498                                 x -= font_metrics::width(str, font) / 2;
3499                         } else if (is_rtl) {
3500                                 x = ww - leftMargin(p.bv, p.row) -
3501                                         font_metrics::width(str, font);
3502                         }
3503                         p.pain->text(int(x), p.yo + p.row->baseline()
3504                                   - p.row->ascent_of_text() - maxdesc,
3505                                   str, font);
3506                 }
3507         }
3508
3509         if (layout.labeltype == LABEL_BIBLIO && par->bibkey) {
3510                 LyXFont font = getLayoutFont(buffer, par);
3511                 float x;
3512                 if (is_rtl) {
3513                         x = ww - leftMargin(p.bv, p.row)
3514                                 + font_metrics::width(layout.labelsep, font);
3515                 } else {
3516                         x = p.x - font_metrics::width(layout.labelsep, font)
3517                                 - par->bibkey->width(p.bv, font);
3518                 }
3519                 par->bibkey->draw(p.bv, font, p.yo + p.row->baseline(), x, p.cleared);
3520         }
3521 }
3522
3523
3524 void LyXText::paintLastRow(DrawRowParams & p)
3525 {
3526         Paragraph * par = p.row->par();
3527         ParagraphParameters const & parparams = par->params();
3528         int y_bottom = p.row->height() - 1;
3529
3530         // think about the margins
3531         if (!p.row->next() && bv_owner)
3532                 y_bottom -= LYX_PAPER_MARGIN;
3533
3534         int const ww = p.bv->workWidth();
3535
3536         // draw a bottom pagebreak
3537         if (parparams.pagebreakBottom()) {
3538                 LyXFont pb_font;
3539                 pb_font.setColor(LColor::pagebreak).decSize();
3540                 int const y = p.yo + y_bottom - 2 * defaultHeight();
3541
3542                 p.pain->line(p.xo, y, p.xo + p.width, y, LColor::pagebreak,
3543                              Painter::line_onoffdash);
3544
3545                 int w = 0;
3546                 int a = 0;
3547                 int d = 0;
3548                 font_metrics::rectText(_("Page Break (bottom)"), pb_font, w, a, d);
3549                 p.pain->rectText((ww - w) / 2, y + d,
3550                         _("Page Break (bottom)"),
3551                         pb_font, backgroundColor(), backgroundColor());
3552
3553                 y_bottom -= 3 * defaultHeight();
3554         }
3555
3556         // draw the additional space if needed:
3557         int const height =  getLengthMarkerHeight(p.bv,
3558                                                   parparams.spaceBottom());
3559         y_bottom -= drawLengthMarker(p, _("Space below"),
3560                                      parparams.spaceBottom(),
3561                                      p.yo + y_bottom - height);
3562
3563         Buffer const * buffer = p.bv->buffer();
3564
3565         // draw a bottom line
3566         if (parparams.lineBottom()) {
3567                 LyXFont font(LyXFont::ALL_SANE);
3568                 int const asc = font_metrics::ascent('x',
3569                         getFont(buffer, par,
3570                         max(pos_type(0), par->size() - 1)));
3571
3572                 y_bottom -= asc;
3573
3574                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3575                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3576                 int const y = p.yo + y_bottom;
3577                 p.pain->line(xp, y, xp + w, y, LColor::topline, Painter::line_solid,
3578                           Painter::line_thick);
3579
3580                 y_bottom -= asc;
3581         }
3582
3583         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3584         int const endlabel = par->getEndLabel(buffer->params);
3585
3586         // draw an endlabel
3587         switch (endlabel) {
3588         case END_LABEL_BOX:
3589         case END_LABEL_FILLED_BOX:
3590         {
3591                 LyXFont const font = getLabelFont(buffer, par);
3592                 int const size = int(0.75 * font_metrics::maxAscent(font));
3593                 int const y = (p.yo + p.row->baseline()) - size;
3594                 int x = is_rtl ? LYX_PAPER_MARGIN : ww - LYX_PAPER_MARGIN - size;
3595
3596                 if (p.row->fill() <= size)
3597                         x += (size - p.row->fill() + 1) * (is_rtl ? -1 : 1);
3598
3599                 if (endlabel == END_LABEL_BOX) {
3600                         p.pain->rectangle(x, y, size, size, LColor::eolmarker);
3601                 } else {
3602                         p.pain->fillRectangle(x, y, size, size,
3603                                               LColor::eolmarker);
3604                 }
3605                 break;
3606         }
3607         case END_LABEL_STATIC:
3608         {
3609                 LyXFont font(LyXFont::ALL_SANE);
3610                 string const & layout = par->layout();
3611                 string const str = textclasslist[buffer->params.textclass][layout].endlabelstring();
3612                 font = getLabelFont(buffer, par);
3613                 int const x = is_rtl ?
3614                         int(p.x) - font_metrics::width(str, font)
3615                         : ww - rightMargin(buffer, p.row) - p.row->fill();
3616                 p.pain->text(x, p.yo + p.row->baseline(), str, font);
3617                 break;
3618         }
3619         case END_LABEL_NO_LABEL:
3620                 break;
3621         }
3622 }
3623
3624 void LyXText::paintRowText(DrawRowParams & p)
3625 {
3626         Paragraph * par = p.row->par();
3627         Buffer const * buffer = p.bv->buffer();
3628
3629         pos_type const last = rowLastPrintable(p.row);
3630         pos_type main_body =
3631                 beginningOfMainBody(buffer, par);
3632         if (main_body > 0 &&
3633                 (main_body - 1 > last ||
3634                 !par->isLineSeparator(main_body - 1))) {
3635                 main_body = 0;
3636         }
3637
3638         LyXLayout const & layout =
3639                 textclasslist[buffer->params.textclass][par->layout()];
3640
3641         pos_type vpos = p.row->pos();
3642         while (vpos <= last) {
3643                 if (p.x > p.bv->workWidth())
3644                         break;
3645                 pos_type pos = vis2log(vpos);
3646                 if (p.x + singleWidth(p.bv, par, pos) < 0) {
3647                         p.x += singleWidth(p.bv, par, pos);
3648                         ++vpos;
3649                         continue;
3650                 }
3651                 if (main_body > 0 && pos == main_body - 1) {
3652                         int const lwidth = font_metrics::width(layout.labelsep,
3653                                 getLabelFont(buffer, par));
3654
3655                         p.x += p.label_hfill + lwidth
3656                                 - singleWidth(p.bv, par, main_body - 1);
3657                 }
3658
3659                 if (par->isHfill(pos)) {
3660                         p.x += 1;
3661
3662                         int const y0 = p.yo + p.row->baseline();
3663                         int const y1 = y0 - defaultHeight() / 2;
3664
3665                         p.pain->line(int(p.x), y1, int(p.x), y0,
3666                                      LColor::added_space);
3667
3668                         if (hfillExpansion(buffer, p.row, pos)) {
3669                                 int const y2 = (y0 + y1) / 2;
3670
3671                                 if (pos >= main_body) {
3672                                         p.pain->line(int(p.x), y2,
3673                                                   int(p.x + p.hfill), y2,
3674                                                   LColor::added_space,
3675                                                   Painter::line_onoffdash);
3676                                         p.x += p.hfill;
3677                                 } else {
3678                                         p.pain->line(int(p.x), y2,
3679                                                   int(p.x + p.label_hfill), y2,
3680                                                   LColor::added_space,
3681                                                   Painter::line_onoffdash);
3682                                         p.x += p.label_hfill;
3683                                 }
3684                                 p.pain->line(int(p.x), y1,
3685                                              int(p.x), y0,
3686                                              LColor::added_space);
3687                         }
3688                         p.x += 2;
3689                         ++vpos;
3690                 } else if (par->isSeparator(pos)) {
3691                         p.x += singleWidth(p.bv, par, pos);
3692                         if (pos >= main_body)
3693                                 p.x += p.separator;
3694                         ++vpos;
3695                 } else {
3696                         if (!draw(p, vpos))
3697                                 break;
3698                 }
3699         }
3700 }
3701
3702
3703 void LyXText::getVisibleRow(BufferView * bv, int y_offset, int x_offset,
3704                             Row * row, int y, bool cleared)
3705 {
3706         if (row->height() <= 0) {
3707                 lyxerr << "LYX_ERROR: row.height: "
3708                        << row->height() << endl;
3709                 return;
3710         }
3711
3712         DrawRowParams p;
3713
3714         // set up drawing parameters
3715         p.bv = bv;
3716         p.pain = &bv->painter();
3717         p.row = row;
3718         p.xo = x_offset;
3719         p.yo = y_offset;
3720         prepareToPrint(bv, row, p.x, p.separator, p.hfill, p.label_hfill);
3721         if (inset_owner && (p.x < 0))
3722                 p.x = 0;
3723         p.x += p.xo;
3724         p.y = y;
3725         p.width = inset_owner ? inset_owner->textWidth(bv, true) : bv->workWidth();
3726         p.cleared = cleared;
3727
3728         // start painting
3729
3730         // clear to background if necessary
3731         p.cleared = paintRowBackground(p);
3732
3733         // paint the selection background
3734         if (selection.set()) {
3735                 paintRowSelection(p);
3736         }
3737
3738         // vertical lines for appendix
3739         paintRowAppendix(p);
3740
3741         // environment depth brackets
3742         paintRowDepthBar(p);
3743
3744         // draw any stuff wanted for a first row of a paragraph
3745         if (!row->pos()) {
3746                 paintFirstRow(p);
3747         }
3748
3749         // draw any stuff wanted for the last row of a paragraph
3750         if (!row->next() || (row->next()->par() != row->par())) {
3751                 paintLastRow(p);
3752         }
3753
3754         // paint text
3755         paintRowText(p);
3756 }
3757
3758
3759 int LyXText::defaultHeight() const
3760 {
3761         LyXFont font(LyXFont::ALL_SANE);
3762         return int(font_metrics::maxAscent(font)
3763                  + font_metrics::maxDescent(font) * 1.5);
3764 }
3765
3766
3767 // returns the column near the specified x-coordinate of the row
3768 // x is set to the real beginning of this column 
3769 pos_type
3770 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3771                         bool & boundary) const
3772 {
3773         float tmpx = 0.0;
3774         float fill_separator;
3775         float fill_hfill;
3776         float fill_label_hfill;
3777
3778         prepareToPrint(bview, row, tmpx, fill_separator,
3779                        fill_hfill, fill_label_hfill);
3780
3781         pos_type vc = row->pos();
3782         pos_type last = rowLastPrintable(row);
3783         pos_type c = 0;
3784         LyXLayout const & layout =
3785                 textclasslist[bview->buffer()->params.textclass][
3786                                     row->par()->layout()];
3787         bool left_side = false;
3788
3789         pos_type main_body = beginningOfMainBody(bview->buffer(), row->par());
3790         float last_tmpx = tmpx;
3791
3792         if (main_body > 0 &&
3793             (main_body - 1 > last ||
3794              !row->par()->isLineSeparator(main_body - 1)))
3795                 main_body = 0;
3796
3797         while (vc <= last && tmpx <= x) {
3798                 c = vis2log(vc);
3799                 last_tmpx = tmpx;
3800                 if (main_body > 0 && c == main_body-1) {
3801                         tmpx += fill_label_hfill +
3802                                 font_metrics::width(layout.labelsep,
3803                                                getLabelFont(bview->buffer(), row->par()));
3804                         if (row->par()->isLineSeparator(main_body - 1))
3805                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3806                 }
3807
3808                 if (hfillExpansion(bview->buffer(), row, c)) {
3809                         x += singleWidth(bview, row->par(), c);
3810                         if (c >= main_body)
3811                                 tmpx += fill_hfill;
3812                         else
3813                                 tmpx += fill_label_hfill;
3814                 }
3815                 else if (row->par()->isSeparator(c)) {
3816                         tmpx += singleWidth(bview, row->par(), c);
3817                         if (c >= main_body)
3818                                 tmpx+= fill_separator;
3819                 } else
3820                         tmpx += singleWidth(bview, row->par(), c);
3821                 ++vc;
3822         }
3823
3824         if ((tmpx + last_tmpx) / 2 > x) {
3825                 tmpx = last_tmpx;
3826                 left_side = true;
3827         }
3828
3829         if (vc > last + 1)  // This shouldn't happen.
3830                 vc = last + 1;
3831
3832         boundary = false;
3833         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3834                                          // some speedup if rtl_support=false
3835                 && (!row->next() || row->next()->par() != row->par());
3836         bool const rtl = (lastrow)
3837                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3838                 : false; // If lastrow is false, we don't need to compute
3839                          // the value of rtl.
3840
3841         if (row->pos() > last)  // Row is empty?
3842                 c = row->pos();
3843         else if (lastrow &&
3844                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3845                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
3846                 c = last + 1;
3847         else if (vc == row->pos()) {
3848                 c = vis2log(vc);
3849                 if (bidi_level(c) % 2 == 1)
3850                         ++c;
3851         } else {
3852                 c = vis2log(vc - 1);
3853                 bool const rtl = (bidi_level(c) % 2 == 1);
3854                 if (left_side == rtl) {
3855                         ++c;
3856                         boundary = isBoundary(bview->buffer(), row->par(), c);
3857                 }
3858         }
3859
3860         if (row->pos() <= last && c > last
3861             && row->par()->isNewline(last)) {
3862                 if (bidi_level(last) % 2 == 0)
3863                         tmpx -= singleWidth(bview, row->par(), last);
3864                 else
3865                         tmpx += singleWidth(bview, row->par(), last);
3866                 c = last;
3867         }
3868
3869         c -= row->pos();
3870         x = int(tmpx);
3871         return c;
3872 }
3873
3874
3875 // returns pointer to a specified row
3876 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
3877 {
3878         if (!firstrow)
3879                 return 0;
3880
3881         Row * tmprow = firstrow;
3882         y = 0;
3883
3884         // find the first row of the specified paragraph
3885         while (tmprow->next() && tmprow->par() != par) {
3886                 y += tmprow->height();
3887                 tmprow = tmprow->next();
3888         }
3889
3890         // now find the wanted row
3891         while (tmprow->pos() < pos
3892                && tmprow->next()
3893                && tmprow->next()->par() == par
3894                && tmprow->next()->pos() <= pos) {
3895                 y += tmprow->height();
3896                 tmprow = tmprow->next();
3897         }
3898
3899         return tmprow;
3900 }
3901
3902
3903 Row * LyXText::getRowNearY(int & y) const
3904 {
3905 #if 1
3906         // If possible we should optimize this method. (Lgb)
3907         Row * tmprow = firstrow;
3908         int tmpy = 0;
3909
3910         while (tmprow->next() && tmpy + tmprow->height() <= y) {
3911                 tmpy += tmprow->height();
3912                 tmprow = tmprow->next();
3913         }
3914
3915         y = tmpy;   // return the real y
3916
3917         //lyxerr << "returned y = " << y << endl;
3918
3919         return tmprow;
3920 #else
3921         // Search from the current cursor position.
3922
3923         Row * tmprow = cursor.row();
3924         int tmpy = cursor.y() - tmprow->baseline();
3925
3926         lyxerr << "cursor.y() = " << tmpy << endl;
3927         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
3928         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
3929         lyxerr << "first = " << first << endl;
3930         lyxerr << "y = " << y << endl;
3931
3932         if (y < tmpy) {
3933                 lyxerr << "up" << endl;
3934 #if 0
3935                 while (tmprow && tmpy - tmprow->height() >= y) {
3936                         tmpy -= tmprow->height();
3937                         tmprow = tmprow->previous();
3938                 }
3939 #else
3940                 do {
3941                         tmpy -= tmprow->height();
3942                         tmprow = tmprow->previous();
3943                 } while (tmprow && tmpy - tmprow->height() >= y);
3944 #endif
3945         } else if (y > tmpy) {
3946                 lyxerr << "down" << endl;
3947
3948                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
3949                         tmpy += tmprow->height();
3950                         tmprow = tmprow->next();
3951                 }
3952         } else {
3953                 lyxerr << "equal" << endl;
3954         }
3955
3956         y = tmpy; // return the real y
3957
3958         lyxerr << "returned y = " << y << endl;
3959
3960         return tmprow;
3961
3962 #endif
3963 }
3964
3965
3966 int LyXText::getDepth() const
3967 {
3968         return cursor.par()->getDepth();
3969 }