]> git.lyx.org Git - lyx.git/blob - src/text.C
f86a5b68742f23fe8fd1bb2aaba73771a9700a70
[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                         if (cursor.pos() == 0 )
1782                                 bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1783                         else
1784                                 bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1785                         charInserted();
1786                         return;
1787                 }
1788         } else if (IsNewlineChar(c)) {
1789                 if (cursor.par() == cursor.par()
1790                     && cursor.pos() <= BeginningOfMainBody(bview->buffer(), cursor.par())) {
1791                         charInserted();
1792                         return;
1793                 }
1794                 /* No newline at first position 
1795                  * of a paragraph or behind labels. 
1796                  * TeX does not allow that. */
1797
1798                 if (cursor.pos() < cursor.par()->size() &&
1799                     cursor.par()->IsLineSeparator(cursor.pos()))
1800                         // newline always after a blank!
1801                         CursorRight(bview);
1802                 cursor.row()->fill(-1);        // to force a new break
1803         }
1804    
1805         // the display inset stuff
1806         if (cursor.row()->par()->GetChar(cursor.row()->pos()) == LyXParagraph::META_INSET
1807             && cursor.row()->par()->GetInset(cursor.row()->pos())
1808             && (cursor.row()->par()->GetInset(cursor.row()->pos())->display() ||
1809                 cursor.row()->par()->GetInset(cursor.row()->pos())->needFullRow()))
1810                 cursor.row()->fill(-1); // to force a new break  
1811
1812         // get the cursor row fist
1813         Row * row = cursor.row();
1814         int y = cursor.y() - row->baseline();
1815         if (c != LyXParagraph::META_INSET) /* Here case LyXText::InsertInset 
1816                                             * already insertet the character */
1817                 cursor.par()->InsertChar(cursor.pos(), c);
1818         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1819
1820         if (!jumped_over_space) {
1821                 // refresh the positions
1822                 Row * tmprow = row;
1823                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1824                         tmprow = tmprow->next();
1825                         tmprow->pos(tmprow->pos() + 1);
1826                 }
1827         }
1828    
1829         // Is there a break one row above
1830         if ((cursor.par()->IsLineSeparator(cursor.pos())
1831              || cursor.par()->IsNewline(cursor.pos())
1832              || cursor.row()->fill() == -1)
1833             && row->previous() && row->previous()->par() == row->par()) {
1834                 LyXParagraph::size_type z = NextBreakPoint(bview,
1835                                                            row->previous(),
1836                                                            workWidth(bview));
1837                 if (z >= row->pos()) {
1838                         row->pos(z + 1);
1839                         
1840                         // set the dimensions of the row above
1841                         row->previous()->fill(Fill(bview,
1842                                                    row->previous(),
1843                                                    workWidth(bview)));
1844
1845                         SetHeightOfRow(bview, row->previous());
1846              
1847                         y -= row->previous()->height();
1848                         refresh_y = y;
1849                         refresh_row = row->previous();
1850                         status = LyXText::NEED_MORE_REFRESH;
1851              
1852                         BreakAgainOneRow(bview, row);
1853
1854                         current_font = rawtmpfont;
1855                         real_current_font = realtmpfont;
1856                         SetCursor(bview, cursor.par(), cursor.pos() + 1,
1857                                   false, cursor.boundary());
1858                         // cursor MUST be in row now.
1859              
1860                         if (row->next() && row->next()->par() == row->par())
1861                                 need_break_row = row->next();
1862                         else
1863                                 need_break_row = 0;
1864              
1865                         // check, wether the last characters font has changed.
1866                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1867                             && rawparfont != rawtmpfont)
1868                                 RedoHeightOfParagraph(bview, cursor);
1869                         
1870                         charInserted();
1871                         return;
1872                 }
1873         }
1874    
1875         // recalculate the fill of the row
1876         if (row->fill() >= 0)  /* needed because a newline
1877                               * will set fill to -1. Otherwise
1878                               * we would not get a rebreak! */
1879                 row->fill(Fill(bview, row, workWidth(bview)));
1880         if (row->fill() < 0) {
1881                 refresh_y = y;
1882                 refresh_row = row; 
1883                 refresh_x = cursor.x();
1884                 refresh_pos = cursor.pos();
1885                 status = LyXText::NEED_MORE_REFRESH;
1886                 BreakAgainOneRow(bview, row); 
1887                 // will the cursor be in another row now?
1888                 if (RowLast(row) <= cursor.pos() + 1 && row->next()) {
1889                         if (row->next() && row->next()->par() == row->par())
1890                                 // this should always be true
1891                                 row = row->next();
1892                         BreakAgainOneRow(bview, row);
1893                 }
1894                 current_font = rawtmpfont;
1895                 real_current_font = realtmpfont;
1896
1897                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
1898                           cursor.boundary());
1899                 if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos())
1900                     != cursor.boundary())
1901                         SetCursor(bview, cursor.par(), cursor.pos(), false,
1902                           !cursor.boundary());
1903                 if (row->next() && row->next()->par() == row->par())
1904                         need_break_row = row->next();
1905                 else
1906                         need_break_row = 0;             
1907         } else {
1908                 refresh_y = y;
1909                 refresh_x = cursor.x();
1910                 refresh_row = row;
1911                 refresh_pos = cursor.pos();
1912                 
1913                 int const tmpheight = row->height();
1914                 SetHeightOfRow(bview, row);
1915                 if (tmpheight == row->height())
1916                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
1917                 else
1918                         status = LyXText::NEED_MORE_REFRESH;
1919             
1920                 current_font = rawtmpfont;
1921                 real_current_font = realtmpfont;
1922                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
1923                           cursor.boundary());
1924         }
1925
1926         // check, wether the last characters font has changed.
1927         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1928             && rawparfont != rawtmpfont) {
1929                 RedoHeightOfParagraph(bview, cursor);
1930         } else {
1931                 // now the special right address boxes
1932                 if (textclasslist.Style(bview->buffer()->params.textclass,
1933                                    cursor.par()->GetLayout()).margintype
1934                     == MARGIN_RIGHT_ADDRESS_BOX) {
1935                         RedoDrawingOfParagraph(bview, cursor); 
1936                 }
1937         }
1938
1939         charInserted();
1940 }
1941    
1942
1943 void LyXText::charInserted()
1944 {
1945         // Here we could call FinishUndo for every 20 characters inserted.
1946         // This is from my experience how emacs does it.
1947         static unsigned int counter = 0;
1948         if (counter < 20) {
1949                 ++counter;
1950         } else {
1951                 FinishUndo();
1952                 counter = 0;
1953         }
1954 }
1955
1956
1957 void LyXText::PrepareToPrint(BufferView * bview,
1958                              Row * row, float & x,
1959                              float & fill_separator, 
1960                              float & fill_hfill,
1961                              float & fill_label_hfill,
1962                              bool bidi) const
1963 {
1964         float nlh, ns;
1965         
1966         float w = row->fill();
1967         fill_hfill = 0;
1968         fill_label_hfill = 0;
1969         fill_separator = 0;
1970         fill_label_hfill = 0;
1971
1972         bool const is_rtl =
1973                 row->par()->isRightToLeftPar(bview->buffer()->params);
1974         if (is_rtl) {
1975                 x = (workWidth(bview) > 0)
1976                         ? RightMargin(bview->buffer(), row) : 0;
1977         } else
1978                 x = (workWidth(bview) > 0) ? LeftMargin(bview, row) : 0;
1979         
1980         // is there a manual margin with a manual label
1981         if (textclasslist.Style(bview->buffer()->params.textclass,
1982                            row->par()->GetLayout()).margintype == MARGIN_MANUAL
1983             && textclasslist.Style(bview->buffer()->params.textclass,
1984                               row->par()->GetLayout()).labeltype == LABEL_MANUAL) {
1985                
1986                 /* one more since labels are left aligned */ 
1987                 nlh = NumberOfLabelHfills(bview->buffer(), row) + 1;
1988                 if (nlh && !row->par()->GetLabelWidthString().empty()) {
1989                         fill_label_hfill = LabelFill(bview, row) / nlh;
1990                 }
1991         }
1992                 
1993         // are there any hfills in the row?
1994         float const nh = NumberOfHfills(bview->buffer(), row);
1995
1996         if (nh)
1997           fill_hfill = w / nh;
1998         else  {
1999                 // is it block, flushleft or flushright? 
2000                 // set x how you need it
2001         int align;
2002         if (row->par()->params.align() == LYX_ALIGN_LAYOUT)
2003           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
2004         else
2005           align = row->par()->params.align();
2006            
2007         // center displayed insets 
2008         Inset * inset;
2009            if (row->par()->GetChar(row->pos()) == LyXParagraph::META_INSET
2010                && (inset=row->par()->GetInset(row->pos()))
2011                && (inset->display())) // || (inset->scroll() < 0)))
2012              align = (inset->LyxCode() == Inset::MATHMACRO_CODE)
2013                      ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2014
2015            switch (align) {
2016             case LYX_ALIGN_BLOCK:
2017               ns = NumberOfSeparators(bview->buffer(), row);
2018               if (ns && row->next() && row->next()->par() == row->par() &&
2019                   !(row->next()->par()->IsNewline(row->next()->pos() - 1))
2020                   && !(row->next()->par()->GetChar(row->next()->pos()) == LyXParagraph::META_INSET
2021                        && row->next()->par()->GetInset(row->next()->pos())
2022                        && row->next()->par()->GetInset(row->next()->pos())->display())
2023                   )
2024                 fill_separator = w / ns;
2025               else if (is_rtl)
2026                 x += w;
2027               break;
2028             case LYX_ALIGN_RIGHT:
2029               x += w;
2030               break;
2031             case LYX_ALIGN_CENTER:
2032               x += w / 2;
2033               break;
2034            }
2035         }
2036         if (!bidi)
2037                 return;
2038
2039         ComputeBidiTables(bview->buffer(), row);
2040         if (is_rtl) {
2041                 LyXParagraph::size_type main_body = 
2042                         BeginningOfMainBody(bview->buffer(), row->par());
2043                 LyXParagraph::size_type last = RowLast(row);
2044
2045                 if (main_body > 0 &&
2046                     (main_body-1 > last || 
2047                      !row->par()->IsLineSeparator(main_body-1))) {
2048                         LyXLayout const & layout =
2049                                 textclasslist.Style(bview->buffer()->params.textclass,
2050                                                     row->par()->GetLayout());
2051                         x += lyxfont::width(layout.labelsep,
2052                                             GetFont(bview->buffer(), row->par(), -2));
2053                         if (main_body-1 <= last)
2054                                 x += fill_label_hfill;
2055                 }
2056         }
2057 }
2058       
2059 /* important for the screen */
2060
2061
2062 /* the cursor set functions have a special mechanism. When they
2063 * realize, that you left an empty paragraph, they will delete it.
2064 * They also delete the corresponding row */
2065
2066 void LyXText::CursorRightOneWord(BufferView * bview) const
2067 {
2068         // treat floats, HFills and Insets as words
2069         LyXCursor tmpcursor = cursor;
2070         // CHECK See comment on top of text.C
2071
2072         if (tmpcursor.pos() == tmpcursor.par()->size()
2073             && tmpcursor.par()->next()) {
2074                         tmpcursor.par(tmpcursor.par()->next());
2075                         tmpcursor.pos(0);
2076         } else {
2077                 int steps = 0;
2078
2079                 // Skip through initial nonword stuff.
2080                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2081                        ! tmpcursor.par()->IsWord( tmpcursor.pos())) {
2082                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2083                         tmpcursor.pos(tmpcursor.pos() + 1);
2084                         ++steps;
2085                 }
2086                 // Advance through word.
2087                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2088                         tmpcursor.par()->IsWord( tmpcursor.pos())) {
2089                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2090                         tmpcursor.pos(tmpcursor.pos() + 1);
2091                         ++steps;
2092                 }
2093         }
2094         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
2095 }
2096
2097
2098 void LyXText::CursorTab(BufferView * bview) const
2099 {
2100     LyXCursor tmpcursor = cursor;
2101     while (tmpcursor.pos() < tmpcursor.par()->size()
2102            && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
2103         tmpcursor.pos(tmpcursor.pos() + 1);
2104
2105     if (tmpcursor.pos() == tmpcursor.par()->size()){
2106         if (tmpcursor.par()->next()) {
2107             tmpcursor.par(tmpcursor.par()->next());
2108             tmpcursor.pos(0);
2109         }
2110     } else
2111         tmpcursor.pos(tmpcursor.pos() + 1);
2112     SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
2113 }
2114
2115
2116 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2117             of prior word, not to end of next prior word. */
2118
2119 void LyXText::CursorLeftOneWord(BufferView * bview)  const
2120 {
2121         // treat HFills, floats and Insets as words
2122         LyXCursor tmpcursor = cursor;
2123         while (tmpcursor.pos() 
2124                && (tmpcursor.par()->IsSeparator(tmpcursor.pos() - 1) 
2125                    || tmpcursor.par()->IsKomma(tmpcursor.pos() - 1))
2126                && !(tmpcursor.par()->IsHfill(tmpcursor.pos() - 1)
2127                     || tmpcursor.par()->IsInset(tmpcursor.pos() - 1)))
2128                 tmpcursor.pos(tmpcursor.pos() - 1);
2129
2130         if (tmpcursor.pos()
2131             && (tmpcursor.par()->IsInset(tmpcursor.pos() - 1)
2132                 || tmpcursor.par()->IsHfill(tmpcursor.pos() - 1))) {
2133                 tmpcursor.pos(tmpcursor.pos() - 1);
2134         } else if (!tmpcursor.pos()) {
2135                 if (tmpcursor.par()->previous()){
2136                         tmpcursor.par(tmpcursor.par()->previous());
2137                         tmpcursor.pos(tmpcursor.par()->size());
2138                 }
2139         } else {                // Here, tmpcursor != 0 
2140                 while (tmpcursor.pos() > 0 &&
2141                        tmpcursor.par()->IsWord(tmpcursor.pos()-1) )
2142                         tmpcursor.pos(tmpcursor.pos() - 1);
2143         }
2144         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
2145 }
2146
2147 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
2148                         patched as well. */
2149
2150 void LyXText::SelectWord(BufferView * bview) 
2151 {
2152         // Move cursor to the beginning, when not already there.
2153         if (cursor.pos()
2154             && !cursor.par()->IsSeparator(cursor.pos()-1)
2155             && !cursor.par()->IsKomma(cursor.pos()-1) )
2156                 CursorLeftOneWord(bview);
2157
2158         // set the sel cursor
2159         sel_cursor = cursor;
2160
2161         while (cursor.pos() < cursor.par()->size()
2162                && !cursor.par()->IsSeparator(cursor.pos())
2163                && !cursor.par()->IsKomma(cursor.pos()) )
2164                 cursor.pos(cursor.pos() + 1);
2165         SetCursor(bview, cursor.par(), cursor.pos() );
2166         
2167         // finally set the selection
2168         SetSelection(bview);
2169 }
2170
2171
2172 /* -------> Select the word currently under the cursor when:
2173                         1: no selection is currently set,
2174                         2: the cursor is not at the borders of the word. */
2175
2176 bool LyXText::SelectWordWhenUnderCursor(BufferView * bview) 
2177 {
2178         if (!selection &&
2179             cursor.pos() > 0 && cursor.pos() < cursor.par()->size()
2180             && !cursor.par()->IsSeparator(cursor.pos())
2181             && !cursor.par()->IsKomma(cursor.pos())
2182             && !cursor.par()->IsSeparator(cursor.pos() -1)
2183             && !cursor.par()->IsKomma(cursor.pos() -1)) {
2184                 SelectWord(bview);
2185                 return true;
2186         }
2187         return false;
2188 }
2189
2190
2191 // This function is only used by the spellchecker for NextWord().
2192 // It doesn't handle LYX_ACCENTs and probably never will.
2193 string const LyXText::SelectNextWord(BufferView * bview,
2194                                      float & value) const
2195 {
2196         LyXParagraph * tmppar = cursor.par();
2197         
2198         // If this is not the very first word, skip rest of
2199         // current word because we are probably in the middle
2200         // of a word if there is text here.
2201         if (cursor.pos() || cursor.par()->previous()) {
2202                 while (cursor.pos() < cursor.par()->size()
2203                        && cursor.par()->IsLetter(cursor.pos()))
2204                         cursor.pos(cursor.pos() + 1);
2205         }
2206         
2207         // Now, skip until we have real text (will jump paragraphs)
2208         while ((cursor.par()->size() > cursor.pos()
2209                 && (!cursor.par()->IsLetter(cursor.pos())
2210                     || cursor.par()->getFont(bview->buffer()->params, cursor.pos())
2211                     .latex() == LyXFont::ON))
2212                || (cursor.par()->size() == cursor.pos()
2213                    && cursor.par()->next())){
2214                 if (cursor.pos() == cursor.par()->size()) {
2215                         cursor.par(cursor.par()->next());
2216                         cursor.pos(0);
2217                 } else
2218                         cursor.pos(cursor.pos() + 1);
2219         }
2220   
2221         // Update the value if we changed paragraphs
2222         if (cursor.par() != tmppar){
2223                 SetCursor(bview, cursor.par(), cursor.pos());
2224                 value = float(cursor.y())/float(height);
2225         }
2226
2227         // Start the selection from here
2228         sel_cursor = cursor;
2229
2230         std::ostringstream latex;
2231
2232         // and find the end of the word 
2233         // (optional hyphens are part of a word)
2234         while (cursor.pos() < cursor.par()->size()
2235                && (cursor.par()->IsLetter(cursor.pos())) 
2236                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
2237                        && cursor.par()->GetInset(cursor.pos()) != 0
2238                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
2239                        && latex.str() == "\\-"
2240                            ))
2241                 cursor.pos(cursor.pos() + 1);
2242
2243         // Finally, we copy the word to a string and return it
2244         string str;
2245         if (sel_cursor.pos() < cursor.pos()) {
2246                 LyXParagraph::size_type i;
2247                 for (i = sel_cursor.pos(); i < cursor.pos(); ++i) {
2248                         if (cursor.par()->GetChar(i) != LyXParagraph::META_INSET)
2249                                 str += cursor.par()->GetChar(i);
2250                 }
2251         }
2252         return str;
2253 }
2254
2255
2256 // This one is also only for the spellchecker
2257 void LyXText::SelectSelectedWord(BufferView * bview)
2258 {
2259         // move cursor to the beginning
2260         SetCursor(bview, sel_cursor.par(), sel_cursor.pos());
2261         
2262         // set the sel cursor
2263         sel_cursor = cursor;
2264
2265         std::ostringstream latex;
2266         
2267         // now find the end of the word
2268         while (cursor.pos() < cursor.par()->size()
2269                && (cursor.par()->IsLetter(cursor.pos())
2270                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
2271                        && cursor.par()->GetInset(cursor.pos()) != 0
2272                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
2273                        && latex.str() == "\\-"
2274                            )))
2275                 cursor.pos(cursor.pos() + 1);
2276         
2277         SetCursor(bview, cursor.par(), cursor.pos());
2278         
2279         // finally set the selection
2280         SetSelection(bview);
2281 }
2282
2283
2284 /* -------> Delete from cursor up to the end of the current or next word. */
2285 void LyXText::DeleteWordForward(BufferView * bview)
2286 {
2287         if (!cursor.par()->size())
2288                 CursorRight(bview);
2289         else {
2290                 LyXCursor tmpcursor = cursor;
2291                 tmpcursor.row(0); // ??
2292                 selection = true; // to avoid deletion 
2293                 CursorRightOneWord(bview);
2294                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2295                 sel_cursor = cursor;
2296                 cursor = tmpcursor;
2297                 SetSelection(bview); 
2298                 
2299                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2300                 CutSelection(bview);
2301         }
2302 }
2303
2304
2305 /* -------> Delete from cursor to start of current or prior word. */
2306 void LyXText::DeleteWordBackward(BufferView * bview)
2307 {
2308        if (!cursor.par()->size())
2309                CursorLeft(bview);
2310        else {
2311                LyXCursor tmpcursor = cursor;
2312                tmpcursor.row(0); // ??
2313                selection = true; // to avoid deletion 
2314                CursorLeftOneWord(bview);
2315                SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2316                sel_cursor = cursor;
2317                cursor = tmpcursor;
2318                SetSelection(bview);
2319                CutSelection(bview);
2320        }
2321 }
2322
2323
2324 /* -------> Kill to end of line. */
2325 void LyXText::DeleteLineForward(BufferView * bview)
2326 {
2327         if (!cursor.par()->size())
2328                 // Paragraph is empty, so we just go to the right
2329                 CursorRight(bview);
2330         else {
2331                 LyXCursor tmpcursor = cursor;
2332                 // We can't store the row over a regular SetCursor
2333                 // so we set it to 0 and reset it afterwards.
2334                 tmpcursor.row(0); // ??
2335                 selection = true; // to avoid deletion 
2336                 CursorEnd(bview);
2337                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2338                 sel_cursor = cursor;
2339                 cursor = tmpcursor;
2340                 SetSelection(bview);
2341                 // What is this test for ??? (JMarc)
2342                 if (!selection) {
2343                         DeleteWordForward(bview);
2344                 } else {
2345                         CutSelection(bview);
2346                 }
2347         }
2348 }
2349
2350
2351 // Change the case of a word at cursor position. 
2352 // This function directly manipulates LyXParagraph::text because there
2353 // is no LyXParagraph::SetChar currently. I did what I could to ensure
2354 // that it is correct. I guess part of it should be moved to
2355 // LyXParagraph, but it will have to change for 1.1 anyway. At least
2356 // it does not access outside of the allocated array as the older
2357 // version did. (JMarc) 
2358 void LyXText::ChangeWordCase(BufferView * bview, LyXText::TextCase action) 
2359 {
2360         LyXParagraph * tmppar = cursor.par();
2361
2362         SetUndo(bview->buffer(),Undo::FINISH,
2363                 tmppar->previous(), tmppar->next()); 
2364
2365         LyXParagraph::size_type tmppos = cursor.pos();
2366
2367         while (tmppos < tmppar->size()) {
2368                 unsigned char c = tmppar->GetChar(tmppos);
2369                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
2370                         break;
2371                 if (c != LyXParagraph::META_INSET) {
2372                         switch (action) {
2373                         case text_lowercase:
2374                                 c = tolower(c);
2375                                 break;
2376                         case text_capitalization:
2377                                 c = toupper(c);
2378                                 action = text_lowercase;
2379                                 break;
2380                         case text_uppercase:
2381                                 c = toupper(c);
2382                                 break;
2383                         }
2384                 }
2385                 
2386                 //tmppar->text[tmppos] = c;
2387                 tmppar->SetChar(tmppos, c);
2388                 ++tmppos;
2389         }
2390         CheckParagraph(bview, tmppar, tmppos);
2391         CursorRightOneWord(bview);
2392 }
2393
2394
2395 void LyXText::TransposeChars(BufferView const & bview)
2396 {
2397         LyXParagraph * tmppar = cursor.par();
2398
2399         SetUndo(bview.buffer(), Undo::FINISH,
2400                 tmppar->previous(), tmppar->next()); 
2401
2402         LyXParagraph::size_type tmppos = cursor.pos();
2403
2404         // First decide if it is possible to transpose at all
2405
2406         // We are at the beginning of a paragraph.
2407         if (tmppos == 0) return;
2408
2409         // We are at the end of a paragraph.
2410         if (tmppos == tmppar->size() - 1) return;
2411
2412         unsigned char c1 = tmppar->GetChar(tmppos);
2413         unsigned char c2 = tmppar->GetChar(tmppos - 1);
2414
2415         if (c1 != LyXParagraph::META_INSET
2416             && c2 != LyXParagraph::META_INSET) {
2417                 tmppar->SetChar(tmppos, c2);
2418                 tmppar->SetChar(tmppos - 1, c1);
2419         }
2420         // We should have an implementation that handles insets
2421         // as well, but that will have to come later. (Lgb)
2422         CheckParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2423 }
2424
2425
2426 void LyXText::Delete(BufferView * bview)
2427 {
2428         // this is a very easy implementation
2429
2430         LyXCursor old_cursor = cursor;
2431         int const old_cur_par_id = old_cursor.par()->id();
2432         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2433                 old_cursor.par()->previous()->id() : 0;
2434         
2435         // just move to the right
2436         CursorRight(bview);
2437
2438         // CHECK Look at the comment here.
2439         // This check is not very good...
2440         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
2441         // and that can very well delete the par or par->previous in
2442         // old_cursor. Will a solution where we compare paragraph id's
2443         //work better?
2444         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2445             == old_cur_par_prev_id
2446             && cursor.par()->id() != old_cur_par_id)
2447                 return; // delete-empty-paragraph-mechanism has done it
2448
2449         // if you had success make a backspace
2450         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2451                 LyXCursor tmpcursor = cursor;
2452                 cursor = old_cursor; // to make sure undo gets the right cursor position
2453                 SetUndo(bview->buffer(), Undo::DELETE,
2454                         cursor.par()->previous(), 
2455                         cursor.par()->next()); 
2456                 cursor = tmpcursor;
2457                 Backspace(bview);
2458         }
2459 }
2460
2461
2462 void LyXText::Backspace(BufferView * bview)
2463 {
2464         // Get the font that is used to calculate the baselineskip
2465         LyXParagraph::size_type lastpos = cursor.par()->size();
2466         LyXFont rawparfont =
2467                 cursor.par()->GetFontSettings(bview->buffer()->params,
2468                                               lastpos - 1);
2469
2470         if (cursor.pos() == 0) {
2471                 // The cursor is at the beginning of a paragraph,
2472                 // so the the backspace will collapse two paragraphs into one.
2473                 
2474                 // we may paste some paragraphs
2475       
2476                 // is it an empty paragraph?
2477       
2478                 if ((lastpos == 0
2479                      || (lastpos == 1 && cursor.par()->IsSeparator(0)))) {
2480                         // This is an empty paragraph and we delete it just by moving the cursor one step
2481                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2482                         // of the paragraph.
2483                         
2484                         if (cursor.par()->previous()) {
2485                                 LyXParagraph * tmppar = cursor.par()->previous();
2486                                 if (cursor.par()->GetLayout() == tmppar->GetLayout()
2487                                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
2488                                         // Inherit bottom DTD from the paragraph below.
2489                                         // (the one we are deleting)
2490                                         tmppar->params.lineBottom(cursor.par()->params.lineBottom());
2491                                         tmppar->params.spaceBottom(cursor.par()->params.spaceBottom());
2492                                         tmppar->params.pagebreakBottom(cursor.par()->params.pagebreakBottom());
2493                                 }
2494                                 
2495                                 CursorLeft(bview);
2496                      
2497                                 // the layout things can change the height of a row !
2498                                 int const tmpheight = cursor.row()->height();
2499                                 SetHeightOfRow(bview, cursor.row());
2500                                 if (cursor.row()->height() != tmpheight) {
2501                                         refresh_y = cursor.y() - cursor.row()->baseline();
2502                                         refresh_row = cursor.row();
2503                                         status = LyXText::NEED_MORE_REFRESH;
2504                                 }
2505                                 return;
2506                         }
2507                 }
2508
2509                 if (cursor.par()->previous()) {
2510                         SetUndo(bview->buffer(), Undo::DELETE,
2511                                 cursor.par()->previous()->previous(),
2512                                 cursor.par()->next());
2513                 }
2514                 
2515                 LyXParagraph * tmppar = cursor.par();
2516                 Row * tmprow = cursor.row();
2517
2518                 // We used to do CursorLeftIntern() here, but it is
2519                 // not a good idea since it triggers the auto-delete
2520                 // mechanism. So we do a CursorLeftIntern()-lite,
2521                 // without the dreaded mechanism. (JMarc)
2522                 if (cursor.par()->previous()) { 
2523                         // steps into the above paragraph.
2524                         SetCursorIntern(bview, cursor.par()->previous(),
2525                                         cursor.par()->previous()->size(),
2526                                         false);
2527                 }
2528
2529                 /* Pasting is not allowed, if the paragraphs have different
2530                    layout. I think it is a real bug of all other
2531                    word processors to allow it. It confuses the user.
2532                    Even so with a footnote paragraph and a non-footnote
2533                    paragraph. I will not allow pasting in this case, 
2534                    because the user would be confused if the footnote behaves 
2535                    different wether it is open or closed.
2536                   
2537                    Correction: Pasting is always allowed with standard-layout
2538                 */
2539                 if (cursor.par() != tmppar
2540                     && (cursor.par()->GetLayout() == tmppar->GetLayout()
2541                         || tmppar->GetLayout() == 0 /*standard*/)
2542                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
2543
2544                         RemoveParagraph(tmprow);
2545                         RemoveRow(tmprow);
2546                         cursor.par()->PasteParagraph(bview->buffer()->params);
2547                         
2548                         if (!cursor.pos() || !cursor.par()->IsSeparator(cursor.pos() - 1))
2549                                 ; //cursor.par()->InsertChar(cursor.pos(), ' ');
2550                         // strangely enough it seems that commenting out the line above removes
2551                         // most or all of the segfaults. I will however also try to move the
2552                         // two Remove... lines in front of the PasteParagraph too.
2553                         else
2554                                 if (cursor.pos())
2555                                         cursor.pos(cursor.pos() - 1);
2556                         
2557                         status = LyXText::NEED_MORE_REFRESH;
2558                         refresh_row = cursor.row();
2559                         refresh_y = cursor.y() - cursor.row()->baseline();
2560                         
2561                         // remove the lost paragraph
2562                         // This one is not safe, since the paragraph that the tmprow and the
2563                         // following rows belong to has been deleted by the PasteParagraph
2564                         // above. The question is... could this be moved in front of the
2565                         // PasteParagraph?
2566                         //RemoveParagraph(tmprow);
2567                         //RemoveRow(tmprow);  
2568                         
2569                         // This rebuilds the rows.
2570                         AppendParagraph(bview, cursor.row());
2571                         UpdateCounters(bview, cursor.row());
2572                         
2573                         // the row may have changed, block, hfills etc.
2574                         SetCursor(bview, cursor.par(), cursor.pos(), false);
2575                 }
2576         } else {
2577                 /* this is the code for a normal backspace, not pasting
2578                  * any paragraphs */ 
2579                 SetUndo(bview->buffer(), Undo::DELETE,
2580                         cursor.par()->previous(),
2581                         cursor.par()->next()); 
2582                 // We used to do CursorLeftIntern() here, but it is
2583                 // not a good idea since it triggers the auto-delete
2584                 // mechanism. So we do a CursorLeftIntern()-lite,
2585                 // without the dreaded mechanism. (JMarc)
2586                 SetCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2587                                 false, cursor.boundary());
2588                 
2589                 // some insets are undeletable here
2590                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
2591                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
2592                                 return; 
2593                         // force complete redo when erasing display insets
2594                         // this is a cruel method but safe..... Matthias 
2595                         if (cursor.par()->GetInset(cursor.pos())->display() ||
2596                             cursor.par()->GetInset(cursor.pos())->needFullRow()) {
2597                                 cursor.par()->Erase(cursor.pos());
2598                                 RedoParagraph(bview);
2599                                 return;
2600                         }
2601                 }
2602                 
2603                 Row * row = cursor.row();
2604                 int y = cursor.y() - row->baseline();
2605                 LyXParagraph::size_type z;
2606                 /* remember that a space at the end of a row doesnt count
2607                  * when calculating the fill */ 
2608                 if (cursor.pos() < RowLast(row) ||
2609                     !cursor.par()->IsLineSeparator(cursor.pos())) {
2610                         row->fill(row->fill() + SingleWidth(bview,
2611                                                             cursor.par(),
2612                                                             cursor.pos()));
2613                 }
2614                 
2615                 /* some special code when deleting a newline. This is similar
2616                  * to the behavior when pasting paragraphs */ 
2617                 if (cursor.pos() && cursor.par()->IsNewline(cursor.pos())) {
2618                         cursor.par()->Erase(cursor.pos());
2619                         // refresh the positions
2620                         Row * tmprow = row;
2621                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2622                                 tmprow = tmprow->next();
2623                                 tmprow->pos(tmprow->pos() - 1);
2624                         }
2625                         if (cursor.par()->IsLineSeparator(cursor.pos() - 1))
2626                                 cursor.pos(cursor.pos() - 1);
2627
2628                         if (cursor.pos() < cursor.par()->size()
2629                             && !cursor.par()->IsSeparator(cursor.pos())) {
2630                                 cursor.par()->InsertChar(cursor.pos(), ' ');
2631                                 SetCharFont(bview->buffer(), cursor.par(), 
2632                                             cursor.pos(), current_font);
2633                                 // refresh the positions
2634                                 tmprow = row;
2635                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2636                                         tmprow = tmprow->next();
2637                                         tmprow->pos(tmprow->pos() + 1);
2638                                 }
2639                         }
2640                 } else {
2641                         cursor.par()->Erase(cursor.pos());
2642                         
2643                         // refresh the positions
2644                         Row * tmprow = row;
2645                         while (tmprow->next()
2646                                && tmprow->next()->par() == row->par()) {
2647                                 tmprow = tmprow->next();
2648                                 tmprow->pos(tmprow->pos() - 1);
2649                         }
2650
2651                         // delete newlines at the beginning of paragraphs
2652                         while (cursor.par()->size() &&
2653                                cursor.par()->IsNewline(cursor.pos()) &&
2654                                cursor.pos() == BeginningOfMainBody(bview->buffer(),
2655                                                                    cursor.par())) {
2656                                 cursor.par()->Erase(cursor.pos());
2657                                 // refresh the positions
2658                                 tmprow = row;
2659                                 while (tmprow->next() && 
2660                                        tmprow->next()->par() == row->par()) {
2661                                         tmprow = tmprow->next();
2662                                         tmprow->pos(tmprow->pos() - 1);
2663                                 }
2664                         }
2665                 }
2666                 
2667                 // is there a break one row above
2668                 if (row->previous() && row->previous()->par() == row->par()) {
2669                         z = NextBreakPoint(bview, row->previous(),
2670                                            workWidth(bview));
2671                         if (z >= row->pos()) {
2672                                 row->pos(z + 1);
2673                                 
2674                                 Row * tmprow = row->previous();
2675                                 
2676                                 // maybe the current row is now empty
2677                                 if (row->pos() >= row->par()->size()) {
2678                                         // remove it
2679                                         RemoveRow(row);
2680                                         need_break_row = 0;
2681                                 } else {
2682                                         BreakAgainOneRow(bview, row);
2683                                         if (row->next() && row->next()->par() == row->par())
2684                                                 need_break_row = row->next();
2685                                         else
2686                                                 need_break_row = 0;
2687                                 }
2688                                 
2689                                 // set the dimensions of the row above
2690                                 y -= tmprow->height();
2691                                 tmprow->fill(Fill(bview, tmprow,
2692                                                   workWidth(bview)));
2693                                 SetHeightOfRow(bview, tmprow);
2694                                 
2695                                 refresh_y = y;
2696                                 refresh_row = tmprow;
2697                                 status = LyXText::NEED_MORE_REFRESH;
2698                                 SetCursor(bview, cursor.par(), cursor.pos(),
2699                                           false, cursor.boundary());
2700                                 //current_font = rawtmpfont;
2701                                 //real_current_font = realtmpfont;
2702                                 // check, whether the last character's font has changed.
2703                                 if (rawparfont !=
2704                                     cursor.par()->GetFontSettings(bview->buffer()->params,
2705                                                                   cursor.par()->size() - 1))
2706                                         RedoHeightOfParagraph(bview, cursor);
2707                                 return;
2708                         }
2709                 }
2710                 
2711                 // break the cursor row again
2712                 if (row->next() && row->next()->par() == row->par() &&
2713                     (RowLast(row) == row->par()->size() - 1 ||
2714                      NextBreakPoint(bview, row, workWidth(bview)) != RowLast(row))) {
2715                         
2716                         /* it can happen that a paragraph loses one row
2717                          * without a real breakup. This is when a word
2718                          * is to long to be broken. Well, I don t care this 
2719                          * hack ;-) */
2720                         if (RowLast(row) == row->par()->size() - 1)
2721                                 RemoveRow(row->next());
2722                         
2723                         refresh_y = y;
2724                         refresh_row = row;
2725                         status = LyXText::NEED_MORE_REFRESH;
2726                         
2727                         BreakAgainOneRow(bview, row);
2728                         // will the cursor be in another row now?
2729                         if (row->next() && row->next()->par() == row->par() &&
2730                             RowLast(row) <= cursor.pos()) {
2731                                 row = row->next();
2732                                 BreakAgainOneRow(bview, row);
2733                         }
2734
2735                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2736
2737                         if (row->next() && row->next()->par() == row->par())
2738                                 need_break_row = row->next();
2739                         else
2740                                 need_break_row = 0;
2741                 } else  {
2742                         // set the dimensions of the row
2743                         row->fill(Fill(bview, row, workWidth(bview)));
2744                         int const tmpheight = row->height();
2745                         SetHeightOfRow(bview, row);
2746                         if (tmpheight == row->height())
2747                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
2748                         else
2749                                 status = LyXText::NEED_MORE_REFRESH;
2750                         refresh_y = y;
2751                         refresh_row = row;
2752                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2753                 }
2754         }
2755
2756         // current_font = rawtmpfont;
2757         // real_current_font = realtmpfont;
2758
2759         if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos())
2760             != cursor.boundary())
2761                 SetCursor(bview, cursor.par(), cursor.pos(), false,
2762                           !cursor.boundary());
2763
2764         lastpos = cursor.par()->size();
2765         if (cursor.pos() == lastpos)
2766                 SetCurrentFont(bview);
2767         
2768         // check, whether the last characters font has changed.
2769         if (rawparfont != 
2770             cursor.par()->GetFontSettings(bview->buffer()->params, lastpos - 1)) {
2771                 RedoHeightOfParagraph(bview, cursor);
2772         } else {
2773                 // now the special right address boxes
2774                 if (textclasslist.Style(bview->buffer()->params.textclass,
2775                                         cursor.par()->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
2776                         RedoDrawingOfParagraph(bview, cursor); 
2777                 }
2778         }
2779 }
2780
2781
2782 void LyXText::GetVisibleRow(BufferView * bview, int y_offset, int x_offset,
2783                             Row * row_ptr, int y, bool cleared)
2784 {
2785         // returns a printed row
2786         Painter & pain = bview->painter();
2787         
2788         bool const is_rtl =
2789                 row_ptr->par()->isRightToLeftPar(bview->buffer()->params);
2790         
2791         LyXParagraph::size_type const last = RowLastPrintable(row_ptr);
2792
2793         LyXParagraph::size_type vpos;
2794         LyXParagraph::size_type pos;
2795
2796         float tmpx;
2797
2798         LyXFont font(LyXFont::ALL_SANE);
2799         int maxdesc;
2800         if (row_ptr->height() <= 0) {
2801                 lyxerr << "LYX_ERROR: row.height: "
2802                        << row_ptr->height() << endl;
2803                 return;
2804         }
2805
2806         float x;
2807         float fill_separator;
2808         float fill_hfill;
2809         float fill_label_hfill;
2810         PrepareToPrint(bview, row_ptr, x, fill_separator,
2811                        fill_hfill, fill_label_hfill);
2812         
2813         if (inset_owner && (x < 0))
2814                 x = 0;
2815         x += x_offset;
2816         
2817         // clear the area where we want to paint/print
2818         int const ww = bview->workWidth();
2819
2820         bool clear_area = true;
2821         Inset * inset = 0;
2822
2823         if (!bview->screen()->forceClear() && last == row_ptr->pos()
2824             && row_ptr->par()->GetChar(row_ptr->pos()) == LyXParagraph::META_INSET
2825             && (inset = row_ptr->par()->GetInset(row_ptr->pos()))) {
2826                 clear_area = inset->doClearArea();
2827         }
2828         // we don't need to clear it's already done!!!
2829         if (cleared) {
2830                 clear_area = true;
2831         } else if (clear_area) {
2832 #ifdef WITH_WARNINGS
2833 #warning Should be fixed with a lyxinset::clear_width(bv, font) function! (Jug)
2834 #warning Should we not fix this in the Painter, please have a look Lars! (Jug)
2835 #endif
2836                 int const y = y_offset < 0 ? 0 : y_offset;
2837                 int const h = y_offset < 0 ?
2838                         row_ptr->height() + y_offset : row_ptr->height();
2839                 int const w = inset_owner ?
2840                         inset_owner->width(bview, font) - 2 : ww;
2841                 int const x = x_offset;
2842                 pain.fillRectangle(x, y, w, h);
2843         } else if (inset != 0) {
2844                 int h = row_ptr->baseline() - inset->ascent(bview, font);
2845                 if (h > 0) {
2846                         int const w = (inset_owner ?
2847                                  inset_owner->width(bview, font) : ww);
2848                         pain.fillRectangle(x_offset, y_offset, w, h);
2849                 }
2850                 h += inset->ascent(bview, font) + inset->descent(bview, font);
2851                 if ((row_ptr->height() - h) > 0) {
2852                         int const w = (inset_owner ?
2853                                  inset_owner->width(bview, font) : ww);
2854                         pain.fillRectangle(x_offset, y_offset + h,
2855                                            w, row_ptr->height() - h);
2856                 }
2857                 if (!inset_owner && !inset->display() && !inset->needFullRow())
2858                 {
2859                         int const w = inset->width(bview, font) + int(x);
2860                         pain.fillRectangle(w, y_offset, ww - w, row_ptr->height());
2861                 }
2862         }
2863         
2864         if (selection) {
2865                 int const w = (inset_owner ?
2866                                inset_owner->width(bview, font) : ww);
2867                 // selection code
2868                 if (bidi_same_direction) {
2869                         if (sel_start_cursor.row() == row_ptr &&
2870                             sel_end_cursor.row() == row_ptr) {
2871                                 if (sel_start_cursor.x() < sel_end_cursor.x())
2872                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
2873                                                            y_offset,
2874                                                            sel_end_cursor.x() - sel_start_cursor.x(),
2875                                                            row_ptr->height(),
2876                                                            LColor::selection);
2877                                 else
2878                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
2879                                                            y_offset,
2880                                                            sel_start_cursor.x() - sel_end_cursor.x(),
2881                                                            row_ptr->height(),
2882                                                            LColor::selection);
2883                         } else if (sel_start_cursor.row() == row_ptr) {
2884                                 if (is_rtl)
2885                                         pain.fillRectangle(x_offset, y_offset,
2886                                                            sel_start_cursor.x(),
2887                                                            row_ptr->height(),
2888                                                            LColor::selection);
2889                                 else
2890                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
2891                                                            y_offset,
2892                                                            w - sel_start_cursor.x(),
2893                                                            row_ptr->height(),
2894                                                            LColor::selection);
2895                         } else if (sel_end_cursor.row() == row_ptr) {
2896                                 if (is_rtl)
2897                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
2898                                                            y_offset,
2899                                                            w - sel_end_cursor.x(),
2900                                                            row_ptr->height(),
2901                                                            LColor::selection);
2902                                 else
2903                                         pain.fillRectangle(x_offset, y_offset,
2904                                                            sel_end_cursor.x(),
2905                                                            row_ptr->height(),
2906                                                            LColor::selection);
2907                         } else if (y > sel_start_cursor.y()
2908                                    && y < sel_end_cursor.y()) {
2909                                 pain.fillRectangle(x_offset, y_offset, w,
2910                                                    row_ptr->height(),
2911                                                    LColor::selection);
2912                         }
2913                 } else if (sel_start_cursor.row() != row_ptr &&
2914                             sel_end_cursor.row() != row_ptr &&
2915                             y > sel_start_cursor.y()
2916                             && y < sel_end_cursor.y()) {
2917                         pain.fillRectangle(x_offset, y_offset, w,
2918                                            row_ptr->height(),
2919                                            LColor::selection);
2920                 } else if (sel_start_cursor.row() == row_ptr ||
2921                            sel_end_cursor.row() == row_ptr) {
2922                         float tmpx = x;
2923                         if ((sel_start_cursor.row() != row_ptr && !is_rtl) ||
2924                              (sel_end_cursor.row() != row_ptr && is_rtl))
2925                                 pain.fillRectangle(x_offset, y_offset,
2926                                                    int(tmpx),
2927                                                    row_ptr->height(),
2928                                                    LColor::selection);
2929                         LyXParagraph::size_type main_body =
2930                                 BeginningOfMainBody(bview->buffer(),
2931                                                     row_ptr->par());
2932                         
2933                         for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
2934                                 pos = vis2log(vpos);
2935                                 float const old_tmpx = tmpx;
2936                                 if (main_body > 0 && pos == main_body-1) {
2937                                         tmpx += fill_label_hfill +
2938                                                 lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
2939                                                                                    row_ptr->par()->GetLayout()).labelsep,
2940                                                                GetFont(bview->buffer(),row_ptr->par(), -2));
2941                                         if (row_ptr->par()->IsLineSeparator(main_body-1))
2942                                                 tmpx -= SingleWidth(bview, row_ptr->par(), main_body-1);
2943                                 }
2944                                 if (HfillExpansion(bview->buffer(), row_ptr, pos)) {
2945                                         tmpx += SingleWidth(bview, row_ptr->par(), pos);
2946                                         if (pos >= main_body)
2947                                                 tmpx += fill_hfill;
2948                                         else 
2949                                                 tmpx += fill_label_hfill;
2950                                 }
2951                                 else if (row_ptr->par()->IsSeparator(pos)) {
2952                                         tmpx += SingleWidth(bview, row_ptr->par(), pos);
2953                                         if (pos >= main_body)
2954                                                 tmpx += fill_separator;
2955                                 } else
2956                                         tmpx += SingleWidth(bview, row_ptr->par(), pos);
2957                                 
2958                                 if ((sel_start_cursor.row() != row_ptr ||
2959                                       sel_start_cursor.pos() <= pos) &&
2960                                      (sel_end_cursor.row() != row_ptr ||
2961                                       pos < sel_end_cursor.pos()) )
2962                                         // Here we do not use x_offset as x_offset was
2963                                         // added to x.
2964                                         pain.fillRectangle(int(old_tmpx),
2965                                                            y_offset,
2966                                                            int(tmpx - old_tmpx + 1),
2967                                                            row_ptr->height(),
2968                                                            LColor::selection);
2969                         }
2970
2971                         if ((sel_start_cursor.row() != row_ptr && is_rtl) ||
2972                              (sel_end_cursor.row() != row_ptr && !is_rtl) )
2973                                 pain.fillRectangle(x_offset + int(tmpx),
2974                                                    y_offset,
2975                                                    int(ww - tmpx),
2976                                                    row_ptr->height(),
2977                                                    LColor::selection);
2978                 }
2979         }
2980
2981         int box_x = 0;
2982
2983         // Draw appendix lines
2984         LyXParagraph * firstpar = row_ptr->par();
2985
2986         if (firstpar->params.appendix()) {
2987                 pain.line(1, y_offset,
2988                           1, y_offset + row_ptr->height(),
2989                           LColor::appendixline);
2990                 pain.line(ww - 2, y_offset,
2991                           ww - 2, y_offset + row_ptr->height(),
2992                           LColor::appendixline);
2993         }
2994
2995         // Draw depth lines
2996         int const depth = firstpar->GetDepth();
2997         if (depth > 0) {
2998                 int next_depth = 0;
2999                 int prev_depth = 0;
3000                 if (row_ptr->next())
3001                                 next_depth = row_ptr->next()->par()->GetDepth();
3002                 if (row_ptr->previous())
3003                                 prev_depth = row_ptr->previous()->par()->GetDepth();
3004
3005                 for (int i = 1; i <= depth; ++i) {
3006                         int const line_x = (LYX_PAPER_MARGIN / 5) *
3007                                 i + box_x + x_offset;
3008                         pain.line(line_x, y_offset, line_x,
3009                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
3010                                   LColor::depthbar);
3011                 
3012                         if (i > prev_depth)
3013                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
3014                                                    LColor::depthbar);
3015                         if (i > next_depth)
3016                                 pain.fillRectangle(line_x,
3017                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
3018                                                    LYX_PAPER_MARGIN / 5, 2,
3019                                                    LColor::depthbar);
3020                 }
3021         }
3022
3023         
3024         LyXLayout const & layout =
3025                 textclasslist.Style(bview->buffer()->params.textclass,
3026                                     row_ptr->par()->GetLayout());
3027
3028         int y_top = 0;
3029         int y_bottom = row_ptr->height();
3030         
3031         // is it a first row?
3032         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
3033                 
3034                 // start of appendix?
3035                 if (row_ptr->par()->params.startOfAppendix()) {
3036                         pain.line(1, y_offset,
3037                                   ww - 2, y_offset,
3038                                   LColor::appendixline);
3039                 }
3040                 
3041                 // think about the margins
3042                 if (!row_ptr->previous() && bv_owner)
3043                         y_top += LYX_PAPER_MARGIN;
3044                 
3045                 // draw a top pagebreak
3046                 if (row_ptr->par()->params.pagebreakTop()) {
3047                         LyXFont pb_font;
3048                         pb_font.setColor(LColor::pagebreak).decSize();
3049                         int w = 0;
3050                         int a = 0;
3051                         int d = 0;
3052                         pain.line(0, y_offset + y_top + 2*DefaultHeight(),
3053                                   ww, 
3054                                   y_offset + y_top + 2 * DefaultHeight(),
3055                                   LColor::pagebreak, 
3056                                   Painter::line_onoffdash)
3057                                 .rectText(0,
3058                                           0,
3059                                           _("Page Break (top)"),
3060                                           pb_font,
3061                                           LColor::background,
3062                                           LColor::background, false, w, a, d);
3063                         pain.rectText((ww - w)/2,
3064                                       y_offset + y_top + 2 * DefaultHeight() + d,
3065                                       _("Page Break (top)"),
3066                                       pb_font,
3067                                       LColor::background,
3068                                       LColor::background);
3069                         y_top += 3 * DefaultHeight();
3070                 }
3071                 
3072                 if (row_ptr->par()->params.spaceTop().kind() == VSpace::VFILL) {
3073                         // draw a vfill top
3074                         pain.line(0, y_offset + 2 + y_top,
3075                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
3076                                   LColor::vfillline);
3077                         
3078                         pain.line(0, y_offset + y_top + 3 * DefaultHeight(),
3079                                   LYX_PAPER_MARGIN,
3080                                   y_offset + y_top + 3 * DefaultHeight(),
3081                                   LColor::vfillline);
3082                         
3083                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
3084                                   LYX_PAPER_MARGIN / 2,
3085                                   y_offset + y_top + 3 * DefaultHeight(),
3086                                   LColor::vfillline);
3087                         
3088                         y_top += 3 * DefaultHeight();
3089                 }
3090                 
3091                 // think about user added space
3092                 y_top += int(row_ptr->par()->params.spaceTop().inPixels(bview));
3093                 
3094                 // think about the parskip
3095                 // some parskips VERY EASY IMPLEMENTATION
3096                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3097                         if (layout.latextype == LATEX_PARAGRAPH
3098                             && firstpar->GetDepth() == 0
3099                             && firstpar->previous())
3100                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
3101                         else if (firstpar->previous()
3102                                  && textclasslist.Style(bview->buffer()->params.textclass,
3103                                                         firstpar->previous()->GetLayout()).latextype == LATEX_PARAGRAPH
3104                                  && firstpar->previous()->GetDepth() == 0)
3105                                 // is it right to use defskip here, too? (AS) 
3106                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
3107                 }
3108                 
3109                 if (row_ptr->par()->params.lineTop()) {
3110                         // draw a top line
3111                         y_top +=  lyxfont::ascent('x',
3112                                                   GetFont(bview->buffer(),
3113                                                           row_ptr->par(), 0));
3114                         int const w = (inset_owner ?
3115                                        inset_owner->width(bview, font) : ww);
3116                         int const xp = static_cast<int>(inset_owner ? x : 0);
3117                         pain.line(xp, y_offset + y_top,
3118                                   w, y_offset + y_top,
3119                                   LColor::topline,
3120                                   Painter::line_solid,
3121                                   Painter::line_thick);
3122                         
3123                         y_top +=  lyxfont::ascent('x',GetFont(bview->buffer(),
3124                                                               row_ptr->par(), 0));
3125                 }
3126                 
3127                 // should we print a label?
3128                 if (layout.labeltype >= LABEL_STATIC
3129                     && (layout.labeltype != LABEL_STATIC
3130                         || layout.latextype != LATEX_ENVIRONMENT
3131                         || row_ptr->par()->IsFirstInSequence())) {
3132                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
3133                         if (!row_ptr->par()->GetLabelstring().empty()) {
3134                                 tmpx = x;
3135                                 string const tmpstring =
3136                                         row_ptr->par()->GetLabelstring();
3137                                 
3138                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3139                                         if (bview->buffer()->params.secnumdepth >= 0) {
3140                                                 // this is special code for
3141                                                 // the chapter layout. This is
3142                                                 // printed in an extra row
3143                                                 // and has a pagebreak at
3144                                                 // the top.
3145                                                 float spacing_val = 1.0;
3146                                                 if (!row_ptr->par()->params.spacing().isDefault()) {
3147                                                         spacing_val = row_ptr->par()->params.spacing().getValue();
3148                                                 } else {
3149                                                         spacing_val = bview->buffer()->params.spacing.getValue();
3150                                                 }
3151    
3152                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3153                                                         + int(layout.parsep) * DefaultHeight();
3154                                                 if (is_rtl)
3155                                                         tmpx = ww - LeftMargin(bview, row_ptr) - 
3156                                                                 lyxfont::width(tmpstring, font);
3157                                                 pain.text(int(tmpx),
3158                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
3159                                                           tmpstring, font);
3160                                         }
3161                                 } else {
3162                                         if (is_rtl) {
3163                                                 tmpx = ww - LeftMargin(bview, row_ptr)
3164                                                         + lyxfont::width(layout.labelsep, font);
3165                                         } else
3166                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3167                                                         - lyxfont::width(tmpstring, font);
3168
3169                                         // draw it!
3170                                         pain.text(int(tmpx),
3171                                                   y_offset + row_ptr->baseline(),
3172                                                   tmpstring, font);
3173                                 }
3174                         }
3175                         // the labels at the top of an environment.
3176                         // More or less for bibliography
3177                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3178                            layout.labeltype == LABEL_BIBLIO ||
3179                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3180                         if (row_ptr->par()->IsFirstInSequence()) {
3181                                 font = GetFont(bview->buffer(),
3182                                                row_ptr->par(), -2);
3183                                 if (!row_ptr->par()->GetLabelstring().empty()) {
3184                                         string const tmpstring =
3185                                                 row_ptr->par()->GetLabelstring();
3186                                         float spacing_val = 1.0;
3187                                         if (!row_ptr->par()->params.spacing().isDefault()) {
3188                                                 spacing_val = row_ptr->par()->params.spacing().getValue();
3189                                         } else {
3190                                                 spacing_val = bview->buffer()->params.spacing.getValue();
3191                                         }
3192    
3193                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3194                                                       + (layout.labelbottomsep * DefaultHeight()));
3195                                         
3196                                         tmpx = x;
3197                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
3198                                                 tmpx = ( (is_rtl ? LeftMargin(bview, row_ptr) : x)
3199                                                          + ww - RightMargin(bview->buffer(), row_ptr) ) / 2; 
3200                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
3201                                         } else if (is_rtl)
3202                                                 tmpx = ww - LeftMargin(bview, row_ptr) - 
3203                                                         lyxfont::width(tmpstring, font);
3204                                         pain.text(int(tmpx),
3205                                                   y_offset + row_ptr->baseline()
3206                                                   - row_ptr->ascent_of_text()
3207                                                   - maxdesc,
3208                                                   tmpstring, font);
3209                                 }
3210                         }
3211                 }
3212                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
3213                         font = GetFont(bview->buffer(), row_ptr->par(), -1);
3214                         if (is_rtl)
3215                                 tmpx = ww - LeftMargin(bview, row_ptr)
3216                                         + lyxfont::width(layout.labelsep, font);
3217                         else
3218                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3219                                         - row_ptr->par()->bibkey->width(bview, font);
3220                         row_ptr->par()->bibkey->draw(bview, font,
3221                                                    y_offset + row_ptr->baseline(), 
3222                                                    tmpx, clear_area);
3223                 }
3224         }
3225         
3226         // is it a last row?
3227         LyXParagraph * par = row_ptr->par();
3228         if (row_ptr->par() == par
3229             && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par())) {
3230                 // think about the margins
3231                 if (!row_ptr->next() && bv_owner)
3232                         y_bottom -= LYX_PAPER_MARGIN;
3233                 
3234                 // draw a bottom pagebreak
3235                 if (firstpar->params.pagebreakBottom()) {
3236                         LyXFont pb_font;
3237                         pb_font.setColor(LColor::pagebreak).decSize();
3238                         int const y_place = y_offset + y_bottom
3239                                 - 2 * DefaultHeight();
3240                         
3241                         int w = 0;
3242                         int a = 0;
3243                         int d = 0;
3244                         pain
3245                                 .line(0, y_place, ww, y_place,
3246                                       LColor::pagebreak,
3247                                       Painter::line_onoffdash)
3248                                 .rectText(0, 0,
3249                                           _("Page Break (bottom)"),
3250                                           pb_font,
3251                                           LColor::background,
3252                                           LColor::background, false, w, a, d);
3253                         pain.rectText((ww - w) / 2, y_place + d,
3254                                       _("Page Break (bottom)"),
3255                                       pb_font,
3256                                       LColor::background,
3257                                       LColor::background);
3258                         y_bottom -= 3 * DefaultHeight();
3259                 }
3260                 
3261                 if (firstpar->params.spaceBottom().kind() == VSpace::VFILL) {
3262                         // draw a vfill bottom
3263                         int const y_place = y_offset + y_bottom
3264                                 - 3 * DefaultHeight();
3265                         
3266                         pain.line(0, y_place,
3267                                   LYX_PAPER_MARGIN, y_place,
3268                                   LColor::vfillline);
3269                         pain.line(0, y_offset + y_bottom - 2,
3270                                   LYX_PAPER_MARGIN,
3271                                   y_offset + y_bottom - 2,
3272                                   LColor::vfillline);
3273                         pain.line(LYX_PAPER_MARGIN / 2,
3274                                   y_place,
3275                                   LYX_PAPER_MARGIN / 2,
3276                                   y_offset + y_bottom - 2,
3277                                   LColor::vfillline);
3278                         y_bottom -= 3 * DefaultHeight();
3279                 }
3280                 
3281                 // think about user added space
3282                 y_bottom -= int(firstpar->params.spaceBottom().inPixels(bview));
3283                 
3284                 if (firstpar->params.lineBottom()) {
3285                         // draw a bottom line
3286                         y_bottom -= lyxfont::ascent('x',
3287                                                     GetFont(bview->buffer(),
3288                                                             par,
3289                                                             par->size() - 1));
3290                         int const w = (inset_owner ?
3291                                        inset_owner->width(bview, font) : ww);
3292                         int const xp = static_cast<int>(inset_owner ? x : 0);
3293                         pain.line(xp, y_offset + y_bottom,
3294                                   w, y_offset + y_bottom,
3295                                   LColor::topline, Painter::line_solid,
3296                                   Painter::line_thick);
3297                         y_bottom -= lyxfont::ascent('x',
3298                                                     GetFont(bview->buffer(),
3299                                                             par,
3300                                                             par->size() - 1));
3301                 }
3302
3303                 // draw an endlabel
3304                 int const endlabel =
3305                         row_ptr->par()->GetEndLabel(bview->buffer()->params);
3306                 switch (endlabel) {
3307                 case END_LABEL_BOX:
3308                 case END_LABEL_FILLED_BOX:
3309                 {
3310                         LyXFont const font = GetFont(bview->buffer(),
3311                                                      row_ptr->par(), last);
3312                         int const size = int(0.75 * lyxfont::maxAscent(font));
3313                         int const y = (y_offset + row_ptr->baseline()) - size;
3314                         int x = is_rtl ? LYX_PAPER_MARGIN 
3315                                 : ww - LYX_PAPER_MARGIN - size;
3316
3317                         if (row_ptr->fill() <= size)
3318                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
3319                         if (endlabel == END_LABEL_BOX) {
3320                                 pain.line(x, y, x, y + size,
3321                                           LColor::eolmarker);
3322                                 pain.line(x + size, y, x + size , y + size,
3323                                           LColor::eolmarker);
3324                                 pain.line(x, y, x + size, y,
3325                                           LColor::eolmarker);
3326                                 pain.line(x, y + size, x + size, y + size,
3327                                           LColor::eolmarker);
3328                         } else
3329                                 pain.fillRectangle(x, y, size, size,
3330                                                    LColor::eolmarker);
3331                         break;
3332                 }
3333                 case END_LABEL_STATIC:
3334                 {
3335                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->GetLayout();
3336                         string const tmpstring = textclasslist.
3337                                 Style(bview->buffer()->params.textclass,
3338                                       layout).endlabelstring();
3339                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
3340                         int const tmpx = is_rtl ?
3341                                 int(x) - lyxfont::width(tmpstring, font)
3342                                 : ww - RightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
3343                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
3344                         break;
3345                 }
3346                 case END_LABEL_NO_LABEL:
3347                         break;
3348                 }
3349         }
3350         
3351         // draw the text in the pixmap
3352         
3353         vpos = row_ptr->pos();
3354
3355         LyXParagraph::size_type main_body = 
3356                 BeginningOfMainBody(bview->buffer(), row_ptr->par());
3357         if (main_body > 0 &&
3358             (main_body-1 > last || 
3359              !row_ptr->par()->IsLineSeparator(main_body - 1)))
3360                 main_body = 0;
3361         
3362         while (vpos <= last)  {
3363                 pos = vis2log(vpos);
3364                 if (main_body > 0 && pos == main_body - 1) {
3365                         x += fill_label_hfill
3366                                 + lyxfont::width(layout.labelsep,
3367                                                  GetFont(bview->buffer(),
3368                                                          row_ptr->par(), -2))
3369                                 - SingleWidth(bview,
3370                                               row_ptr->par(),
3371                                               main_body - 1);
3372                 }
3373                 
3374                 if (row_ptr->par() ->IsHfill(pos)) {
3375                         x += 1;
3376                         pain.line(int(x),
3377                                   y_offset + row_ptr->baseline() - DefaultHeight() / 2,
3378                                   int(x),
3379                                   y_offset + row_ptr->baseline(),
3380                                   LColor::vfillline);
3381                         
3382                         if (HfillExpansion(bview->buffer(),
3383                                            row_ptr, pos)) {
3384                                 if (pos >= main_body) {
3385                                         pain.line(int(x),
3386                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3387                                                   int(x + fill_hfill),
3388                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3389                                                   LColor::vfillline,
3390                                                   Painter::line_onoffdash);
3391                                         x += fill_hfill;
3392                                 } else {
3393                                         pain.line(int(x),
3394                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3395                                                   int(x + fill_label_hfill),
3396                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3397                                                   LColor::vfillline,
3398                                                   Painter::line_onoffdash);
3399                                         
3400                                         x += fill_label_hfill;
3401                                 }
3402                                 pain.line(int(x),
3403                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
3404                                           int(x),
3405                                           y_offset + row_ptr->baseline(),
3406                                           LColor::vfillline);
3407                         }
3408                         x += 2;
3409                         ++vpos;
3410                 } else if (row_ptr->par()->IsSeparator(pos)) {
3411                         x += SingleWidth(bview,
3412                                          row_ptr->par(), pos);
3413                         if (pos >= main_body)
3414                                 x += fill_separator;
3415                         ++vpos;
3416                 } else
3417                         draw(bview, row_ptr, vpos, y_offset, x, clear_area);
3418         }
3419 }
3420
3421
3422 int LyXText::DefaultHeight() const
3423 {
3424         LyXFont font(LyXFont::ALL_SANE);
3425         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3426 }
3427
3428    
3429 /* returns the column near the specified x-coordinate of the row 
3430 * x is set to the real beginning of this column  */ 
3431 int LyXText::GetColumnNearX(BufferView * bview, Row * row, int & x,
3432                             bool & boundary) const
3433 {
3434         float tmpx = 0.0;
3435         float fill_separator, fill_hfill, fill_label_hfill;
3436    
3437         PrepareToPrint(bview, row, tmpx, fill_separator,
3438                        fill_hfill, fill_label_hfill);
3439
3440         LyXParagraph::size_type vc = row->pos();
3441         LyXParagraph::size_type last = RowLastPrintable(row);
3442         LyXParagraph::size_type c = 0;
3443         LyXLayout const & layout =
3444                 textclasslist.Style(bview->buffer()->params.textclass,
3445                                     row->par()->GetLayout());
3446         bool left_side = false;
3447
3448         LyXParagraph::size_type
3449                 main_body = BeginningOfMainBody(bview->buffer(), row->par());
3450         float last_tmpx = tmpx;
3451         
3452         if (main_body > 0 &&
3453             (main_body-1 > last || 
3454              !row->par()->IsLineSeparator(main_body - 1)))
3455                 main_body = 0;
3456         
3457         while (vc <= last && tmpx <= x) {
3458                 c = vis2log(vc);
3459                 last_tmpx = tmpx;
3460                 if (main_body > 0 && c == main_body-1) {
3461                         tmpx += fill_label_hfill +
3462                                 lyxfont::width(layout.labelsep,
3463                                                GetFont(bview->buffer(), row->par(), -2));
3464                         if (row->par()->IsLineSeparator(main_body - 1))
3465                                 tmpx -= SingleWidth(bview, row->par(), main_body-1);
3466                 }
3467                 
3468                 if (HfillExpansion(bview->buffer(), row, c)) {
3469                         x += SingleWidth(bview, row->par(), c);
3470                         if (c >= main_body)
3471                                 tmpx += fill_hfill;
3472                         else
3473                                 tmpx += fill_label_hfill;
3474                 }
3475                 else if (row->par()->IsSeparator(c)) {
3476                         tmpx += SingleWidth(bview, row->par(), c);
3477                         if (c >= main_body)
3478                                 tmpx+= fill_separator;
3479                 } else
3480                         tmpx += SingleWidth(bview, row->par(), c);
3481                 ++vc;
3482         }
3483         
3484         if ((tmpx + last_tmpx) / 2 > x) {
3485                 tmpx = last_tmpx;
3486                 left_side = true;
3487         }
3488
3489         if (vc > last + 1)  // This shouldn't happen.
3490                 vc = last + 1;
3491
3492         boundary = false;
3493         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3494                                          // some speedup if rtl_support=false
3495                 && (!row->next() || row->next()->par() != row->par());
3496         bool const rtl = (lastrow)
3497                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3498                 : false; // If lastrow is false, we don't need to compute
3499                          // the value of rtl.
3500
3501         if (row->pos() > last)  // Row is empty?
3502                 c = row->pos();
3503         else if (lastrow &&
3504                  ( ( rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3505                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5) ))
3506                 c = last + 1;
3507         else if (vc == row->pos()) {
3508                 c = vis2log(vc);
3509                 if (bidi_level(c) % 2 == 1)
3510                         ++c;
3511         } else {
3512                 c = vis2log(vc - 1);
3513                 bool const rtl = (bidi_level(c) % 2 == 1);
3514                 if (left_side == rtl) {
3515                         ++c;
3516                         boundary = IsBoundary(bview->buffer(), row->par(), c);
3517                 }
3518         }
3519
3520         if (row->pos() <= last && c > last
3521             && row->par()->IsNewline(last)) {
3522                 if (bidi_level(last) % 2 == 0)
3523                         tmpx -= SingleWidth(bview, row->par(), last);
3524                 else
3525                         tmpx += SingleWidth(bview, row->par(), last);
3526                 c = last;
3527         }
3528
3529         c -= row->pos();
3530         x = int(tmpx);
3531         return c;
3532 }
3533
3534
3535 // returns pointer to a specified row
3536 Row * LyXText::GetRow(LyXParagraph * par,
3537                       LyXParagraph::size_type pos, int & y) const
3538 {
3539         if (!firstrow)
3540                 return 0;
3541         
3542         Row * tmprow = firstrow;
3543         y = 0;
3544         
3545         // find the first row of the specified paragraph
3546         while (tmprow->next() && tmprow->par() != par) {
3547                 y += tmprow->height();
3548                 tmprow = tmprow->next();
3549         }
3550         
3551         // now find the wanted row
3552         while (tmprow->pos() < pos
3553                && tmprow->next()
3554                && tmprow->next()->par() == par
3555                && tmprow->next()->pos() <= pos) {
3556                 y += tmprow->height();
3557                 tmprow = tmprow->next();
3558         }
3559         
3560         return tmprow;
3561 }