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