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