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