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