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