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