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