]> git.lyx.org Git - features.git/blob - src/text.C
3b9a19e085f17d7a6c251818b8944c97c48e7165
[features.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 #if 0
926                                         last_separator = i;
927                                         x += width;
928 #else
929                                         x += singleWidth(bview, par, i, c);
930 #endif
931                                 }
932                         } else  {
933                                 if (IsLineSeparatorChar(c))
934                                         last_separator = i;
935                                 x += singleWidth(bview, par, i, c);
936                         }
937                         ++i;
938                         if (i == main_body) {
939                                 x += lyxfont::width(layout.labelsep,
940                                                     getFont(bview->buffer(), par, -2));
941                                 if (par->isLineSeparator(i - 1))
942                                         x-= singleWidth(bview, par, i - 1);
943                                 int left_margin = labelEnd(bview, row);
944                                 if (x < left_margin)
945                                         x = left_margin;
946                         }
947                 }
948                 // end of paragraph is always a suitable separator
949                 if (i == last && x < width)
950                         last_separator = i;
951         }
952         
953         // well, if last_separator is still 0, the line isn't breakable. 
954         // don't care and cut simply at the end
955         if (last_separator < 0) {
956                 last_separator = i;
957         }
958         
959         // manual labels cannot be broken in LaTeX, do not care
960         if (main_body && last_separator < main_body)
961                 last_separator = main_body - 1;
962         
963         return last_separator;
964 }
965
966
967 // returns the minimum space a row needs on the screen in pixel
968 int LyXText::fill(BufferView * bview, Row * row, int paper_width) const
969 {
970         if (paper_width < 0)
971                 return 20;
972
973         int w;
974         // get the pure distance
975         Paragraph::size_type const last = rowLastPrintable(row);
976         
977         // special handling of the right address boxes
978         if (textclasslist.Style(bview->buffer()->params.textclass,
979                                 row->par()->getLayout()).margintype
980             == MARGIN_RIGHT_ADDRESS_BOX) {
981                 int const tmpfill = row->fill();
982                 row->fill(0); // the minfill in MarginLeft()
983                 w = leftMargin(bview, row);
984                 row->fill(tmpfill);
985         } else
986                 w = leftMargin(bview, row);
987         
988         LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
989                                                        row->par()->getLayout());
990         Paragraph::size_type const main_body = 
991                 beginningOfMainBody(bview->buffer(), row->par());
992         Paragraph::size_type i = row->pos();
993
994         while (i <= last) {
995                 if (main_body > 0 && i == main_body) {
996                         w += lyxfont::width(layout.labelsep, getFont(bview->buffer(), row->par(), -2));
997                         if (row->par()->isLineSeparator(i - 1))
998                                 w -= singleWidth(bview, row->par(), i - 1);
999                         int left_margin = labelEnd(bview, row);
1000                         if (w < left_margin)
1001                                 w = left_margin;
1002                 }
1003                 w += singleWidth(bview, row->par(), i);
1004                 ++i;
1005         }
1006         if (main_body > 0 && main_body > last) {
1007                 w += lyxfont::width(layout.labelsep, getFont(bview->buffer(), row->par(), -2));
1008                 if (last >= 0 && row->par()->isLineSeparator(last))
1009                         w -= singleWidth(bview, row->par(), last);
1010                 int const left_margin = labelEnd(bview, row);
1011                 if (w < left_margin)
1012                         w = left_margin;
1013         }
1014         
1015         int const fill = paper_width - w - rightMargin(bview->buffer(), row);
1016 #ifdef WITH_WARNINGS
1017 #warning Please fix me (Jug!)
1018 #endif
1019 #if 0
1020         if (fill < 0)
1021                 return 0;
1022 #endif
1023         return fill;
1024 }
1025
1026
1027 // returns the minimum space a manual label needs on the screen in pixel
1028 int LyXText::labelFill(BufferView * bview, Row const * row) const
1029 {
1030         Paragraph::size_type last = beginningOfMainBody(bview->buffer(), row->par()) - 1;
1031         // -1 because a label ends either with a space that is in the label, 
1032         // or with the beginning of a footnote that is outside the label.
1033
1034         // I don't understand this code in depth, but sometimes "last" is
1035         // less than 0 and this causes a crash. This fix seems to work
1036         // correctly, but I bet the real error is elsewhere.  The bug is
1037         // triggered when you have an open footnote in a paragraph
1038         // environment with a manual label. (Asger)
1039         if (last < 0) last = 0;
1040         
1041         if (row->par()->isLineSeparator(last)) /* a sepearator at this end 
1042                                                 does not count */
1043                 --last;
1044         
1045         int w = 0;
1046         int i = row->pos();
1047         while (i <= last) {
1048                 w += singleWidth(bview, row->par(), i);
1049                 ++i;
1050         }
1051         
1052         int fill = 0;
1053         if (!row->par()->params().labelWidthString().empty()) {
1054                 fill = max(lyxfont::width(row->par()->params().labelWidthString(),
1055                                           getFont(bview->buffer(), row->par(), -2)) - w,
1056                            0);
1057         }
1058         
1059         return fill;
1060 }
1061
1062
1063 // returns the number of separators in the specified row. The separator 
1064 // on the very last column doesnt count
1065 int LyXText::numberOfSeparators(Buffer const * buf, Row const * row) const
1066 {
1067         Paragraph::size_type const last = rowLast(row);
1068         Paragraph::size_type p =
1069                 max(row->pos(), beginningOfMainBody(buf, row->par()));
1070         int n = 0;
1071         for (; p < last; ++p) {
1072                 if (row->par()->isSeparator(p)) {
1073                         ++n;
1074                 }
1075         }
1076         return n;
1077 }
1078
1079
1080 // returns the number of hfills in the specified row. The LyX-Hfill is
1081 // a LaTeX \hfill so that the hfills at the beginning and at the end were 
1082 // ignored. This is *MUCH* more usefull than not to ignore!
1083 int LyXText::numberOfHfills(Buffer const * buf, Row const * row) const
1084 {
1085         Paragraph::size_type const last = rowLast(row);
1086         Paragraph::size_type first = row->pos();
1087         if (first) { /* hfill *DO* count at the beginning 
1088                       * of paragraphs! */
1089                 while(first <= last && row->par()->isHfill(first))
1090                         ++first;
1091         }
1092
1093         first = max(first, beginningOfMainBody(buf, row->par()));
1094         int n = 0;
1095         for (int p = first; p <= last; ++p) { // last, because the end is ignored!
1096                 if (row->par()->isHfill(p)) {
1097                         ++n;
1098                 }
1099         }
1100         return n;
1101 }
1102
1103
1104 // like NumberOfHfills, but only those in the manual label!
1105 int LyXText::numberOfLabelHfills(Buffer const * buf, Row const * row) const
1106 {
1107         Paragraph::size_type last = rowLast(row);
1108         Paragraph::size_type first = row->pos();
1109         if (first) { /* hfill *DO* count at the beginning 
1110                       * of paragraphs! */
1111                 while(first < last && row->par()->isHfill(first))
1112                         ++first;
1113         }
1114
1115         last = min(last, beginningOfMainBody(buf, row->par()));
1116         int n = 0;
1117         for (Paragraph::size_type p = first;
1118              p < last; ++p) {  // last, because the end is ignored!
1119                 if (row->par()->isHfill(p)) {
1120                         ++n;
1121                 }
1122         }
1123         return n;
1124 }
1125
1126
1127 // returns true, if a expansion is needed.
1128 // Rules are given by LaTeX
1129 bool LyXText::hfillExpansion(Buffer const * buf, Row const * row_ptr,
1130                              Paragraph::size_type pos) const
1131 {
1132         // by the way, is it a hfill?
1133         if (!row_ptr->par()->isHfill(pos))
1134                 return false;
1135         
1136         // at the end of a row it does not count
1137         if (pos >= rowLast(row_ptr))
1138                 return false;
1139         
1140         // at the beginning of a row it does not count, if it is not 
1141         // the first row of a paragaph
1142         if (!row_ptr->pos())
1143                 return true;
1144         
1145         // in some labels  it does not count
1146         if (textclasslist.Style(buf->params.textclass,
1147                                 row_ptr->par()->getLayout()).margintype
1148             != MARGIN_MANUAL
1149             && pos < beginningOfMainBody(buf, row_ptr->par()))
1150                 return false; 
1151         
1152         // if there is anything between the first char of the row and
1153         // the sepcified position that is not a newline and not a hfill,
1154         // the hfill will count, otherwise not
1155         Paragraph::size_type i = row_ptr->pos();
1156         while (i < pos && (row_ptr->par()->isNewline(i)
1157                            || row_ptr->par()->isHfill(i)))
1158                 ++i;
1159         
1160         return i != pos;
1161 }
1162
1163
1164 void LyXText::setHeightOfRow(BufferView * bview, Row * row_ptr) const
1165 {
1166     /* get the maximum ascent and the maximum descent */
1167    int asc = 0;
1168    int desc = 0;
1169    float layoutasc = 0;
1170    float layoutdesc = 0;
1171    float tmptop = 0;
1172    LyXFont tmpfont;
1173    Inset * tmpinset = 0;
1174
1175    /* this must not happen before the currentrow for clear reasons.
1176       so the trick is just to set the current row onto this row */
1177    int unused_y;
1178    getRow(row_ptr->par(), row_ptr->pos(), unused_y);
1179
1180    /* ok , let us initialize the maxasc and maxdesc value. 
1181     * This depends in LaTeX of the font of the last character
1182     * in the paragraph. The hack below is necessary because
1183     * of the possibility of open footnotes */
1184
1185    /* Correction: only the fontsize count. The other properties
1186       are taken from the layoutfont. Nicer on the screen :) */
1187    Paragraph * par = row_ptr->par();
1188    Paragraph * firstpar = row_ptr->par();
1189    
1190    LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
1191                                                   firstpar->getLayout());
1192
1193    LyXFont font = getFont(bview->buffer(), par, par->size() - 1);
1194    LyXFont::FONT_SIZE const size = font.size();
1195    font = getFont(bview->buffer(), par, -1);
1196    font.setSize(size);
1197
1198    LyXFont labelfont = getFont(bview->buffer(), par, -2);
1199
1200    float spacing_val = 1.0;
1201    if (!row_ptr->par()->params().spacing().isDefault()) {
1202            spacing_val = row_ptr->par()->params().spacing().getValue();
1203    } else {
1204            spacing_val = bview->buffer()->params.spacing.getValue();
1205    }
1206    //lyxerr << "spacing_val = " << spacing_val << endl;
1207    
1208    int maxasc = int(lyxfont::maxAscent(font) *
1209                    layout.spacing.getValue() *
1210                    spacing_val);
1211    int maxdesc = int(lyxfont::maxDescent(font) *
1212                     layout.spacing.getValue() *
1213                     spacing_val);
1214    int const pos_end = rowLast(row_ptr);
1215    int labeladdon = 0;
1216    int maxwidth = 0;
1217
1218    // Check if any insets are larger
1219    for (int pos = row_ptr->pos(); pos <= pos_end; ++pos) {
1220            if (row_ptr->par()->getChar(pos) == Paragraph::META_INSET) {
1221                    tmpfont = getFont(bview->buffer(), row_ptr->par(), pos);
1222                    tmpinset = row_ptr->par()->getInset(pos);
1223                    if (tmpinset) {
1224 #if 1 // this is needed for deep update on initialitation
1225                            tmpinset->update(bview, tmpfont);
1226 #endif
1227                            asc = tmpinset->ascent(bview, tmpfont);
1228                            desc = tmpinset->descent(bview, tmpfont);
1229                            maxwidth += tmpinset->width(bview, tmpfont);
1230                            maxasc = max(maxasc, asc);
1231                            maxdesc = max(maxdesc, desc);
1232                    }
1233            } else {
1234                    maxwidth += singleWidth(bview, row_ptr->par(), pos);
1235            }
1236    }
1237
1238    // Check if any custom fonts are larger (Asger)
1239    // This is not completely correct, but we can live with the small,
1240    // cosmetic error for now.
1241    LyXFont::FONT_SIZE const maxsize =
1242            row_ptr->par()->highestFontInRange(row_ptr->pos(),
1243                                               pos_end);
1244    if (maxsize > font.size()) {
1245         font.setSize(maxsize);
1246
1247         asc = lyxfont::maxAscent(font);
1248         desc = lyxfont::maxDescent(font);
1249         if (asc > maxasc) 
1250                 maxasc = asc;
1251         if (desc > maxdesc)
1252                 maxdesc = desc;
1253    }
1254
1255    // This is nicer with box insets:
1256    ++maxasc;
1257    ++maxdesc;
1258
1259    row_ptr->ascent_of_text(maxasc);
1260    
1261    // is it a top line?
1262    if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
1263       
1264            // some parksips VERY EASY IMPLEMENTATION
1265       if (bview->buffer()->params.paragraph_separation ==
1266           BufferParams::PARSEP_SKIP) {
1267          if (layout.isParagraph()
1268              && firstpar->getDepth() == 0
1269              && firstpar->previous())
1270             maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1271          else if (firstpar->previous()
1272                   && textclasslist.Style(bview->buffer()->params.textclass,
1273                            firstpar->previous()->getLayout()).isParagraph()
1274                   && firstpar->previous()->getDepth() == 0)
1275            // is it right to use defskip here too? (AS)
1276            maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1277       }
1278       
1279       // the paper margins
1280       if (!row_ptr->par()->previous() && bv_owner)
1281          maxasc += LYX_PAPER_MARGIN;
1282       
1283       // add the vertical spaces, that the user added
1284       if (firstpar->params().spaceTop().kind() != VSpace::NONE)
1285          maxasc += int(firstpar->params().spaceTop().inPixels(bview));
1286       
1287       // do not forget the DTP-lines!
1288       // there height depends on the font of the nearest character
1289       if (firstpar->params().lineTop())
1290          maxasc += 2 * lyxfont::ascent('x', getFont(bview->buffer(),
1291                                                     firstpar, 0));
1292       
1293       // and now the pagebreaks
1294       if (firstpar->params().pagebreakTop())
1295          maxasc += 3 * defaultHeight();
1296       
1297       // This is special code for the chapter, since the label of this
1298       // layout is printed in an extra row
1299       if (layout.labeltype == LABEL_COUNTER_CHAPTER
1300           && bview->buffer()->params.secnumdepth >= 0) {
1301               float spacing_val = 1.0;
1302               if (!row_ptr->par()->params().spacing().isDefault()) {
1303                       spacing_val = row_ptr->par()->params().spacing().getValue();
1304               } else {
1305                       spacing_val = bview->buffer()->params.spacing.getValue();
1306               }
1307               
1308               labeladdon = int(lyxfont::maxDescent(labelfont) *
1309                                layout.spacing.getValue() *
1310                                spacing_val)
1311                       + int(lyxfont::maxAscent(labelfont) *
1312                             layout.spacing.getValue() *
1313                             spacing_val);
1314       }
1315       
1316       // special code for the top label
1317       if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1318            || layout.labeltype == LABEL_BIBLIO
1319            || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1320           && row_ptr->par()->isFirstInSequence()
1321           && !row_ptr->par()->getLabelstring().empty()) {
1322               float spacing_val = 1.0;
1323               if (!row_ptr->par()->params().spacing().isDefault()) {
1324                       spacing_val = row_ptr->par()->params().spacing().getValue();
1325               } else {
1326                       spacing_val = bview->buffer()->params.spacing.getValue();
1327               }
1328               
1329               labeladdon = int(
1330                       (lyxfont::maxAscent(labelfont) *
1331                        layout.spacing.getValue() *
1332                        spacing_val)
1333                       +(lyxfont::maxDescent(labelfont) *
1334                         layout.spacing.getValue() *
1335                         spacing_val)
1336                       + layout.topsep * defaultHeight()
1337                       + layout.labelbottomsep *  defaultHeight());
1338       }
1339    
1340       // and now the layout spaces, for example before and after a section, 
1341       // or between the items of a itemize or enumerate environment
1342       
1343       if (!firstpar->params().pagebreakTop()) {
1344          Paragraph * prev = row_ptr->par()->previous();
1345          if (prev)
1346             prev = row_ptr->par()->depthHook(row_ptr->par()->getDepth());
1347          if (prev && prev->getLayout() == firstpar->getLayout()
1348              && prev->getDepth() == firstpar->getDepth()
1349              && prev->getLabelWidthString() == firstpar->getLabelWidthString())
1350            {
1351               layoutasc = (layout.itemsep * defaultHeight());
1352            }
1353          else if (row_ptr->previous()) {
1354             tmptop = layout.topsep;
1355             
1356             if (row_ptr->previous()->par()->getDepth() >= row_ptr->par()->getDepth())
1357                tmptop -= textclasslist.Style(bview->buffer()->params.textclass,
1358                                              row_ptr->previous()->par()->
1359                                              getLayout()).bottomsep;
1360             
1361             if (tmptop > 0)
1362                layoutasc = (tmptop * defaultHeight());
1363          }
1364          else if (row_ptr->par()->params().lineTop()) {
1365             tmptop = layout.topsep;
1366             
1367             if (tmptop > 0)
1368                layoutasc = (tmptop * defaultHeight());
1369          }
1370          
1371          prev = row_ptr->par()->outerHook();
1372          if (prev)  {
1373             maxasc += int(textclasslist.Style(bview->buffer()->params.textclass,
1374                                          prev->getLayout()).parsep * defaultHeight());
1375          }
1376          else {
1377                 if (firstpar->previous()
1378                     && firstpar->previous()->getDepth() == 0
1379                     && firstpar->previous()->getLayout() != firstpar->getLayout()) {
1380                         // avoid parsep
1381                 }
1382             else if (firstpar->previous()){
1383                maxasc += int(layout.parsep * defaultHeight());
1384             }
1385          }
1386       }
1387    }
1388    
1389    // is it a bottom line?
1390    if (row_ptr->par() == par
1391        && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par())) {
1392           
1393            // the paper margins
1394           if (!par->next() && bv_owner)
1395             maxdesc += LYX_PAPER_MARGIN;
1396           
1397           // add the vertical spaces, that the user added
1398           if (firstpar->params().spaceBottom().kind() != VSpace::NONE)
1399                   maxdesc += int(firstpar->params().spaceBottom().inPixels(bview));
1400           
1401           // do not forget the DTP-lines!
1402           // there height depends on the font of the nearest character
1403           if (firstpar->params().lineBottom())
1404                   maxdesc += 2 * lyxfont::ascent('x',
1405                                                  getFont(bview->buffer(),
1406                                                          par, par->size() - 1));
1407           
1408           // and now the pagebreaks
1409           if (firstpar->params().pagebreakBottom())
1410             maxdesc += 3 * defaultHeight();
1411           
1412           // and now the layout spaces, for example before and after
1413           // a section, or between the items of a itemize or enumerate
1414           // environment
1415           if (!firstpar->params().pagebreakBottom() && row_ptr->par()->next()) {
1416              Paragraph * nextpar = row_ptr->par()->next();
1417              Paragraph * comparepar = row_ptr->par();
1418              float usual = 0;
1419              float unusual = 0;
1420              
1421              if (comparepar->getDepth() > nextpar->getDepth()) {
1422                 usual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->getLayout()).bottomsep * defaultHeight());
1423                 comparepar = comparepar->depthHook(nextpar->getDepth());
1424                 if (comparepar->getLayout()!= nextpar->getLayout()
1425                     || nextpar->getLabelWidthString() != 
1426                         comparepar->getLabelWidthString())
1427                   unusual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->getLayout()).bottomsep * defaultHeight());
1428                 
1429                 if (unusual > usual)
1430                   layoutdesc = unusual;
1431                 else
1432                   layoutdesc = usual;
1433              }
1434              else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1435                 
1436                 if (comparepar->getLayout()!= nextpar->getLayout()
1437                     || nextpar->getLabelWidthString() != 
1438                         comparepar->getLabelWidthString())
1439                   layoutdesc = int(textclasslist.Style(bview->buffer()->params.textclass, comparepar->getLayout()).bottomsep * defaultHeight());
1440              }
1441           }
1442        }
1443    
1444    // incalculate the layout spaces
1445    maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1446    maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1447
1448    // calculate the new height of the text
1449    height -= row_ptr->height();
1450    
1451    row_ptr->height(maxasc + maxdesc + labeladdon);
1452    row_ptr->baseline(maxasc + labeladdon);
1453    
1454    height += row_ptr->height();
1455    float x;
1456    float dummy;
1457    prepareToPrint(bview, row_ptr, x, dummy, dummy, dummy, false);
1458    row_ptr->width(int(maxwidth + x));
1459    if (inset_owner) {
1460            Row * r = firstrow;
1461            width = max(0,workWidth(bview));
1462            while(r) {
1463                    if (r->width() > width)
1464                            width = r->width();
1465                    r = r->next();
1466            }
1467    }
1468 }
1469
1470
1471 /* Appends the implicit specified paragraph behind the specified row,
1472  * start at the implicit given position */
1473 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1474 {
1475    bool not_ready = true;
1476    
1477    // The last character position of a paragraph is an invariant so we can 
1478    // safely get it here. (Asger)
1479    int const lastposition = row->par()->size();
1480    do {
1481       // Get the next breakpoint
1482       int z = nextBreakPoint(bview, row, workWidth(bview));
1483       
1484       Row * tmprow = row;
1485
1486       // Insert the new row
1487       if (z < lastposition) {
1488          ++z;
1489          insertRow(row, row->par(), z);
1490          row = row->next();
1491
1492          row->height(0);
1493       } else
1494          not_ready = false;
1495       
1496       // Set the dimensions of the row
1497       tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1498       setHeightOfRow(bview, tmprow);
1499
1500    } while (not_ready);
1501 }
1502
1503
1504 void LyXText::breakAgain(BufferView * bview, Row * row) const
1505 {
1506         bool not_ready = true;
1507    
1508         do  {
1509                 // get the next breakpoint
1510                 Paragraph::size_type z = nextBreakPoint(bview, row, workWidth(bview));
1511                 Row * tmprow = row;
1512
1513                 if (z < row->par()->size()) {
1514                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1515                                 // insert a new row
1516                                 ++z;
1517                                 insertRow(row, row->par(), z);
1518                                 row = row->next();
1519                                 row->height(0);
1520                         } else  {
1521                                 row = row->next();
1522                                 ++z;
1523                                 if (row->pos() == z)
1524                                         not_ready = false;     // the rest will not change
1525                                 else {
1526                                         row->pos(z);
1527                                 }
1528                         }
1529                 } else {
1530                         /* if there are some rows too much, delete them */
1531                         /* only if you broke the whole paragraph! */ 
1532                         Row * tmprow2 = row;
1533                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1534                                 tmprow2 = tmprow2->next();
1535                         }
1536                         while (tmprow2 != row) {
1537                                 tmprow2 = tmprow2->previous();
1538                                 removeRow(tmprow2->next());
1539                         }
1540                         not_ready = false;
1541                 }
1542                 
1543                 /* set the dimensions of the row */ 
1544                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1545                 setHeightOfRow(bview, tmprow);
1546         } while (not_ready);
1547 }
1548
1549
1550 // this is just a little changed version of break again
1551 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1552 {
1553         // get the next breakpoint
1554         Paragraph::size_type z = nextBreakPoint(bview, row, workWidth(bview));
1555         Row * tmprow = row;
1556
1557         if (z < row->par()->size()) {
1558                 if (!row->next()
1559                     || (row->next() && row->next()->par() != row->par())) {
1560                         /* insert a new row */ 
1561                         ++z;
1562                         insertRow(row, row->par(), z);
1563                         row = row->next();
1564                         row->height(0);
1565                 } else  {
1566                         row= row->next();
1567                         ++z;
1568                         if (row->pos() != z)
1569                                 row->pos(z);
1570                 }
1571         } else {
1572                 // if there are some rows too much, delete them
1573                 // only if you broke the whole paragraph!
1574                 Row * tmprow2 = row;
1575                 while (tmprow2->next()
1576                        && tmprow2->next()->par() == row->par()) {
1577                         tmprow2 = tmprow2->next();
1578                 }
1579                 while (tmprow2 != row) {
1580                         tmprow2 = tmprow2->previous();
1581                         removeRow(tmprow2->next());
1582                 }
1583         }
1584         
1585         // set the dimensions of the row
1586         tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1587         setHeightOfRow(bview, tmprow);
1588 }
1589
1590
1591 void LyXText::breakParagraph(BufferView * bview, char keep_layout)
1592 {
1593    LyXLayout const & layout =
1594            textclasslist.Style(bview->buffer()->params.textclass,
1595                                cursor.par()->getLayout());
1596
1597    // this is only allowed, if the current paragraph is not empty or caption
1598    if ((cursor.par()->size() <= 0)
1599        && layout.labeltype!= LABEL_SENSITIVE)
1600            return;
1601    
1602    setUndo(bview->buffer(), Undo::INSERT,
1603            cursor.par()->previous(), 
1604            cursor.par()->next()); 
1605
1606    // Always break behind a space
1607    //
1608    // It is better to erase the space (Dekel)
1609    if (cursor.pos() < cursor.par()->size()
1610        && cursor.par()->isLineSeparator(cursor.pos()))
1611            cursor.par()->erase(cursor.pos());
1612            // cursor.pos(cursor.pos() + 1);
1613
1614    // break the paragraph
1615    if (keep_layout)
1616      keep_layout = 2;
1617    else 
1618      keep_layout = layout.isEnvironment();
1619    cursor.par()->breakParagraph(bview->buffer()->params, cursor.pos(),
1620                                 keep_layout);
1621
1622    // well this is the caption hack since one caption is really enough
1623    if (layout.labeltype == LABEL_SENSITIVE) {
1624      if (!cursor.pos())
1625              // set to standard-layout
1626              cursor.par()->setLayout(0);
1627      else
1628              // set to standard-layout
1629              cursor.par()->next()->setLayout(0);
1630    }
1631    
1632    /* if the cursor is at the beginning of a row without prior newline, 
1633     * move one row up! 
1634     * This touches only the screen-update. Otherwise we would may have
1635     * an empty row on the screen */
1636    if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1637        && cursor.row()->pos() == cursor.pos()) {
1638            cursorLeft(bview);
1639    } 
1640    
1641    status = LyXText::NEED_MORE_REFRESH;
1642    refresh_row = cursor.row();
1643    refresh_y = cursor.y() - cursor.row()->baseline();
1644    
1645    // Do not forget the special right address boxes
1646    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1647       while (refresh_row->previous() &&
1648              refresh_row->previous()->par() == refresh_row->par()) {
1649               refresh_row = refresh_row->previous();
1650               refresh_y -= refresh_row->height();
1651       }
1652    }
1653    removeParagraph(cursor.row());
1654    
1655    // set the dimensions of the cursor row
1656    cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1657
1658    setHeightOfRow(bview, cursor.row());
1659
1660    while (cursor.par()->next()->size()
1661           && cursor.par()->next()->isNewline(0))
1662            cursor.par()->next()->erase(0);
1663    
1664    insertParagraph(bview, cursor.par()->next(), cursor.row());
1665
1666    updateCounters(bview, cursor.row()->previous());
1667    
1668    /* This check is necessary. Otherwise the new empty paragraph will
1669     * be deleted automatically. And it is more friendly for the user! */ 
1670    if (cursor.pos())
1671            setCursor(bview, cursor.par()->next(), 0);
1672    else
1673            setCursor(bview, cursor.par(), 0);
1674    
1675    if (cursor.row()->next())
1676            breakAgain(bview, cursor.row()->next());
1677
1678    need_break_row = 0;
1679 }
1680
1681
1682 // Just a macro to make some thing easier. 
1683 void LyXText::redoParagraph(BufferView * bview) const
1684 {
1685         clearSelection(bview);
1686         redoParagraphs(bview, cursor, cursor.par()->next());
1687         setCursorIntern(bview, cursor.par(), cursor.pos());
1688 }
1689
1690
1691 /* insert a character, moves all the following breaks in the 
1692  * same Paragraph one to the right and make a rebreak */
1693 void LyXText::insertChar(BufferView * bview, char c)
1694 {
1695         setUndo(bview->buffer(), Undo::INSERT,
1696                 cursor.par()->previous(),
1697                 cursor.par()->next());
1698
1699         // When the free-spacing option is set for the current layout,
1700         // disable the double-space checking
1701
1702         bool const freeSpacing = 
1703                 textclasslist.Style(bview->buffer()->params.textclass,
1704                                cursor.row()->par()->getLayout()).free_spacing;
1705
1706
1707         if (lyxrc.auto_number) {
1708                 static string const number_operators = "+-/*";
1709                 static string const number_unary_operators = "+-";
1710                 static string const number_seperators = ".,:";
1711
1712                 if (current_font.number() == LyXFont::ON) {
1713                         if (!isdigit(c) && !contains(number_operators, c) &&
1714                             !(contains(number_seperators, c) &&
1715                               cursor.pos() >= 1 &&
1716                               cursor.pos() < cursor.par()->size() &&
1717                               getFont(bview->buffer(),
1718                                       cursor.par(),
1719                                       cursor.pos()).number() == LyXFont::ON &&
1720                               getFont(bview->buffer(),
1721                                       cursor.par(),
1722                                       cursor.pos()-1).number() == LyXFont::ON)
1723                             )
1724                                 Number(bview); // Set current_font.number to OFF
1725                 } else if (isdigit(c) &&
1726                            real_current_font.isVisibleRightToLeft()) {
1727                         Number(bview); // Set current_font.number to ON
1728
1729                         if (cursor.pos() > 0) {
1730                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1731                                 if (contains(number_unary_operators, c) &&
1732                                     (cursor.pos() == 1 ||
1733                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1734                                      cursor.par()->isNewline(cursor.pos() - 2) )
1735                                    ) {
1736                                         setCharFont(bview->buffer(),
1737                                                     cursor.par(),
1738                                                     cursor.pos() - 1,
1739                                                     current_font);
1740                                 } else if (contains(number_seperators, c) &&
1741                                            cursor.pos() >= 2 &&
1742                                            getFont(bview->buffer(),
1743                                                    cursor.par(),
1744                                                    cursor.pos()-2).number() == LyXFont::ON) {
1745                                         setCharFont(bview->buffer(),
1746                                                     cursor.par(),
1747                                                     cursor.pos() - 1,
1748                                                     current_font);
1749                                 }
1750                         }
1751                 }
1752         }
1753
1754
1755         /* First check, if there will be two blanks together or a blank at 
1756           the beginning of a paragraph. 
1757           I decided to handle blanks like normal characters, the main 
1758           difference are the special checks when calculating the row.fill
1759           (blank does not count at the end of a row) and the check here */ 
1760
1761         // The bug is triggered when we type in a description environment:
1762         // The current_font is not changed when we go from label to main text
1763         // and it should (along with realtmpfont) when we type the space.
1764         // CHECK There is a bug here! (Asger)
1765         
1766         LyXFont realtmpfont = real_current_font;
1767         LyXFont rawtmpfont = current_font;  /* store the current font.
1768                                      * This is because of the use
1769                                      * of cursor movements. The moving
1770                                      * cursor would refresh the 
1771                                      * current font */
1772
1773         // Get the font that is used to calculate the baselineskip
1774         Paragraph::size_type const lastpos = cursor.par()->size();
1775         LyXFont rawparfont =
1776                 cursor.par()->getFontSettings(bview->buffer()->params,
1777                                               lastpos - 1);
1778
1779         bool jumped_over_space = false;
1780    
1781         if (!freeSpacing && IsLineSeparatorChar(c)) {
1782                 if ((cursor.pos() > 0 
1783                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1784                     || (cursor.pos() > 0
1785                         && cursor.par()->isNewline(cursor.pos() - 1))
1786                     || (cursor.pos() == 0)) {
1787                         static bool sent_space_message = false;
1788                         if (!sent_space_message) {
1789                                 if (cursor.pos() == 0) 
1790                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1791                                 else
1792                                         bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1793                                 sent_space_message = true;
1794                         }
1795                         charInserted();
1796                         return;
1797                 }
1798         } else if (IsNewlineChar(c)) {
1799                 if (cursor.par() == cursor.par()
1800                     && cursor.pos() <= beginningOfMainBody(bview->buffer(), cursor.par())) {
1801                         charInserted();
1802                         return;
1803                 }
1804                 /* No newline at first position 
1805                  * of a paragraph or behind labels. 
1806                  * TeX does not allow that. */
1807
1808                 if (cursor.pos() < cursor.par()->size() &&
1809                     cursor.par()->isLineSeparator(cursor.pos()))
1810                         // newline always after a blank!
1811                         cursorRight(bview);
1812                 cursor.row()->fill(-1);        // to force a new break
1813         }
1814    
1815         // the display inset stuff
1816         if (cursor.row()->par()->getChar(cursor.row()->pos()) == Paragraph::META_INSET
1817             && cursor.row()->par()->getInset(cursor.row()->pos())
1818             && (cursor.row()->par()->getInset(cursor.row()->pos())->display() ||
1819                 cursor.row()->par()->getInset(cursor.row()->pos())->needFullRow()))
1820                 cursor.row()->fill(-1); // to force a new break  
1821
1822         // get the cursor row fist
1823         Row * row = cursor.row();
1824         int y = cursor.y() - row->baseline();
1825         if (c != Paragraph::META_INSET) /* Here case LyXText::InsertInset 
1826                                             * already insertet the character */
1827                 cursor.par()->insertChar(cursor.pos(), c);
1828         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1829
1830         if (!jumped_over_space) {
1831                 // refresh the positions
1832                 Row * tmprow = row;
1833                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1834                         tmprow = tmprow->next();
1835                         tmprow->pos(tmprow->pos() + 1);
1836                 }
1837         }
1838    
1839         // Is there a break one row above
1840         if ((cursor.par()->isLineSeparator(cursor.pos())
1841              || cursor.par()->isNewline(cursor.pos())
1842              || cursor.row()->fill() == -1)
1843             && row->previous() && row->previous()->par() == row->par()) {
1844                 Paragraph::size_type z = nextBreakPoint(bview,
1845                                                            row->previous(),
1846                                                            workWidth(bview));
1847                 if (z >= row->pos()) {
1848                         row->pos(z + 1);
1849                         
1850                         // set the dimensions of the row above
1851                         row->previous()->fill(fill(bview,
1852                                                    row->previous(),
1853                                                    workWidth(bview)));
1854
1855                         setHeightOfRow(bview, row->previous());
1856              
1857                         y -= row->previous()->height();
1858                         refresh_y = y;
1859                         refresh_row = row->previous();
1860                         status = LyXText::NEED_MORE_REFRESH;
1861              
1862                         breakAgainOneRow(bview, row);
1863
1864                         current_font = rawtmpfont;
1865                         real_current_font = realtmpfont;
1866                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1867                                   false, cursor.boundary());
1868                         // cursor MUST be in row now.
1869              
1870                         if (row->next() && row->next()->par() == row->par())
1871                                 need_break_row = row->next();
1872                         else
1873                                 need_break_row = 0;
1874              
1875                         // check, wether the last characters font has changed.
1876                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1877                             && rawparfont != rawtmpfont)
1878                                 redoHeightOfParagraph(bview, cursor);
1879                         
1880                         charInserted();
1881                         return;
1882                 }
1883         }
1884    
1885         // recalculate the fill of the row
1886         if (row->fill() >= 0)  /* needed because a newline
1887                               * will set fill to -1. Otherwise
1888                               * we would not get a rebreak! */
1889                 row->fill(fill(bview, row, workWidth(bview)));
1890         if (row->fill() < 0) {
1891                 refresh_y = y;
1892                 refresh_row = row; 
1893                 refresh_x = cursor.x();
1894                 refresh_pos = cursor.pos();
1895                 status = LyXText::NEED_MORE_REFRESH;
1896                 breakAgainOneRow(bview, row); 
1897                 // will the cursor be in another row now?
1898                 if (rowLast(row) <= cursor.pos() + 1 && row->next()) {
1899                         if (row->next() && row->next()->par() == row->par())
1900                                 // this should always be true
1901                                 row = row->next();
1902                         breakAgainOneRow(bview, row);
1903                 }
1904                 current_font = rawtmpfont;
1905                 real_current_font = realtmpfont;
1906
1907                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1908                           cursor.boundary());
1909                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1910                     != cursor.boundary())
1911                         setCursor(bview, cursor.par(), cursor.pos(), false,
1912                           !cursor.boundary());
1913                 if (row->next() && row->next()->par() == row->par())
1914                         need_break_row = row->next();
1915                 else
1916                         need_break_row = 0;             
1917         } else {
1918                 refresh_y = y;
1919                 refresh_x = cursor.x();
1920                 refresh_row = row;
1921                 refresh_pos = cursor.pos();
1922                 
1923                 int const tmpheight = row->height();
1924                 setHeightOfRow(bview, row);
1925                 if (tmpheight == row->height())
1926                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
1927                 else
1928                         status = LyXText::NEED_MORE_REFRESH;
1929             
1930                 current_font = rawtmpfont;
1931                 real_current_font = realtmpfont;
1932                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1933                           cursor.boundary());
1934         }
1935
1936         // check, wether the last characters font has changed.
1937         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1938             && rawparfont != rawtmpfont) {
1939                 redoHeightOfParagraph(bview, cursor);
1940         } else {
1941                 // now the special right address boxes
1942                 if (textclasslist.Style(bview->buffer()->params.textclass,
1943                                    cursor.par()->getLayout()).margintype
1944                     == MARGIN_RIGHT_ADDRESS_BOX) {
1945                         redoDrawingOfParagraph(bview, cursor); 
1946                 }
1947         }
1948
1949         charInserted();
1950 }
1951    
1952
1953 void LyXText::charInserted()
1954 {
1955         // Here we could call FinishUndo for every 20 characters inserted.
1956         // This is from my experience how emacs does it.
1957         static unsigned int counter;
1958         if (counter < 20) {
1959                 ++counter;
1960         } else {
1961                 finishUndo();
1962                 counter = 0;
1963         }
1964 }
1965
1966
1967 void LyXText::prepareToPrint(BufferView * bview,
1968                              Row * row, float & x,
1969                              float & fill_separator, 
1970                              float & fill_hfill,
1971                              float & fill_label_hfill,
1972                              bool bidi) const
1973 {
1974         float nlh;
1975         float ns;
1976         
1977         float w = row->fill();
1978         fill_hfill = 0;
1979         fill_label_hfill = 0;
1980         fill_separator = 0;
1981         fill_label_hfill = 0;
1982
1983         bool const is_rtl =
1984                 row->par()->isRightToLeftPar(bview->buffer()->params);
1985         if (is_rtl) {
1986                 x = (workWidth(bview) > 0)
1987                         ? rightMargin(bview->buffer(), row) : 0;
1988         } else
1989                 x = (workWidth(bview) > 0) ? leftMargin(bview, row) : 0;
1990         
1991         // is there a manual margin with a manual label
1992         if (textclasslist.Style(bview->buffer()->params.textclass,
1993                            row->par()->getLayout()).margintype == MARGIN_MANUAL
1994             && textclasslist.Style(bview->buffer()->params.textclass,
1995                               row->par()->getLayout()).labeltype == LABEL_MANUAL) {
1996                
1997                 /* one more since labels are left aligned */ 
1998                 nlh = numberOfLabelHfills(bview->buffer(), row) + 1;
1999                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2000                         fill_label_hfill = labelFill(bview, row) / nlh;
2001                 }
2002         }
2003                 
2004         // are there any hfills in the row?
2005         float const nh = numberOfHfills(bview->buffer(), row);
2006
2007         if (nh)
2008           fill_hfill = w / nh;
2009         else  {
2010                 // is it block, flushleft or flushright? 
2011                 // set x how you need it
2012         int align;
2013         if (row->par()->params().align() == LYX_ALIGN_LAYOUT)
2014           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->getLayout()).align;
2015         else
2016           align = row->par()->params().align();
2017            
2018         // center displayed insets 
2019         Inset * inset;
2020            if (row->par()->getChar(row->pos()) == Paragraph::META_INSET
2021                && (inset=row->par()->getInset(row->pos()))
2022                && (inset->display())) // || (inset->scroll() < 0)))
2023              align = (inset->LyxCode() == Inset::MATHMACRO_CODE)
2024                      ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2025
2026            switch (align) {
2027             case LYX_ALIGN_BLOCK:
2028               ns = numberOfSeparators(bview->buffer(), row);
2029               if (ns && row->next() && row->next()->par() == row->par() &&
2030                   !(row->next()->par()->isNewline(row->next()->pos() - 1))
2031                   && !(row->next()->par()->getChar(row->next()->pos()) == Paragraph::META_INSET
2032                        && row->next()->par()->getInset(row->next()->pos())
2033                        && row->next()->par()->getInset(row->next()->pos())->display())
2034                   )
2035                 fill_separator = w / ns;
2036               else if (is_rtl)
2037                 x += w;
2038               break;
2039             case LYX_ALIGN_RIGHT:
2040               x += w;
2041               break;
2042             case LYX_ALIGN_CENTER:
2043               x += w / 2;
2044               break;
2045            }
2046         }
2047         if (!bidi)
2048                 return;
2049
2050         computeBidiTables(bview->buffer(), row);
2051         if (is_rtl) {
2052                 Paragraph::size_type main_body = 
2053                         beginningOfMainBody(bview->buffer(), row->par());
2054                 Paragraph::size_type last = rowLast(row);
2055
2056                 if (main_body > 0 &&
2057                     (main_body-1 > last || 
2058                      !row->par()->isLineSeparator(main_body-1))) {
2059                         LyXLayout const & layout =
2060                                 textclasslist.Style(bview->buffer()->params.textclass,
2061                                                     row->par()->getLayout());
2062                         x += lyxfont::width(layout.labelsep,
2063                                             getFont(bview->buffer(), row->par(), -2));
2064                         if (main_body-1 <= last)
2065                                 x += fill_label_hfill;
2066                 }
2067         }
2068 }
2069       
2070 /* important for the screen */
2071
2072
2073 /* the cursor set functions have a special mechanism. When they
2074 * realize, that you left an empty paragraph, they will delete it.
2075 * They also delete the corresponding row */
2076
2077 void LyXText::cursorRightOneWord(BufferView * bview) const
2078 {
2079         // treat floats, HFills and Insets as words
2080         LyXCursor tmpcursor = cursor;
2081         // CHECK See comment on top of text.C
2082
2083         if (tmpcursor.pos() == tmpcursor.par()->size()
2084             && tmpcursor.par()->next()) {
2085                         tmpcursor.par(tmpcursor.par()->next());
2086                         tmpcursor.pos(0);
2087         } else {
2088                 int steps = 0;
2089
2090                 // Skip through initial nonword stuff.
2091                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2092                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2093                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2094                         tmpcursor.pos(tmpcursor.pos() + 1);
2095                         ++steps;
2096                 }
2097                 // Advance through word.
2098                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2099                         tmpcursor.par()->isWord( tmpcursor.pos())) {
2100                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2101                         tmpcursor.pos(tmpcursor.pos() + 1);
2102                         ++steps;
2103                 }
2104         }
2105         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2106 }
2107
2108
2109 void LyXText::cursorTab(BufferView * bview) const
2110 {
2111     LyXCursor tmpcursor = cursor;
2112     while (tmpcursor.pos() < tmpcursor.par()->size()
2113            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2114         tmpcursor.pos(tmpcursor.pos() + 1);
2115
2116     if (tmpcursor.pos() == tmpcursor.par()->size()){
2117         if (tmpcursor.par()->next()) {
2118             tmpcursor.par(tmpcursor.par()->next());
2119             tmpcursor.pos(0);
2120         }
2121     } else
2122         tmpcursor.pos(tmpcursor.pos() + 1);
2123     setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2124 }
2125
2126
2127 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2128             of prior word, not to end of next prior word. */
2129
2130 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2131 {
2132         // treat HFills, floats and Insets as words
2133         LyXCursor tmpcursor = cursor;
2134         while (tmpcursor.pos() 
2135                && (tmpcursor.par()->isSeparator(tmpcursor.pos() - 1) 
2136                    || tmpcursor.par()->isKomma(tmpcursor.pos() - 1))
2137                && !(tmpcursor.par()->isHfill(tmpcursor.pos() - 1)
2138                     || tmpcursor.par()->isInset(tmpcursor.pos() - 1)))
2139                 tmpcursor.pos(tmpcursor.pos() - 1);
2140
2141         if (tmpcursor.pos()
2142             && (tmpcursor.par()->isInset(tmpcursor.pos() - 1)
2143                 || tmpcursor.par()->isHfill(tmpcursor.pos() - 1))) {
2144                 tmpcursor.pos(tmpcursor.pos() - 1);
2145         } else if (!tmpcursor.pos()) {
2146                 if (tmpcursor.par()->previous()){
2147                         tmpcursor.par(tmpcursor.par()->previous());
2148                         tmpcursor.pos(tmpcursor.par()->size());
2149                 }
2150         } else {                // Here, tmpcursor != 0 
2151                 while (tmpcursor.pos() > 0 &&
2152                        tmpcursor.par()->isWord(tmpcursor.pos()-1) )
2153                         tmpcursor.pos(tmpcursor.pos() - 1);
2154         }
2155         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2156 }
2157
2158 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
2159                         patched as well. */
2160
2161 void LyXText::selectWord(BufferView * bview) 
2162 {
2163         // Move cursor to the beginning, when not already there.
2164         if (cursor.pos()
2165             && !cursor.par()->isSeparator(cursor.pos() - 1)
2166             && !cursor.par()->isKomma(cursor.pos() - 1))
2167                 cursorLeftOneWord(bview);
2168
2169         // set the sel cursor
2170 #if 0
2171         sel_cursor = cursor;
2172 #else
2173         selection.cursor = cursor;
2174 #endif
2175         
2176         while (cursor.pos() < cursor.par()->size()
2177                && !cursor.par()->isSeparator(cursor.pos())
2178                && !cursor.par()->isKomma(cursor.pos()) )
2179                 cursor.pos(cursor.pos() + 1);
2180         setCursor(bview, cursor.par(), cursor.pos() );
2181         
2182         // finally set the selection
2183         setSelection(bview);
2184 }
2185
2186
2187 /* -------> Select the word currently under the cursor when:
2188                         1: no selection is currently set,
2189                         2: the cursor is not at the borders of the word. */
2190
2191 bool LyXText::selectWordWhenUnderCursor(BufferView * bview) 
2192 {
2193 #if 0
2194         if (!selection &&
2195 #else
2196             if (!selection.set() &&
2197 #endif
2198             cursor.pos() > 0 && cursor.pos() < cursor.par()->size()
2199             && !cursor.par()->isSeparator(cursor.pos())
2200             && !cursor.par()->isKomma(cursor.pos())
2201             && !cursor.par()->isSeparator(cursor.pos() -1)
2202             && !cursor.par()->isKomma(cursor.pos() -1)) {
2203                 selectWord(bview);
2204                 return true;
2205         }
2206         return false;
2207 }
2208
2209
2210 // This function is only used by the spellchecker for NextWord().
2211 // It doesn't handle LYX_ACCENTs and probably never will.
2212 string const LyXText::selectNextWord(BufferView * bview,
2213                                      float & value) const
2214 {
2215         Paragraph * tmppar = cursor.par();
2216         
2217         // If this is not the very first word, skip rest of
2218         // current word because we are probably in the middle
2219         // of a word if there is text here.
2220         if (cursor.pos() || cursor.par()->previous()) {
2221                 while (cursor.pos() < cursor.par()->size()
2222                        && cursor.par()->isLetter(cursor.pos()))
2223                         cursor.pos(cursor.pos() + 1);
2224         }
2225         
2226         // Now, skip until we have real text (will jump paragraphs)
2227         while ((cursor.par()->size() > cursor.pos()
2228                 && (!cursor.par()->isLetter(cursor.pos())
2229                     || cursor.par()->getFont(bview->buffer()->params, cursor.pos())
2230                     .latex() == LyXFont::ON))
2231                || (cursor.par()->size() == cursor.pos()
2232                    && cursor.par()->next())){
2233                 if (cursor.pos() == cursor.par()->size()) {
2234                         cursor.par(cursor.par()->next());
2235                         cursor.pos(0);
2236                 } else
2237                         cursor.pos(cursor.pos() + 1);
2238         }
2239   
2240         // Update the value if we changed paragraphs
2241         if (cursor.par() != tmppar){
2242                 setCursor(bview, cursor.par(), cursor.pos());
2243                 value = float(cursor.y())/float(height);
2244         }
2245
2246         // Start the selection from here
2247 #if 0
2248         sel_cursor = cursor;
2249 #else
2250         selection.cursor = cursor;
2251 #endif
2252         
2253         std::ostringstream latex;
2254
2255         // and find the end of the word 
2256         // (optional hyphens are part of a word)
2257         while (cursor.pos() < cursor.par()->size()
2258                && (cursor.par()->isLetter(cursor.pos())) 
2259                    || (cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET
2260                        && cursor.par()->getInset(cursor.pos()) != 0
2261                        && cursor.par()->getInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
2262                        && latex.str() == "\\-"
2263                            ))
2264                 cursor.pos(cursor.pos() + 1);
2265
2266         // Finally, we copy the word to a string and return it
2267         string str;
2268 #if 0
2269         if (sel_cursor.pos() < cursor.pos()) {
2270                 Paragraph::size_type i;
2271                 for (i = sel_cursor.pos(); i < cursor.pos(); ++i) {
2272                         if (cursor.par()->getChar(i) != Paragraph::META_INSET)
2273                                 str += cursor.par()->getChar(i);
2274                 }
2275         }
2276 #else
2277         if (selection.cursor.pos() < cursor.pos()) {
2278                 Paragraph::size_type i;
2279                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2280                         if (cursor.par()->getChar(i) != Paragraph::META_INSET)
2281                                 str += cursor.par()->getChar(i);
2282                 }
2283         }
2284 #endif
2285         return str;
2286 }
2287
2288
2289 // This one is also only for the spellchecker
2290 void LyXText::selectSelectedWord(BufferView * bview)
2291 {
2292 #if 0
2293         // move cursor to the beginning
2294         setCursor(bview, sel_cursor.par(), sel_cursor.pos());
2295         
2296         // set the sel cursor
2297         sel_cursor = cursor;
2298 #else
2299         // move cursor to the beginning
2300         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2301         
2302         // set the sel cursor
2303         selection.cursor = cursor;
2304 #endif
2305         std::ostringstream latex;
2306         
2307         // now find the end of the word
2308         while (cursor.pos() < cursor.par()->size()
2309                && (cursor.par()->isLetter(cursor.pos())
2310                    || (cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET
2311                        && cursor.par()->getInset(cursor.pos()) != 0
2312                        && cursor.par()->getInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
2313                        && latex.str() == "\\-"
2314                            )))
2315                 cursor.pos(cursor.pos() + 1);
2316         
2317         setCursor(bview, cursor.par(), cursor.pos());
2318         
2319         // finally set the selection
2320         setSelection(bview);
2321 }
2322
2323
2324 /* -------> Delete from cursor up to the end of the current or next word. */
2325 void LyXText::deleteWordForward(BufferView * bview)
2326 {
2327         if (!cursor.par()->size())
2328                 cursorRight(bview);
2329         else {
2330                 LyXCursor tmpcursor = cursor;
2331                 tmpcursor.row(0); // ??
2332 #if 0
2333                 selection = true; // to avoid deletion
2334 #else
2335                 selection.set(true); // to avoid deletion
2336 #endif
2337                 cursorRightOneWord(bview);
2338                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2339 #if 0
2340                 sel_cursor = cursor;
2341 #else
2342                 selection.cursor = cursor;
2343 #endif
2344                 cursor = tmpcursor;
2345                 setSelection(bview); 
2346                 
2347                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2348                 cutSelection(bview);
2349         }
2350 }
2351
2352
2353 /* -------> Delete from cursor to start of current or prior word. */
2354 void LyXText::deleteWordBackward(BufferView * bview)
2355 {
2356        if (!cursor.par()->size())
2357                cursorLeft(bview);
2358        else {
2359                LyXCursor tmpcursor = cursor;
2360                tmpcursor.row(0); // ??
2361 #if 0
2362                selection = true; // to avoid deletion
2363 #else
2364                selection.set(true); // to avoid deletion
2365 #endif
2366                cursorLeftOneWord(bview);
2367                setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2368 #if 0
2369                sel_cursor = cursor;
2370 #else
2371                selection.cursor = cursor;
2372 #endif
2373                cursor = tmpcursor;
2374                setSelection(bview);
2375                cutSelection(bview);
2376        }
2377 }
2378
2379
2380 /* -------> Kill to end of line. */
2381 void LyXText::deleteLineForward(BufferView * bview)
2382 {
2383         if (!cursor.par()->size())
2384                 // Paragraph is empty, so we just go to the right
2385                 cursorRight(bview);
2386         else {
2387                 LyXCursor tmpcursor = cursor;
2388                 // We can't store the row over a regular setCursor
2389                 // so we set it to 0 and reset it afterwards.
2390                 tmpcursor.row(0); // ??
2391 #if 0
2392                 selection = true; // to avoid deletion
2393 #else
2394                 selection.set(true); // to avoid deletion
2395 #endif
2396                 cursorEnd(bview);
2397                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2398 #if 0
2399                 sel_cursor = cursor;
2400 #else
2401                 selection.cursor = cursor;
2402 #endif
2403                 cursor = tmpcursor;
2404                 setSelection(bview);
2405                 // What is this test for ??? (JMarc)
2406 #if 0
2407                 if (!selection) {
2408 #else
2409                         if (!selection.set()) {
2410 #endif
2411                         deleteWordForward(bview);
2412                 } else {
2413                         cutSelection(bview);
2414                 }
2415         }
2416 }
2417
2418
2419 // Change the case of a word at cursor position. 
2420 // This function directly manipulates Paragraph::text because there
2421 // is no Paragraph::SetChar currently. I did what I could to ensure
2422 // that it is correct. I guess part of it should be moved to
2423 // Paragraph, but it will have to change for 1.1 anyway. At least
2424 // it does not access outside of the allocated array as the older
2425 // version did. (JMarc) 
2426 void LyXText::changeWordCase(BufferView * bview, LyXText::TextCase action) 
2427 {
2428         Paragraph * tmppar = cursor.par();
2429
2430         setUndo(bview->buffer(),Undo::FINISH,
2431                 tmppar->previous(), tmppar->next()); 
2432
2433         Paragraph::size_type tmppos = cursor.pos();
2434
2435         while (tmppos < tmppar->size()) {
2436                 unsigned char c = tmppar->getChar(tmppos);
2437                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
2438                         break;
2439                 if (c != Paragraph::META_INSET) {
2440                         switch (action) {
2441                         case text_lowercase:
2442                                 c = tolower(c);
2443                                 break;
2444                         case text_capitalization:
2445                                 c = toupper(c);
2446                                 action = text_lowercase;
2447                                 break;
2448                         case text_uppercase:
2449                                 c = toupper(c);
2450                                 break;
2451                         }
2452                 }
2453                 
2454                 //tmppar->text[tmppos] = c;
2455                 tmppar->setChar(tmppos, c);
2456                 ++tmppos;
2457         }
2458         checkParagraph(bview, tmppar, tmppos);
2459         cursorRightOneWord(bview);
2460 }
2461
2462
2463 void LyXText::transposeChars(BufferView const & bview)
2464 {
2465         Paragraph * tmppar = cursor.par();
2466
2467         setUndo(bview.buffer(), Undo::FINISH,
2468                 tmppar->previous(), tmppar->next()); 
2469
2470         Paragraph::size_type tmppos = cursor.pos();
2471
2472         // First decide if it is possible to transpose at all
2473
2474         // We are at the beginning of a paragraph.
2475         if (tmppos == 0) return;
2476
2477         // We are at the end of a paragraph.
2478         if (tmppos == tmppar->size() - 1) return;
2479
2480         unsigned char c1 = tmppar->getChar(tmppos);
2481         unsigned char c2 = tmppar->getChar(tmppos - 1);
2482
2483         if (c1 != Paragraph::META_INSET
2484             && c2 != Paragraph::META_INSET) {
2485                 tmppar->setChar(tmppos, c2);
2486                 tmppar->setChar(tmppos - 1, c1);
2487         }
2488         // We should have an implementation that handles insets
2489         // as well, but that will have to come later. (Lgb)
2490         checkParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2491 }
2492
2493
2494 void LyXText::Delete(BufferView * bview)
2495 {
2496         // this is a very easy implementation
2497
2498         LyXCursor old_cursor = cursor;
2499         int const old_cur_par_id = old_cursor.par()->id();
2500         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2501                 old_cursor.par()->previous()->id() : 0;
2502         
2503         // just move to the right
2504         cursorRight(bview);
2505
2506         // CHECK Look at the comment here.
2507         // This check is not very good...
2508         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2509         // and that can very well delete the par or par->previous in
2510         // old_cursor. Will a solution where we compare paragraph id's
2511         //work better?
2512         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2513             == old_cur_par_prev_id
2514             && cursor.par()->id() != old_cur_par_id)
2515                 return; // delete-empty-paragraph-mechanism has done it
2516
2517         // if you had success make a backspace
2518         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2519                 LyXCursor tmpcursor = cursor;
2520                 cursor = old_cursor; // to make sure undo gets the right cursor position
2521                 setUndo(bview->buffer(), Undo::DELETE,
2522                         cursor.par()->previous(), 
2523                         cursor.par()->next()); 
2524                 cursor = tmpcursor;
2525                 backspace(bview);
2526         }
2527 }
2528
2529
2530 void LyXText::backspace(BufferView * bview)
2531 {
2532         // Get the font that is used to calculate the baselineskip
2533         Paragraph::size_type lastpos = cursor.par()->size();
2534         LyXFont rawparfont =
2535                 cursor.par()->getFontSettings(bview->buffer()->params,
2536                                               lastpos - 1);
2537
2538         if (cursor.pos() == 0) {
2539                 // The cursor is at the beginning of a paragraph,
2540                 // so the the backspace will collapse two paragraphs into one.
2541                 
2542                 // we may paste some paragraphs
2543       
2544                 // is it an empty paragraph?
2545       
2546                 if ((lastpos == 0
2547                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2548                         // This is an empty paragraph and we delete it just by moving the cursor one step
2549                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2550                         // of the paragraph.
2551                         
2552                         if (cursor.par()->previous()) {
2553                                 Paragraph * tmppar = cursor.par()->previous();
2554                                 if (cursor.par()->getLayout() == tmppar->getLayout()
2555                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2556                                         // Inherit bottom DTD from the paragraph below.
2557                                         // (the one we are deleting)
2558                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2559                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2560                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2561                                 }
2562                                 
2563                                 cursorLeft(bview);
2564                      
2565                                 // the layout things can change the height of a row !
2566                                 int const tmpheight = cursor.row()->height();
2567                                 setHeightOfRow(bview, cursor.row());
2568                                 if (cursor.row()->height() != tmpheight) {
2569                                         refresh_y = cursor.y() - cursor.row()->baseline();
2570                                         refresh_row = cursor.row();
2571                                         status = LyXText::NEED_MORE_REFRESH;
2572                                 }
2573                                 return;
2574                         }
2575                 }
2576
2577                 if (cursor.par()->previous()) {
2578                         setUndo(bview->buffer(), Undo::DELETE,
2579                                 cursor.par()->previous()->previous(),
2580                                 cursor.par()->next());
2581                 }
2582                 
2583                 Paragraph * tmppar = cursor.par();
2584                 Row * tmprow = cursor.row();
2585
2586                 // We used to do cursorLeftIntern() here, but it is
2587                 // not a good idea since it triggers the auto-delete
2588                 // mechanism. So we do a cursorLeftIntern()-lite,
2589                 // without the dreaded mechanism. (JMarc)
2590                 if (cursor.par()->previous()) { 
2591                         // steps into the above paragraph.
2592                         setCursorIntern(bview, cursor.par()->previous(),
2593                                         cursor.par()->previous()->size(),
2594                                         false);
2595                 }
2596
2597                 /* Pasting is not allowed, if the paragraphs have different
2598                    layout. I think it is a real bug of all other
2599                    word processors to allow it. It confuses the user.
2600                    Even so with a footnote paragraph and a non-footnote
2601                    paragraph. I will not allow pasting in this case, 
2602                    because the user would be confused if the footnote behaves 
2603                    different wether it is open or closed.
2604                   
2605                    Correction: Pasting is always allowed with standard-layout
2606                 */
2607                 if (cursor.par() != tmppar
2608                     && (cursor.par()->getLayout() == tmppar->getLayout()
2609                         || tmppar->getLayout() == 0 /*standard*/)
2610                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2611
2612                         removeParagraph(tmprow);
2613                         removeRow(tmprow);
2614                         cursor.par()->pasteParagraph(bview->buffer()->params);
2615                         
2616                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2617                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2618                         // strangely enough it seems that commenting out the line above removes
2619                         // most or all of the segfaults. I will however also try to move the
2620                         // two Remove... lines in front of the PasteParagraph too.
2621                         else
2622                                 if (cursor.pos())
2623                                         cursor.pos(cursor.pos() - 1);
2624                         
2625                         status = LyXText::NEED_MORE_REFRESH;
2626                         refresh_row = cursor.row();
2627                         refresh_y = cursor.y() - cursor.row()->baseline();
2628                         
2629                         // remove the lost paragraph
2630                         // This one is not safe, since the paragraph that the tmprow and the
2631                         // following rows belong to has been deleted by the PasteParagraph
2632                         // above. The question is... could this be moved in front of the
2633                         // PasteParagraph?
2634                         //RemoveParagraph(tmprow);
2635                         //RemoveRow(tmprow);  
2636                         
2637                         // This rebuilds the rows.
2638                         appendParagraph(bview, cursor.row());
2639                         updateCounters(bview, cursor.row());
2640                         
2641                         // the row may have changed, block, hfills etc.
2642                         setCursor(bview, cursor.par(), cursor.pos(), false);
2643                 }
2644         } else {
2645                 /* this is the code for a normal backspace, not pasting
2646                  * any paragraphs */ 
2647                 setUndo(bview->buffer(), Undo::DELETE,
2648                         cursor.par()->previous(),
2649                         cursor.par()->next()); 
2650                 // We used to do cursorLeftIntern() here, but it is
2651                 // not a good idea since it triggers the auto-delete
2652                 // mechanism. So we do a cursorLeftIntern()-lite,
2653                 // without the dreaded mechanism. (JMarc)
2654                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2655                                 false, cursor.boundary());
2656                 
2657                 // some insets are undeletable here
2658                 if (cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET) {
2659                         if (!cursor.par()->getInset(cursor.pos())->Deletable())
2660                                 return; 
2661                         // force complete redo when erasing display insets
2662                         // this is a cruel method but safe..... Matthias 
2663                         if (cursor.par()->getInset(cursor.pos())->display() ||
2664                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2665                                 cursor.par()->erase(cursor.pos());
2666                                 redoParagraph(bview);
2667                                 return;
2668                         }
2669                 }
2670                 
2671                 Row * row = cursor.row();
2672                 int y = cursor.y() - row->baseline();
2673                 Paragraph::size_type z;
2674                 /* remember that a space at the end of a row doesnt count
2675                  * when calculating the fill */ 
2676                 if (cursor.pos() < rowLast(row) ||
2677                     !cursor.par()->isLineSeparator(cursor.pos())) {
2678                         row->fill(row->fill() + singleWidth(bview,
2679                                                             cursor.par(),
2680                                                             cursor.pos()));
2681                 }
2682                 
2683                 /* some special code when deleting a newline. This is similar
2684                  * to the behavior when pasting paragraphs */ 
2685                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2686                         cursor.par()->erase(cursor.pos());
2687                         // refresh the positions
2688                         Row * tmprow = row;
2689                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2690                                 tmprow = tmprow->next();
2691                                 tmprow->pos(tmprow->pos() - 1);
2692                         }
2693                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2694                                 cursor.pos(cursor.pos() - 1);
2695
2696                         if (cursor.pos() < cursor.par()->size()
2697                             && !cursor.par()->isSeparator(cursor.pos())) {
2698                                 cursor.par()->insertChar(cursor.pos(), ' ');
2699                                 setCharFont(bview->buffer(), cursor.par(), 
2700                                             cursor.pos(), current_font);
2701                                 // refresh the positions
2702                                 tmprow = row;
2703                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2704                                         tmprow = tmprow->next();
2705                                         tmprow->pos(tmprow->pos() + 1);
2706                                 }
2707                         }
2708                 } else {
2709                         cursor.par()->erase(cursor.pos());
2710                         
2711                         // refresh the positions
2712                         Row * tmprow = row;
2713                         while (tmprow->next()
2714                                && tmprow->next()->par() == row->par()) {
2715                                 tmprow = tmprow->next();
2716                                 tmprow->pos(tmprow->pos() - 1);
2717                         }
2718
2719                         // delete newlines at the beginning of paragraphs
2720                         while (cursor.par()->size() &&
2721                                cursor.par()->isNewline(cursor.pos()) &&
2722                                cursor.pos() == beginningOfMainBody(bview->buffer(),
2723                                                                    cursor.par())) {
2724                                 cursor.par()->erase(cursor.pos());
2725                                 // refresh the positions
2726                                 tmprow = row;
2727                                 while (tmprow->next() && 
2728                                        tmprow->next()->par() == row->par()) {
2729                                         tmprow = tmprow->next();
2730                                         tmprow->pos(tmprow->pos() - 1);
2731                                 }
2732                         }
2733                 }
2734                 
2735                 // is there a break one row above
2736                 if (row->previous() && row->previous()->par() == row->par()) {
2737                         z = nextBreakPoint(bview, row->previous(),
2738                                            workWidth(bview));
2739                         if (z >= row->pos()) {
2740                                 row->pos(z + 1);
2741                                 
2742                                 Row * tmprow = row->previous();
2743                                 
2744                                 // maybe the current row is now empty
2745                                 if (row->pos() >= row->par()->size()) {
2746                                         // remove it
2747                                         removeRow(row);
2748                                         need_break_row = 0;
2749                                 } else {
2750                                         breakAgainOneRow(bview, row);
2751                                         if (row->next() && row->next()->par() == row->par())
2752                                                 need_break_row = row->next();
2753                                         else
2754                                                 need_break_row = 0;
2755                                 }
2756                                 
2757                                 // set the dimensions of the row above
2758                                 y -= tmprow->height();
2759                                 tmprow->fill(fill(bview, tmprow,
2760                                                   workWidth(bview)));
2761                                 setHeightOfRow(bview, tmprow);
2762                                 
2763                                 refresh_y = y;
2764                                 refresh_row = tmprow;
2765                                 status = LyXText::NEED_MORE_REFRESH;
2766                                 setCursor(bview, cursor.par(), cursor.pos(),
2767                                           false, cursor.boundary());
2768                                 //current_font = rawtmpfont;
2769                                 //real_current_font = realtmpfont;
2770                                 // check, whether the last character's font has changed.
2771                                 if (rawparfont !=
2772                                     cursor.par()->getFontSettings(bview->buffer()->params,
2773                                                                   cursor.par()->size() - 1))
2774                                         redoHeightOfParagraph(bview, cursor);
2775                                 return;
2776                         }
2777                 }
2778                 
2779                 // break the cursor row again
2780                 if (row->next() && row->next()->par() == row->par() &&
2781                     (rowLast(row) == row->par()->size() - 1 ||
2782                      nextBreakPoint(bview, row, workWidth(bview)) != rowLast(row))) {
2783                         
2784                         /* it can happen that a paragraph loses one row
2785                          * without a real breakup. This is when a word
2786                          * is to long to be broken. Well, I don t care this 
2787                          * hack ;-) */
2788                         if (rowLast(row) == row->par()->size() - 1)
2789                                 removeRow(row->next());
2790                         
2791                         refresh_y = y;
2792                         refresh_row = row;
2793                         status = LyXText::NEED_MORE_REFRESH;
2794                         
2795                         breakAgainOneRow(bview, row);
2796                         // will the cursor be in another row now?
2797                         if (row->next() && row->next()->par() == row->par() &&
2798                             rowLast(row) <= cursor.pos()) {
2799                                 row = row->next();
2800                                 breakAgainOneRow(bview, row);
2801                         }
2802
2803                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2804
2805                         if (row->next() && row->next()->par() == row->par())
2806                                 need_break_row = row->next();
2807                         else
2808                                 need_break_row = 0;
2809                 } else  {
2810                         // set the dimensions of the row
2811                         row->fill(fill(bview, row, workWidth(bview)));
2812                         int const tmpheight = row->height();
2813                         setHeightOfRow(bview, row);
2814                         if (tmpheight == row->height())
2815                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
2816                         else
2817                                 status = LyXText::NEED_MORE_REFRESH;
2818                         refresh_y = y;
2819                         refresh_row = row;
2820                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2821                 }
2822         }
2823
2824         // current_font = rawtmpfont;
2825         // real_current_font = realtmpfont;
2826
2827         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2828             != cursor.boundary())
2829                 setCursor(bview, cursor.par(), cursor.pos(), false,
2830                           !cursor.boundary());
2831
2832         lastpos = cursor.par()->size();
2833         if (cursor.pos() == lastpos)
2834                 setCurrentFont(bview);
2835         
2836         // check, whether the last characters font has changed.
2837         if (rawparfont != 
2838             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2839                 redoHeightOfParagraph(bview, cursor);
2840         } else {
2841                 // now the special right address boxes
2842                 if (textclasslist.Style(bview->buffer()->params.textclass,
2843                                         cursor.par()->getLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
2844                         redoDrawingOfParagraph(bview, cursor); 
2845                 }
2846         }
2847 }
2848
2849
2850 void LyXText::getVisibleRow(BufferView * bview, int y_offset, int x_offset,
2851                             Row * row_ptr, int y, bool cleared)
2852 {
2853         // returns a printed row
2854         Painter & pain = bview->painter();
2855         
2856         bool const is_rtl =
2857                 row_ptr->par()->isRightToLeftPar(bview->buffer()->params);
2858         
2859         Paragraph::size_type const last = rowLastPrintable(row_ptr);
2860
2861         Paragraph::size_type vpos;
2862         Paragraph::size_type pos;
2863
2864         float tmpx;
2865
2866         LyXFont font(LyXFont::ALL_SANE);
2867         int maxdesc;
2868         if (row_ptr->height() <= 0) {
2869                 lyxerr << "LYX_ERROR: row.height: "
2870                        << row_ptr->height() << endl;
2871                 return;
2872         }
2873
2874         float x;
2875         float fill_separator;
2876         float fill_hfill;
2877         float fill_label_hfill;
2878         prepareToPrint(bview, row_ptr, x, fill_separator,
2879                        fill_hfill, fill_label_hfill);
2880         
2881         if (inset_owner && (x < 0))
2882                 x = 0;
2883         x += x_offset;
2884         
2885         // clear the area where we want to paint/print
2886         int const ww = bview->workWidth();
2887
2888         bool clear_area = true;
2889         Inset * inset = 0;
2890
2891         if (!bview->screen()->forceClear() && last == row_ptr->pos()
2892             && row_ptr->par()->getChar(row_ptr->pos()) == Paragraph::META_INSET
2893             && (inset = row_ptr->par()->getInset(row_ptr->pos()))) {
2894                 clear_area = inset->doClearArea();
2895         }
2896         // we don't need to clear it's already done!!!
2897         if (cleared) {
2898                 clear_area = true;
2899         } else if (clear_area) {
2900 #ifdef WITH_WARNINGS
2901 #warning Should be fixed with a lyxinset::clear_width(bv, font) function! (Jug)
2902 #warning Should we not fix this in the Painter, please have a look Lars! (Jug)
2903 #endif
2904                 int const y = y_offset < 0 ? 0 : y_offset;
2905                 int const h = y_offset < 0 ?
2906                         row_ptr->height() + y_offset : row_ptr->height();
2907                 int const w = inset_owner ?
2908                         inset_owner->width(bview, font) - 2 : ww;
2909                 int const x = x_offset;
2910                 pain.fillRectangle(x, y, w, h);
2911         } else if (inset != 0) {
2912                 int h = row_ptr->baseline() - inset->ascent(bview, font);
2913                 if (h > 0) {
2914                         int const w = (inset_owner ?
2915                                  inset_owner->width(bview, font) : ww);
2916                         pain.fillRectangle(x_offset, y_offset, w, h);
2917                 }
2918                 h += inset->ascent(bview, font) + inset->descent(bview, font);
2919                 if ((row_ptr->height() - h) > 0) {
2920                         int const w = (inset_owner ?
2921                                  inset_owner->width(bview, font) : ww);
2922                         pain.fillRectangle(x_offset, y_offset + h,
2923                                            w, row_ptr->height() - h);
2924                 }
2925                 if (!inset_owner && !inset->display() && !inset->needFullRow())
2926                 {
2927                         int const w = inset->width(bview, font) + int(x);
2928                         pain.fillRectangle(w, y_offset, ww - w, row_ptr->height());
2929                 }
2930         }
2931
2932         if (selection.set()) {
2933                 int const w = (inset_owner ?
2934                                inset_owner->width(bview, font) : ww);
2935                 // selection code
2936                 if (bidi_same_direction) {
2937                         if (selection.start.row() == row_ptr &&
2938                             selection.end.row() == row_ptr) {
2939                                 if (selection.start.x() < selection.end.x())
2940                                         pain.fillRectangle(x_offset + selection.start.x(),
2941                                                            y_offset,
2942                                                            selection.end.x() - selection.start.x(),
2943                                                            row_ptr->height(),
2944                                                            LColor::selection);
2945                                 else
2946                                         pain.fillRectangle(x_offset + selection.end.x(),
2947                                                            y_offset,
2948                                                            selection.start.x() - selection.end.x(),
2949                                                            row_ptr->height(),
2950                                                            LColor::selection);
2951                         } else if (selection.start.row() == row_ptr) {
2952                                 if (is_rtl)
2953                                         pain.fillRectangle(x_offset, y_offset,
2954                                                            selection.start.x(),
2955                                                            row_ptr->height(),
2956                                                            LColor::selection);
2957                                 else
2958                                         pain.fillRectangle(x_offset + selection.start.x(),
2959                                                            y_offset,
2960                                                            w - selection.start.x(),
2961                                                            row_ptr->height(),
2962                                                            LColor::selection);
2963                         } else if (selection.end.row() == row_ptr) {
2964                                 if (is_rtl)
2965                                         pain.fillRectangle(x_offset + selection.end.x(),
2966                                                            y_offset,
2967                                                            w - selection.end.x(),
2968                                                            row_ptr->height(),
2969                                                            LColor::selection);
2970                                 else
2971                                         pain.fillRectangle(x_offset, y_offset,
2972                                                            selection.end.x(),
2973                                                            row_ptr->height(),
2974                                                            LColor::selection);
2975                         } else if (y > selection.start.y()
2976                                    && y < selection.end.y()) {
2977                                 pain.fillRectangle(x_offset, y_offset, w,
2978                                                    row_ptr->height(),
2979                                                    LColor::selection);
2980                         }
2981                 } else if (selection.start.row() != row_ptr &&
2982                             selection.end.row() != row_ptr &&
2983                             y > selection.start.y()
2984                             && y < selection.end.y()) {
2985                         pain.fillRectangle(x_offset, y_offset, w,
2986                                            row_ptr->height(),
2987                                            LColor::selection);
2988                 } else if (selection.start.row() == row_ptr ||
2989                            selection.end.row() == row_ptr) {
2990                         float tmpx = x;
2991                         if ((selection.start.row() != row_ptr && !is_rtl) ||
2992                              (selection.end.row() != row_ptr && is_rtl))
2993                                 pain.fillRectangle(x_offset, y_offset,
2994                                                    int(tmpx),
2995                                                    row_ptr->height(),
2996                                                    LColor::selection);
2997                         Paragraph::size_type main_body =
2998                                 beginningOfMainBody(bview->buffer(),
2999                                                     row_ptr->par());
3000                         
3001                         for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3002                                 pos = vis2log(vpos);
3003                                 float const old_tmpx = tmpx;
3004                                 if (main_body > 0 && pos == main_body-1) {
3005                                         tmpx += fill_label_hfill +
3006                                                 lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
3007                                                                                    row_ptr->par()->getLayout()).labelsep,
3008                                                                getFont(bview->buffer(),row_ptr->par(), -2));
3009                                         if (row_ptr->par()->isLineSeparator(main_body-1))
3010                                                 tmpx -= singleWidth(bview, row_ptr->par(), main_body-1);
3011                                 }
3012                                 if (hfillExpansion(bview->buffer(), row_ptr, pos)) {
3013                                         tmpx += singleWidth(bview, row_ptr->par(), pos);
3014                                         if (pos >= main_body)
3015                                                 tmpx += fill_hfill;
3016                                         else 
3017                                                 tmpx += fill_label_hfill;
3018                                 }
3019                                 else if (row_ptr->par()->isSeparator(pos)) {
3020                                         tmpx += singleWidth(bview, row_ptr->par(), pos);
3021                                         if (pos >= main_body)
3022                                                 tmpx += fill_separator;
3023                                 } else
3024                                         tmpx += singleWidth(bview, row_ptr->par(), pos);
3025                                 
3026                                 if ((selection.start.row() != row_ptr ||
3027                                       selection.start.pos() <= pos) &&
3028                                      (selection.end.row() != row_ptr ||
3029                                       pos < selection.end.pos()) )
3030                                         // Here we do not use x_offset as x_offset was
3031                                         // added to x.
3032                                         pain.fillRectangle(int(old_tmpx),
3033                                                            y_offset,
3034                                                            int(tmpx - old_tmpx + 1),
3035                                                            row_ptr->height(),
3036                                                            LColor::selection);
3037                         }
3038
3039                         if ((selection.start.row() != row_ptr && is_rtl) ||
3040                              (selection.end.row() != row_ptr && !is_rtl) )
3041                                 pain.fillRectangle(x_offset + int(tmpx),
3042                                                    y_offset,
3043                                                    int(ww - tmpx),
3044                                                    row_ptr->height(),
3045                                                    LColor::selection);
3046                 }
3047         }
3048
3049         int box_x = 0;
3050
3051         // Draw appendix lines
3052         Paragraph * firstpar = row_ptr->par();
3053
3054         if (firstpar->params().appendix()) {
3055                 pain.line(1, y_offset,
3056                           1, y_offset + row_ptr->height(),
3057                           LColor::appendixline);
3058                 pain.line(ww - 2, y_offset,
3059                           ww - 2, y_offset + row_ptr->height(),
3060                           LColor::appendixline);
3061         }
3062
3063         // Draw depth lines
3064         Paragraph::depth_type const depth = firstpar->getDepth();
3065         if (depth > 0) {
3066                 Paragraph::depth_type next_depth = 0;
3067                 Paragraph::depth_type prev_depth = 0;
3068                 if (row_ptr->next())
3069                                 next_depth = row_ptr->next()->par()->getDepth();
3070                 if (row_ptr->previous())
3071                                 prev_depth = row_ptr->previous()->par()->getDepth();
3072
3073                 for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3074                         int const line_x = (LYX_PAPER_MARGIN / 5) *
3075                                 i + box_x + x_offset;
3076                         pain.line(line_x, y_offset, line_x,
3077                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
3078                                   LColor::depthbar);
3079                 
3080                         if (i > prev_depth)
3081                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
3082                                                    LColor::depthbar);
3083                         if (i > next_depth)
3084                                 pain.fillRectangle(line_x,
3085                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
3086                                                    LYX_PAPER_MARGIN / 5, 2,
3087                                                    LColor::depthbar);
3088                 }
3089         }
3090
3091         
3092         LyXLayout const & layout =
3093                 textclasslist.Style(bview->buffer()->params.textclass,
3094                                     row_ptr->par()->getLayout());
3095
3096         int y_top = 0;
3097         int y_bottom = row_ptr->height();
3098         
3099         // is it a first row?
3100         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
3101                 
3102                 // start of appendix?
3103                 if (row_ptr->par()->params().startOfAppendix()) {
3104                         pain.line(1, y_offset,
3105                                   ww - 2, y_offset,
3106                                   LColor::appendixline);
3107                 }
3108                 
3109                 // think about the margins
3110                 if (!row_ptr->previous() && bv_owner)
3111                         y_top += LYX_PAPER_MARGIN;
3112                 
3113                 // draw a top pagebreak
3114                 if (row_ptr->par()->params().pagebreakTop()) {
3115                         LyXFont pb_font;
3116                         pb_font.setColor(LColor::pagebreak).decSize();
3117                         int w = 0;
3118                         int a = 0;
3119                         int d = 0;
3120                         pain.line(0, y_offset + y_top + 2*defaultHeight(),
3121                                   ww, 
3122                                   y_offset + y_top + 2 * defaultHeight(),
3123                                   LColor::pagebreak, 
3124                                   Painter::line_onoffdash)
3125                                 .rectText(0,
3126                                           0,
3127                                           _("Page Break (top)"),
3128                                           pb_font,
3129                                           LColor::background,
3130                                           LColor::background, false, w, a, d);
3131                         pain.rectText((ww - w)/2,
3132                                       y_offset + y_top + 2 * defaultHeight() + d,
3133                                       _("Page Break (top)"),
3134                                       pb_font,
3135                                       LColor::background,
3136                                       LColor::background);
3137                         y_top += 3 * defaultHeight();
3138                 }
3139                 
3140                 if (row_ptr->par()->params().spaceTop().kind() == VSpace::VFILL) {
3141                         // draw a vfill top
3142                         pain.line(0, y_offset + 2 + y_top,
3143                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
3144                                   LColor::vfillline);
3145                         
3146                         pain.line(0, y_offset + y_top + 3 * defaultHeight(),
3147                                   LYX_PAPER_MARGIN,
3148                                   y_offset + y_top + 3 * defaultHeight(),
3149                                   LColor::vfillline);
3150                         
3151                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
3152                                   LYX_PAPER_MARGIN / 2,
3153                                   y_offset + y_top + 3 * defaultHeight(),
3154                                   LColor::vfillline);
3155                         
3156                         y_top += 3 * defaultHeight();
3157                 }
3158                 
3159                 // think about user added space
3160                 y_top += int(row_ptr->par()->params().spaceTop().inPixels(bview));
3161                 
3162                 // think about the parskip
3163                 // some parskips VERY EASY IMPLEMENTATION
3164                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3165                         if (layout.latextype == LATEX_PARAGRAPH
3166                             && firstpar->getDepth() == 0
3167                             && firstpar->previous())
3168                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
3169                         else if (firstpar->previous()
3170                                  && textclasslist.Style(bview->buffer()->params.textclass,
3171                                                         firstpar->previous()->getLayout()).latextype == LATEX_PARAGRAPH
3172                                  && firstpar->previous()->getDepth() == 0)
3173                                 // is it right to use defskip here, too? (AS) 
3174                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
3175                 }
3176                 
3177                 if (row_ptr->par()->params().lineTop()) {
3178                         // draw a top line
3179                         y_top +=  lyxfont::ascent('x',
3180                                                   getFont(bview->buffer(),
3181                                                           row_ptr->par(), 0));
3182                         int const w = (inset_owner ?
3183                                        inset_owner->width(bview, font) : ww);
3184                         int const xp = static_cast<int>(inset_owner ? x : 0);
3185                         pain.line(xp, y_offset + y_top,
3186                                   w, y_offset + y_top,
3187                                   LColor::topline,
3188                                   Painter::line_solid,
3189                                   Painter::line_thick);
3190                         
3191                         y_top +=  lyxfont::ascent('x',getFont(bview->buffer(),
3192                                                               row_ptr->par(), 0));
3193                 }
3194                 
3195                 // should we print a label?
3196                 if (layout.labeltype >= LABEL_STATIC
3197                     && (layout.labeltype != LABEL_STATIC
3198                         || layout.latextype != LATEX_ENVIRONMENT
3199                         || row_ptr->par()->isFirstInSequence())) {
3200                         font = getFont(bview->buffer(), row_ptr->par(), -2);
3201                         if (!row_ptr->par()->getLabelstring().empty()) {
3202                                 tmpx = x;
3203                                 string const tmpstring =
3204                                         row_ptr->par()->getLabelstring();
3205                                 
3206                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3207                                         if (bview->buffer()->params.secnumdepth >= 0) {
3208                                                 // this is special code for
3209                                                 // the chapter layout. This is
3210                                                 // printed in an extra row
3211                                                 // and has a pagebreak at
3212                                                 // the top.
3213                                                 float spacing_val = 1.0;
3214                                                 if (!row_ptr->par()->params().spacing().isDefault()) {
3215                                                         spacing_val = row_ptr->par()->params().spacing().getValue();
3216                                                 } else {
3217                                                         spacing_val = bview->buffer()->params.spacing.getValue();
3218                                                 }
3219    
3220                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3221                                                         + int(layout.parsep) * defaultHeight();
3222                                                 if (is_rtl)
3223                                                         tmpx = ww - leftMargin(bview, row_ptr) - 
3224                                                                 lyxfont::width(tmpstring, font);
3225                                                 pain.text(int(tmpx),
3226                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
3227                                                           tmpstring, font);
3228                                         }
3229                                 } else {
3230                                         if (is_rtl) {
3231                                                 tmpx = ww - leftMargin(bview, row_ptr)
3232                                                         + lyxfont::width(layout.labelsep, font);
3233                                         } else
3234                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3235                                                         - lyxfont::width(tmpstring, font);
3236
3237                                         // draw it!
3238                                         pain.text(int(tmpx),
3239                                                   y_offset + row_ptr->baseline(),
3240                                                   tmpstring, font);
3241                                 }
3242                         }
3243                         // the labels at the top of an environment.
3244                         // More or less for bibliography
3245                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3246                            layout.labeltype == LABEL_BIBLIO ||
3247                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3248                         if (row_ptr->par()->isFirstInSequence()) {
3249                                 font = getFont(bview->buffer(),
3250                                                row_ptr->par(), -2);
3251                                 if (!row_ptr->par()->getLabelstring().empty()) {
3252                                         string const tmpstring =
3253                                                 row_ptr->par()->getLabelstring();
3254                                         float spacing_val = 1.0;
3255                                         if (!row_ptr->par()->params().spacing().isDefault()) {
3256                                                 spacing_val = row_ptr->par()->params().spacing().getValue();
3257                                         } else {
3258                                                 spacing_val = bview->buffer()->params.spacing.getValue();
3259                                         }
3260    
3261                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3262                                                       + (layout.labelbottomsep * defaultHeight()));
3263                                         
3264                                         tmpx = x;
3265                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
3266                                                 tmpx = ( (is_rtl ? leftMargin(bview, row_ptr) : x)
3267                                                          + ww - rightMargin(bview->buffer(), row_ptr) ) / 2; 
3268                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
3269                                         } else if (is_rtl)
3270                                                 tmpx = ww - leftMargin(bview, row_ptr) - 
3271                                                         lyxfont::width(tmpstring, font);
3272                                         pain.text(int(tmpx),
3273                                                   y_offset + row_ptr->baseline()
3274                                                   - row_ptr->ascent_of_text()
3275                                                   - maxdesc,
3276                                                   tmpstring, font);
3277                                 }
3278                         }
3279                 }
3280                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
3281                         font = getFont(bview->buffer(), row_ptr->par(), -1);
3282                         if (is_rtl)
3283                                 tmpx = ww - leftMargin(bview, row_ptr)
3284                                         + lyxfont::width(layout.labelsep, font);
3285                         else
3286                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3287                                         - row_ptr->par()->bibkey->width(bview, font);
3288                         row_ptr->par()->bibkey->draw(bview, font,
3289                                                    y_offset + row_ptr->baseline(), 
3290                                                    tmpx, clear_area);
3291                 }
3292         }
3293         
3294         // is it a last row?
3295         Paragraph * par = row_ptr->par();
3296         if (row_ptr->par() == par
3297             && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par())) {
3298                 // think about the margins
3299                 if (!row_ptr->next() && bv_owner)
3300                         y_bottom -= LYX_PAPER_MARGIN;
3301                 
3302                 // draw a bottom pagebreak
3303                 if (firstpar->params().pagebreakBottom()) {
3304                         LyXFont pb_font;
3305                         pb_font.setColor(LColor::pagebreak).decSize();
3306                         int const y_place = y_offset + y_bottom
3307                                 - 2 * defaultHeight();
3308                         
3309                         int w = 0;
3310                         int a = 0;
3311                         int d = 0;
3312                         pain
3313                                 .line(0, y_place, ww, y_place,
3314                                       LColor::pagebreak,
3315                                       Painter::line_onoffdash)
3316                                 .rectText(0, 0,
3317                                           _("Page Break (bottom)"),
3318                                           pb_font,
3319                                           LColor::background,
3320                                           LColor::background, false, w, a, d);
3321                         pain.rectText((ww - w) / 2, y_place + d,
3322                                       _("Page Break (bottom)"),
3323                                       pb_font,
3324                                       LColor::background,
3325                                       LColor::background);
3326                         y_bottom -= 3 * defaultHeight();
3327                 }
3328                 
3329                 if (firstpar->params().spaceBottom().kind() == VSpace::VFILL) {
3330                         // draw a vfill bottom
3331                         int const y_place = y_offset + y_bottom
3332                                 - 3 * defaultHeight();
3333                         
3334                         pain.line(0, y_place,
3335                                   LYX_PAPER_MARGIN, y_place,
3336                                   LColor::vfillline);
3337                         pain.line(0, y_offset + y_bottom - 2,
3338                                   LYX_PAPER_MARGIN,
3339                                   y_offset + y_bottom - 2,
3340                                   LColor::vfillline);
3341                         pain.line(LYX_PAPER_MARGIN / 2,
3342                                   y_place,
3343                                   LYX_PAPER_MARGIN / 2,
3344                                   y_offset + y_bottom - 2,
3345                                   LColor::vfillline);
3346                         y_bottom -= 3 * defaultHeight();
3347                 }
3348                 
3349                 // think about user added space
3350                 y_bottom -= int(firstpar->params().spaceBottom().inPixels(bview));
3351                 
3352                 if (firstpar->params().lineBottom()) {
3353                         // draw a bottom line
3354                         y_bottom -= lyxfont::ascent('x',
3355                                                     getFont(bview->buffer(),
3356                                                             par,
3357                                                             par->size() - 1));
3358                         int const w = (inset_owner ?
3359                                        inset_owner->width(bview, font) : ww);
3360                         int const xp = static_cast<int>(inset_owner ? x : 0);
3361                         pain.line(xp, y_offset + y_bottom,
3362                                   w, y_offset + y_bottom,
3363                                   LColor::topline, Painter::line_solid,
3364                                   Painter::line_thick);
3365                         y_bottom -= lyxfont::ascent('x',
3366                                                     getFont(bview->buffer(),
3367                                                             par,
3368                                                             par->size() - 1));
3369                 }
3370
3371                 // draw an endlabel
3372                 int const endlabel =
3373                         row_ptr->par()->getEndLabel(bview->buffer()->params);
3374                 switch (endlabel) {
3375                 case END_LABEL_BOX:
3376                 case END_LABEL_FILLED_BOX:
3377                 {
3378                         LyXFont const font = getFont(bview->buffer(),
3379                                                      row_ptr->par(), last);
3380                         int const size = int(0.75 * lyxfont::maxAscent(font));
3381                         int const y = (y_offset + row_ptr->baseline()) - size;
3382                         int x = is_rtl ? LYX_PAPER_MARGIN 
3383                                 : ww - LYX_PAPER_MARGIN - size;
3384
3385                         if (row_ptr->fill() <= size)
3386                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
3387                         if (endlabel == END_LABEL_BOX) {
3388                                 pain.line(x, y, x, y + size,
3389                                           LColor::eolmarker);
3390                                 pain.line(x + size, y, x + size , y + size,
3391                                           LColor::eolmarker);
3392                                 pain.line(x, y, x + size, y,
3393                                           LColor::eolmarker);
3394                                 pain.line(x, y + size, x + size, y + size,
3395                                           LColor::eolmarker);
3396                         } else
3397                                 pain.fillRectangle(x, y, size, size,
3398                                                    LColor::eolmarker);
3399                         break;
3400                 }
3401                 case END_LABEL_STATIC:
3402                 {
3403                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->getLayout();
3404                         string const tmpstring = textclasslist.
3405                                 Style(bview->buffer()->params.textclass,
3406                                       layout).endlabelstring();
3407                         font = getFont(bview->buffer(), row_ptr->par(), -2);
3408                         int const tmpx = is_rtl ?
3409                                 int(x) - lyxfont::width(tmpstring, font)
3410                                 : ww - rightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
3411                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
3412                         break;
3413                 }
3414                 case END_LABEL_NO_LABEL:
3415                         break;
3416                 }
3417         }
3418         
3419         // draw the text in the pixmap
3420         
3421         vpos = row_ptr->pos();
3422
3423         Paragraph::size_type main_body = 
3424                 beginningOfMainBody(bview->buffer(), row_ptr->par());
3425         if (main_body > 0 &&
3426             (main_body-1 > last || 
3427              !row_ptr->par()->isLineSeparator(main_body - 1)))
3428                 main_body = 0;
3429         
3430         while (vpos <= last)  {
3431                 pos = vis2log(vpos);
3432                 if (main_body > 0 && pos == main_body - 1) {
3433                         x += fill_label_hfill
3434                                 + lyxfont::width(layout.labelsep,
3435                                                  getFont(bview->buffer(),
3436                                                          row_ptr->par(), -2))
3437                                 - singleWidth(bview,
3438                                               row_ptr->par(),
3439                                               main_body - 1);
3440                 }
3441                 
3442                 if (row_ptr->par() ->isHfill(pos)) {
3443                         x += 1;
3444                         pain.line(int(x),
3445                                   y_offset + row_ptr->baseline() - defaultHeight() / 2,
3446                                   int(x),
3447                                   y_offset + row_ptr->baseline(),
3448                                   LColor::vfillline);
3449                         
3450                         if (hfillExpansion(bview->buffer(),
3451                                            row_ptr, pos)) {
3452                                 if (pos >= main_body) {
3453                                         pain.line(int(x),
3454                                                   y_offset + row_ptr->baseline() - defaultHeight() / 4,
3455                                                   int(x + fill_hfill),
3456                                                   y_offset + row_ptr->baseline() - defaultHeight() / 4,
3457                                                   LColor::vfillline,
3458                                                   Painter::line_onoffdash);
3459                                         x += fill_hfill;
3460                                 } else {
3461                                         pain.line(int(x),
3462                                                   y_offset + row_ptr->baseline() - defaultHeight() / 4,
3463                                                   int(x + fill_label_hfill),
3464                                                   y_offset + row_ptr->baseline() - defaultHeight() / 4,
3465                                                   LColor::vfillline,
3466                                                   Painter::line_onoffdash);
3467                                         
3468                                         x += fill_label_hfill;
3469                                 }
3470                                 pain.line(int(x),
3471                                           y_offset + row_ptr->baseline() - defaultHeight() / 2,
3472                                           int(x),
3473                                           y_offset + row_ptr->baseline(),
3474                                           LColor::vfillline);
3475                         }
3476                         x += 2;
3477                         ++vpos;
3478                 } else if (row_ptr->par()->isSeparator(pos)) {
3479                         x += singleWidth(bview,
3480                                          row_ptr->par(), pos);
3481                         if (pos >= main_body)
3482                                 x += fill_separator;
3483                         ++vpos;
3484                 } else
3485                         draw(bview, row_ptr, vpos, y_offset, x, clear_area);
3486         }
3487 }
3488
3489
3490 int LyXText::defaultHeight() const
3491 {
3492         LyXFont font(LyXFont::ALL_SANE);
3493         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3494 }
3495
3496    
3497 /* returns the column near the specified x-coordinate of the row 
3498 * x is set to the real beginning of this column  */ 
3499 int LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3500                             bool & boundary) const
3501 {
3502         float tmpx = 0.0;
3503         float fill_separator;
3504         float fill_hfill;
3505         float fill_label_hfill;
3506    
3507         prepareToPrint(bview, row, tmpx, fill_separator,
3508                        fill_hfill, fill_label_hfill);
3509
3510         Paragraph::size_type vc = row->pos();
3511         Paragraph::size_type last = rowLastPrintable(row);
3512         Paragraph::size_type c = 0;
3513         LyXLayout const & layout =
3514                 textclasslist.Style(bview->buffer()->params.textclass,
3515                                     row->par()->getLayout());
3516         bool left_side = false;
3517
3518         Paragraph::size_type
3519                 main_body = beginningOfMainBody(bview->buffer(), row->par());
3520         float last_tmpx = tmpx;
3521         
3522         if (main_body > 0 &&
3523             (main_body-1 > last || 
3524              !row->par()->isLineSeparator(main_body - 1)))
3525                 main_body = 0;
3526         
3527         while (vc <= last && tmpx <= x) {
3528                 c = vis2log(vc);
3529                 last_tmpx = tmpx;
3530                 if (main_body > 0 && c == main_body-1) {
3531                         tmpx += fill_label_hfill +
3532                                 lyxfont::width(layout.labelsep,
3533                                                getFont(bview->buffer(), row->par(), -2));
3534                         if (row->par()->isLineSeparator(main_body - 1))
3535                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3536                 }
3537                 
3538                 if (hfillExpansion(bview->buffer(), row, c)) {
3539                         x += singleWidth(bview, row->par(), c);
3540                         if (c >= main_body)
3541                                 tmpx += fill_hfill;
3542                         else
3543                                 tmpx += fill_label_hfill;
3544                 }
3545                 else if (row->par()->isSeparator(c)) {
3546                         tmpx += singleWidth(bview, row->par(), c);
3547                         if (c >= main_body)
3548                                 tmpx+= fill_separator;
3549                 } else
3550                         tmpx += singleWidth(bview, row->par(), c);
3551                 ++vc;
3552         }
3553         
3554         if (1 || (tmpx + last_tmpx) / 2 > x) {
3555                 tmpx = last_tmpx;
3556                 left_side = true;
3557         }
3558
3559         if (vc > last + 1)  // This shouldn't happen.
3560                 vc = last + 1;
3561
3562         boundary = false;
3563         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3564                                          // some speedup if rtl_support=false
3565                 && (!row->next() || row->next()->par() != row->par());
3566         bool const rtl = (lastrow)
3567                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3568                 : false; // If lastrow is false, we don't need to compute
3569                          // the value of rtl.
3570
3571         if (row->pos() > last)  // Row is empty?
3572                 c = row->pos();
3573         else if (lastrow &&
3574                  ( ( rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3575                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5) ))
3576                 c = last + 1;
3577         else if (vc == row->pos()) {
3578                 c = vis2log(vc);
3579                 if (bidi_level(c) % 2 == 1)
3580                         ++c;
3581         } else {
3582                 c = vis2log(vc - 1);
3583                 bool const rtl = (bidi_level(c) % 2 == 1);
3584                 if (left_side == rtl) {
3585                         ++c;
3586                         boundary = isBoundary(bview->buffer(), row->par(), c);
3587                 }
3588         }
3589
3590         if (row->pos() <= last && c > last
3591             && row->par()->isNewline(last)) {
3592                 if (bidi_level(last) % 2 == 0)
3593                         tmpx -= singleWidth(bview, row->par(), last);
3594                 else
3595                         tmpx += singleWidth(bview, row->par(), last);
3596                 c = last;
3597         }
3598
3599         c -= row->pos();
3600         x = int(tmpx);
3601         return c;
3602 }
3603
3604
3605 // returns pointer to a specified row
3606 Row * LyXText::getRow(Paragraph * par,
3607                       Paragraph::size_type pos, int & y) const
3608 {
3609         if (!firstrow)
3610                 return 0;
3611         
3612         Row * tmprow = firstrow;
3613         y = 0;
3614         
3615         // find the first row of the specified paragraph
3616         while (tmprow->next() && tmprow->par() != par) {
3617                 y += tmprow->height();
3618                 tmprow = tmprow->next();
3619         }
3620         
3621         // now find the wanted row
3622         while (tmprow->pos() < pos
3623                && tmprow->next()
3624                && tmprow->next()->par() == par
3625                && tmprow->next()->pos() <= pos) {
3626                 y += tmprow->height();
3627                 tmprow = tmprow->next();
3628         }
3629         
3630         return tmprow;
3631 }