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