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