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