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