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