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