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