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