]> git.lyx.org Git - lyx.git/blob - src/text.C
0a965a0d32052bbc49945177706df79d4f9469bb
[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         /* ok , let us initialize the maxasc and maxdesc value. 
1216          * This depends in LaTeX of the font of the last character
1217          * in the paragraph. The hack below is necessary because
1218          * of the possibility of open footnotes */
1219         
1220         /* Correction: only the fontsize count. The other properties
1221            are taken from the layoutfont. Nicer on the screen :) */
1222         Paragraph * par = row_ptr->par();
1223         Paragraph * firstpar = row_ptr->par();
1224    
1225         LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
1226                                                        firstpar->getLayout());
1227
1228         // as max get the first character of this row then it can increes but not
1229         // decrees the height. Just some point to start with so we don't have to
1230         // do the assignment below too often.
1231         LyXFont font = getFont(bview->buffer(), par, row_ptr->pos());
1232         LyXFont::FONT_SIZE const tmpsize = font.size();
1233         font = getLayoutFont(bview->buffer(), par);
1234         LyXFont::FONT_SIZE const size = font.size();
1235         font.setSize(tmpsize);
1236
1237         LyXFont labelfont = getLabelFont(bview->buffer(), par);
1238
1239         float spacing_val = 1.0;
1240         if (!row_ptr->par()->params().spacing().isDefault()) {
1241                 spacing_val = row_ptr->par()->params().spacing().getValue();
1242         } else {
1243                 spacing_val = bview->buffer()->params.spacing.getValue();
1244         }
1245         //lyxerr << "spacing_val = " << spacing_val << endl;
1246    
1247         int maxasc = int(lyxfont::maxAscent(font) *
1248                          layout.spacing.getValue() *
1249                          spacing_val);
1250         int maxdesc = int(lyxfont::maxDescent(font) *
1251                           layout.spacing.getValue() *
1252                           spacing_val);
1253         Paragraph::size_type const pos_end = rowLast(row_ptr);
1254         int labeladdon = 0;
1255         int maxwidth = 0;
1256
1257         // Check if any insets are larger
1258         for (Paragraph::size_type pos = row_ptr->pos(); pos <= pos_end; ++pos) {
1259                 if (row_ptr->par()->getChar(pos) == Paragraph::META_INSET) {
1260                         tmpfont = getFont(bview->buffer(), row_ptr->par(), pos);
1261                         tmpinset = row_ptr->par()->getInset(pos);
1262                         if (tmpinset) {
1263 #if 1 // this is needed for deep update on initialitation
1264                                 tmpinset->update(bview, tmpfont);
1265 #endif
1266                                 asc = tmpinset->ascent(bview, tmpfont);
1267                                 desc = tmpinset->descent(bview, tmpfont);
1268                                 maxwidth += tmpinset->width(bview, tmpfont);
1269                                 maxasc = max(maxasc, asc);
1270                                 maxdesc = max(maxdesc, desc);
1271                         }
1272                 } else {
1273                         maxwidth += singleWidth(bview, row_ptr->par(), pos);
1274                 }
1275         }
1276
1277         // Check if any custom fonts are larger (Asger)
1278         // This is not completely correct, but we can live with the small,
1279         // cosmetic error for now.
1280         LyXFont::FONT_SIZE maxsize =
1281                 row_ptr->par()->highestFontInRange(row_ptr->pos(), pos_end, size);
1282         if (maxsize > font.size()) {
1283                 font.setSize(maxsize);
1284
1285                 asc = lyxfont::maxAscent(font);
1286                 desc = lyxfont::maxDescent(font);
1287                 if (asc > maxasc) 
1288                         maxasc = asc;
1289                 if (desc > maxdesc)
1290                         maxdesc = desc;
1291         }
1292
1293         // This is nicer with box insets:
1294         ++maxasc;
1295         ++maxdesc;
1296
1297         row_ptr->ascent_of_text(maxasc);
1298    
1299         // is it a top line?
1300         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
1301       
1302                 // some parksips VERY EASY IMPLEMENTATION
1303                 if (bview->buffer()->params.paragraph_separation ==
1304                         BufferParams::PARSEP_SKIP)
1305                 {
1306                         if (layout.isParagraph()
1307                                 && firstpar->getDepth() == 0
1308                                 && firstpar->previous())
1309                         {
1310                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1311                         } else if (firstpar->previous() &&
1312                                    textclasslist.Style(bview->buffer()->params.textclass,
1313                                                        firstpar->previous()->
1314                                                        getLayout()).isParagraph() &&
1315                                    firstpar->previous()->getDepth() == 0)
1316                         {
1317                                 // is it right to use defskip here too? (AS)
1318                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1319                         }
1320                 }
1321       
1322                 // the paper margins
1323                 if (!row_ptr->par()->previous() && bv_owner)
1324                         maxasc += LYX_PAPER_MARGIN;
1325       
1326                 // add the vertical spaces, that the user added
1327                 if (firstpar->params().spaceTop().kind() != VSpace::NONE)
1328                         maxasc += int(firstpar->params().spaceTop().inPixels(bview));
1329       
1330                 // do not forget the DTP-lines!
1331                 // there height depends on the font of the nearest character
1332                 if (firstpar->params().lineTop())
1333                         maxasc += 2 * lyxfont::ascent('x', getFont(bview->buffer(),
1334                                                                    firstpar, 0));
1335       
1336                 // and now the pagebreaks
1337                 if (firstpar->params().pagebreakTop())
1338                         maxasc += 3 * defaultHeight();
1339       
1340                 // This is special code for the chapter, since the label of this
1341                 // layout is printed in an extra row
1342                 if (layout.labeltype == LABEL_COUNTER_CHAPTER
1343                         && bview->buffer()->params.secnumdepth >= 0)
1344                 {
1345                         float spacing_val = 1.0;
1346                         if (!row_ptr->par()->params().spacing().isDefault()) {
1347                                 spacing_val = row_ptr->par()->params().spacing().getValue();
1348                         } else {
1349                                 spacing_val = bview->buffer()->params.spacing.getValue();
1350                         }
1351               
1352                         labeladdon = int(lyxfont::maxDescent(labelfont) *
1353                                          layout.spacing.getValue() *
1354                                          spacing_val)
1355                                 + int(lyxfont::maxAscent(labelfont) *
1356                                       layout.spacing.getValue() *
1357                                       spacing_val);
1358                 }
1359       
1360                 // special code for the top label
1361                 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1362                      || layout.labeltype == LABEL_BIBLIO
1363                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1364                     && row_ptr->par()->isFirstInSequence()
1365                     && !row_ptr->par()->getLabelstring().empty())
1366                 {
1367                         float spacing_val = 1.0;
1368                         if (!row_ptr->par()->params().spacing().isDefault()) {
1369                                 spacing_val = row_ptr->par()->params().spacing().getValue();
1370                         } else {
1371                                 spacing_val = bview->buffer()->params.spacing.getValue();
1372                         }
1373               
1374                         labeladdon = int(
1375                                 (lyxfont::maxAscent(labelfont) *
1376                                  layout.spacing.getValue() *
1377                                  spacing_val)
1378                                 +(lyxfont::maxDescent(labelfont) *
1379                                   layout.spacing.getValue() *
1380                                   spacing_val)
1381                                 + layout.topsep * defaultHeight()
1382                                 + layout.labelbottomsep *  defaultHeight());
1383                 }
1384    
1385                 // and now the layout spaces, for example before and after a section, 
1386                 // or between the items of a itemize or enumerate environment
1387       
1388                 if (!firstpar->params().pagebreakTop()) {
1389                         Paragraph * prev = row_ptr->par()->previous();
1390                         if (prev)
1391                                 prev = row_ptr->par()->depthHook(row_ptr->par()->getDepth());
1392                         if (prev && prev->getLayout() == firstpar->getLayout() &&
1393                                 prev->getDepth() == firstpar->getDepth() &&
1394                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1395                         {
1396                                 layoutasc = (layout.itemsep * defaultHeight());
1397                         } else if (row_ptr->previous()) {
1398                                 tmptop = layout.topsep;
1399             
1400                                 if (row_ptr->previous()->par()->getDepth() >= row_ptr->par()->getDepth())
1401                                         tmptop -= textclasslist.Style(bview->buffer()->params.textclass,
1402                                                                       row_ptr->previous()->par()->
1403                                                                       getLayout()).bottomsep;
1404             
1405                                 if (tmptop > 0)
1406                                         layoutasc = (tmptop * defaultHeight());
1407                         } else if (row_ptr->par()->params().lineTop()) {
1408                                 tmptop = layout.topsep;
1409             
1410                                 if (tmptop > 0)
1411                                         layoutasc = (tmptop * defaultHeight());
1412                         }
1413          
1414                         prev = row_ptr->par()->outerHook();
1415                         if (prev)  {
1416                                 maxasc += int(textclasslist.Style(bview->buffer()->params.textclass,
1417                                               prev->getLayout()).parsep * defaultHeight());
1418                         } else {
1419                                 if (firstpar->previous() &&
1420                                         firstpar->previous()->getDepth() == 0 &&
1421                                         firstpar->previous()->getLayout() !=
1422                                         firstpar->getLayout())
1423                                 {
1424                                         // avoid parsep
1425                                 } else if (firstpar->previous()) {
1426                                         maxasc += int(layout.parsep * defaultHeight());
1427                                 }
1428                         }
1429                 }
1430         }
1431    
1432         // is it a bottom line?
1433         if (row_ptr->par() == par
1434                 && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par()))
1435         {
1436                 // the paper margins
1437                 if (!par->next() && bv_owner)
1438                         maxdesc += LYX_PAPER_MARGIN;
1439           
1440                 // add the vertical spaces, that the user added
1441                 if (firstpar->params().spaceBottom().kind() != VSpace::NONE)
1442                         maxdesc += int(firstpar->params().spaceBottom().inPixels(bview));
1443           
1444                 // do not forget the DTP-lines!
1445                 // there height depends on the font of the nearest character
1446                 if (firstpar->params().lineBottom())
1447                         maxdesc += 2 * lyxfont::ascent('x',
1448                                                        getFont(bview->buffer(),
1449                                                                par,
1450                                                                max(Paragraph::size_type(0), par->size() - 1)));
1451           
1452                 // and now the pagebreaks
1453                 if (firstpar->params().pagebreakBottom())
1454                         maxdesc += 3 * defaultHeight();
1455           
1456                 // and now the layout spaces, for example before and after
1457                 // a section, or between the items of a itemize or enumerate
1458                 // environment
1459                 if (!firstpar->params().pagebreakBottom() && row_ptr->par()->next()) {
1460                         Paragraph * nextpar = row_ptr->par()->next();
1461                         Paragraph * comparepar = row_ptr->par();
1462                         float usual = 0;
1463                         float unusual = 0;
1464              
1465                         if (comparepar->getDepth() > nextpar->getDepth()) {
1466                                 usual = (textclasslist.Style(bview->buffer()->params.textclass,
1467                                          comparepar->getLayout()).bottomsep * defaultHeight());
1468                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1469                                 if (comparepar->getLayout()!= nextpar->getLayout()
1470                                         || nextpar->getLabelWidthString() != 
1471                                         comparepar->getLabelWidthString())
1472                                 {
1473                                         unusual = (textclasslist.Style(bview->buffer()->params.textclass,
1474                                                    comparepar->getLayout()).bottomsep * defaultHeight());
1475                                 }
1476                                 if (unusual > usual)
1477                                         layoutdesc = unusual;
1478                                 else
1479                                         layoutdesc = usual;
1480                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1481                                 
1482                                 if (comparepar->getLayout()!= nextpar->getLayout()
1483                                         || nextpar->getLabelWidthString() != 
1484                                         comparepar->getLabelWidthString())
1485                                         layoutdesc = int(textclasslist.Style(bview->buffer()->params.textclass,
1486                                                                                                                  comparepar->getLayout()).bottomsep * defaultHeight());
1487                         }
1488                 }
1489         }
1490         
1491         // incalculate the layout spaces
1492         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1493         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1494         
1495         // calculate the new height of the text
1496         height -= row_ptr->height();
1497         
1498         row_ptr->height(maxasc + maxdesc + labeladdon);
1499         row_ptr->baseline(maxasc + labeladdon);
1500         
1501         height += row_ptr->height();
1502         float x = 0;
1503         if (layout.margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1504                 float dummy;
1505                 prepareToPrint(bview, row_ptr, x, dummy, dummy, dummy, false);
1506         }
1507         row_ptr->width(int(maxwidth + x));
1508         if (inset_owner) {
1509                 Row * r = firstrow;
1510                 width = max(0,workWidth(bview));
1511                 while(r) {
1512                         if (r->width() > width)
1513                                 width = r->width();
1514                         r = r->next();
1515                 }
1516         }
1517 }
1518
1519
1520 /* Appends the implicit specified paragraph behind the specified row,
1521  * start at the implicit given position */
1522 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1523 {
1524    bool not_ready = true;
1525    
1526    // The last character position of a paragraph is an invariant so we can 
1527    // safely get it here. (Asger)
1528    Paragraph::size_type const lastposition = row->par()->size();
1529    do {
1530       // Get the next breakpoint
1531       Paragraph::size_type z = nextBreakPoint(bview, row, workWidth(bview));
1532       
1533       Row * tmprow = row;
1534
1535       // Insert the new row
1536       if (z < lastposition) {
1537          ++z;
1538          insertRow(row, row->par(), z);
1539          row = row->next();
1540
1541          row->height(0);
1542       } else
1543          not_ready = false;
1544       
1545       // Set the dimensions of the row
1546 #ifdef WITH_WARNINGS
1547 #warning Something is rotten here! (Jug)
1548 #endif
1549       tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1550       setHeightOfRow(bview, tmprow);
1551
1552    } while (not_ready);
1553 }
1554
1555
1556 void LyXText::breakAgain(BufferView * bview, Row * row) const
1557 {
1558         bool not_ready = true;
1559    
1560         do  {
1561                 // get the next breakpoint
1562                 Paragraph::size_type z = nextBreakPoint(bview, row, workWidth(bview));
1563                 Row * tmprow = row;
1564
1565                 if (z < row->par()->size()) {
1566                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1567                                 // insert a new row
1568                                 ++z;
1569                                 insertRow(row, row->par(), z);
1570                                 row = row->next();
1571                                 row->height(0);
1572                         } else  {
1573                                 row = row->next();
1574                                 ++z;
1575                                 if (row->pos() == z)
1576                                         not_ready = false;     // the rest will not change
1577                                 else {
1578                                         row->pos(z);
1579                                 }
1580                         }
1581                 } else {
1582                         /* if there are some rows too much, delete them */
1583                         /* only if you broke the whole paragraph! */ 
1584                         Row * tmprow2 = row;
1585                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1586                                 tmprow2 = tmprow2->next();
1587                         }
1588                         while (tmprow2 != row) {
1589                                 tmprow2 = tmprow2->previous();
1590                                 removeRow(tmprow2->next());
1591                         }
1592                         not_ready = false;
1593                 }
1594                 
1595                 /* set the dimensions of the row */ 
1596                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1597                 setHeightOfRow(bview, tmprow);
1598         } while (not_ready);
1599 }
1600
1601
1602 // this is just a little changed version of break again
1603 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1604 {
1605         // get the next breakpoint
1606         Paragraph::size_type z = nextBreakPoint(bview, row, workWidth(bview));
1607         Row * tmprow = row;
1608
1609         if (z < row->par()->size()) {
1610                 if (!row->next()
1611                     || (row->next() && row->next()->par() != row->par())) {
1612                         /* insert a new row */ 
1613                         ++z;
1614                         insertRow(row, row->par(), z);
1615                         row = row->next();
1616                         row->height(0);
1617                 } else  {
1618                         row= row->next();
1619                         ++z;
1620                         if (row->pos() != z)
1621                                 row->pos(z);
1622                 }
1623         } else {
1624                 // if there are some rows too much, delete them
1625                 // only if you broke the whole paragraph!
1626                 Row * tmprow2 = row;
1627                 while (tmprow2->next()
1628                        && tmprow2->next()->par() == row->par()) {
1629                         tmprow2 = tmprow2->next();
1630                 }
1631                 while (tmprow2 != row) {
1632                         tmprow2 = tmprow2->previous();
1633                         removeRow(tmprow2->next());
1634                 }
1635         }
1636         
1637         // set the dimensions of the row
1638         tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1639         setHeightOfRow(bview, tmprow);
1640 }
1641
1642
1643 void LyXText::breakParagraph(BufferView * bview, char keep_layout)
1644 {
1645    LyXLayout const & layout =
1646            textclasslist.Style(bview->buffer()->params.textclass,
1647                                cursor.par()->getLayout());
1648
1649    // this is only allowed, if the current paragraph is not empty or caption
1650    if ((cursor.par()->size() <= 0)
1651        && layout.labeltype!= LABEL_SENSITIVE)
1652            return;
1653    
1654    setUndo(bview, Undo::INSERT,cursor.par(),cursor.par()->next()); 
1655
1656    // Always break behind a space
1657    //
1658    // It is better to erase the space (Dekel)
1659    if (cursor.pos() < cursor.par()->size()
1660        && cursor.par()->isLineSeparator(cursor.pos()))
1661            cursor.par()->erase(cursor.pos());
1662            // cursor.pos(cursor.pos() + 1);
1663
1664    // break the paragraph
1665    if (keep_layout)
1666      keep_layout = 2;
1667    else 
1668      keep_layout = layout.isEnvironment();
1669    cursor.par()->breakParagraph(bview->buffer()->params, cursor.pos(),
1670                                 keep_layout);
1671
1672    // well this is the caption hack since one caption is really enough
1673    if (layout.labeltype == LABEL_SENSITIVE) {
1674      if (!cursor.pos())
1675              // set to standard-layout
1676              cursor.par()->setLayout(0);
1677      else
1678              // set to standard-layout
1679              cursor.par()->next()->setLayout(0);
1680    }
1681    
1682    /* if the cursor is at the beginning of a row without prior newline, 
1683     * move one row up! 
1684     * This touches only the screen-update. Otherwise we would may have
1685     * an empty row on the screen */
1686    if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1687        && cursor.row()->pos() == cursor.pos()) {
1688            cursorLeft(bview);
1689    } 
1690    
1691    status(bview, LyXText::NEED_MORE_REFRESH);
1692    refresh_row = cursor.row();
1693    refresh_y = cursor.y() - cursor.row()->baseline();
1694    
1695    // Do not forget the special right address boxes
1696    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1697       while (refresh_row->previous() &&
1698              refresh_row->previous()->par() == refresh_row->par()) {
1699               refresh_row = refresh_row->previous();
1700               refresh_y -= refresh_row->height();
1701       }
1702    }
1703    removeParagraph(cursor.row());
1704    
1705    // set the dimensions of the cursor row
1706    cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1707
1708    setHeightOfRow(bview, cursor.row());
1709
1710    while (cursor.par()->next()->size()
1711           && cursor.par()->next()->isNewline(0))
1712            cursor.par()->next()->erase(0);
1713    
1714    insertParagraph(bview, cursor.par()->next(), cursor.row());
1715
1716    updateCounters(bview, cursor.row()->previous());
1717    
1718    /* This check is necessary. Otherwise the new empty paragraph will
1719     * be deleted automatically. And it is more friendly for the user! */ 
1720    if (cursor.pos())
1721            setCursor(bview, cursor.par()->next(), 0);
1722    else
1723            setCursor(bview, cursor.par(), 0);
1724    
1725    if (cursor.row()->next())
1726            breakAgain(bview, cursor.row()->next());
1727
1728    need_break_row = 0;
1729 }
1730
1731
1732 // Just a macro to make some thing easier. 
1733 void LyXText::redoParagraph(BufferView * bview) const
1734 {
1735         clearSelection();
1736         redoParagraphs(bview, cursor, cursor.par()->next());
1737         setCursorIntern(bview, cursor.par(), cursor.pos());
1738 }
1739
1740
1741 /* insert a character, moves all the following breaks in the 
1742  * same Paragraph one to the right and make a rebreak */
1743 void LyXText::insertChar(BufferView * bview, char c)
1744 {
1745         setUndo(bview, Undo::INSERT,
1746                 cursor.par(), cursor.par()->next());
1747
1748         // When the free-spacing option is set for the current layout,
1749         // disable the double-space checking
1750
1751         bool const freeSpacing = 
1752                 textclasslist.Style(bview->buffer()->params.textclass,
1753                                cursor.row()->par()->getLayout()).free_spacing;
1754
1755
1756         if (lyxrc.auto_number) {
1757                 static string const number_operators = "+-/*";
1758                 static string const number_unary_operators = "+-";
1759                 static string const number_seperators = ".,:";
1760
1761                 if (current_font.number() == LyXFont::ON) {
1762                         if (!isdigit(c) && !contains(number_operators, c) &&
1763                             !(contains(number_seperators, c) &&
1764                               cursor.pos() >= 1 &&
1765                               cursor.pos() < cursor.par()->size() &&
1766                               getFont(bview->buffer(),
1767                                       cursor.par(),
1768                                       cursor.pos()).number() == LyXFont::ON &&
1769                               getFont(bview->buffer(),
1770                                       cursor.par(),
1771                                       cursor.pos() - 1).number() == LyXFont::ON)
1772                             )
1773                                 number(bview); // Set current_font.number to OFF
1774                 } else if (isdigit(c) &&
1775                            real_current_font.isVisibleRightToLeft()) {
1776                         number(bview); // Set current_font.number to ON
1777
1778                         if (cursor.pos() > 0) {
1779                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1780                                 if (contains(number_unary_operators, c) &&
1781                                     (cursor.pos() == 1 ||
1782                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1783                                      cursor.par()->isNewline(cursor.pos() - 2) )
1784                                    ) {
1785                                         setCharFont(bview->buffer(),
1786                                                     cursor.par(),
1787                                                     cursor.pos() - 1,
1788                                                     current_font);
1789                                 } else if (contains(number_seperators, c) &&
1790                                            cursor.pos() >= 2 &&
1791                                            getFont(bview->buffer(),
1792                                                    cursor.par(),
1793                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1794                                         setCharFont(bview->buffer(),
1795                                                     cursor.par(),
1796                                                     cursor.pos() - 1,
1797                                                     current_font);
1798                                 }
1799                         }
1800                 }
1801         }
1802
1803
1804         /* First check, if there will be two blanks together or a blank at 
1805           the beginning of a paragraph. 
1806           I decided to handle blanks like normal characters, the main 
1807           difference are the special checks when calculating the row.fill
1808           (blank does not count at the end of a row) and the check here */ 
1809
1810         // The bug is triggered when we type in a description environment:
1811         // The current_font is not changed when we go from label to main text
1812         // and it should (along with realtmpfont) when we type the space.
1813         // CHECK There is a bug here! (Asger)
1814         
1815         LyXFont realtmpfont = real_current_font;
1816         LyXFont rawtmpfont = current_font;  /* store the current font.
1817                                      * This is because of the use
1818                                      * of cursor movements. The moving
1819                                      * cursor would refresh the 
1820                                      * current font */
1821
1822         // Get the font that is used to calculate the baselineskip
1823         Paragraph::size_type const lastpos = cursor.par()->size();
1824         LyXFont rawparfont =
1825                 cursor.par()->getFontSettings(bview->buffer()->params,
1826                                               lastpos - 1);
1827
1828         bool jumped_over_space = false;
1829    
1830         if (!freeSpacing && IsLineSeparatorChar(c)) {
1831                 if ((cursor.pos() > 0 
1832                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1833                     || (cursor.pos() > 0
1834                         && cursor.par()->isNewline(cursor.pos() - 1))
1835                     || (cursor.pos() == 0)) {
1836                         static bool sent_space_message = false;
1837                         if (!sent_space_message) {
1838                                 if (cursor.pos() == 0) 
1839                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1840                                 else
1841                                         bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1842                                 sent_space_message = true;
1843                         }
1844                         charInserted();
1845                         return;
1846                 }
1847         } else if (IsNewlineChar(c)) {
1848                 if (cursor.par() == cursor.par()
1849                     && cursor.pos() <= beginningOfMainBody(bview->buffer(), cursor.par())) {
1850                         charInserted();
1851                         return;
1852                 }
1853                 /* No newline at first position 
1854                  * of a paragraph or behind labels. 
1855                  * TeX does not allow that. */
1856
1857                 if (cursor.pos() < cursor.par()->size() &&
1858                     cursor.par()->isLineSeparator(cursor.pos()))
1859                         // newline always after a blank!
1860                         cursorRight(bview);
1861                 cursor.row()->fill(-1);        // to force a new break
1862         }
1863    
1864         // the display inset stuff
1865         if (cursor.row()->par()->getChar(cursor.row()->pos()) == Paragraph::META_INSET
1866             && cursor.row()->par()->getInset(cursor.row()->pos())
1867             && (cursor.row()->par()->getInset(cursor.row()->pos())->display() ||
1868                 cursor.row()->par()->getInset(cursor.row()->pos())->needFullRow()))
1869                 cursor.row()->fill(-1); // to force a new break  
1870
1871         // get the cursor row fist
1872         Row * row = cursor.row();
1873         int y = cursor.y() - row->baseline();
1874         if (c != Paragraph::META_INSET) /* Here case LyXText::InsertInset 
1875                                             * already insertet the character */
1876                 cursor.par()->insertChar(cursor.pos(), c);
1877         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1878
1879         if (!jumped_over_space) {
1880                 // refresh the positions
1881                 Row * tmprow = row;
1882                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1883                         tmprow = tmprow->next();
1884                         tmprow->pos(tmprow->pos() + 1);
1885                 }
1886         }
1887    
1888         // Is there a break one row above
1889         if ((cursor.par()->isLineSeparator(cursor.pos())
1890              || cursor.par()->isNewline(cursor.pos())
1891              || cursor.row()->fill() == -1)
1892             && row->previous() && row->previous()->par() == row->par()) {
1893                 Paragraph::size_type z = nextBreakPoint(bview,
1894                                                            row->previous(),
1895                                                            workWidth(bview));
1896                 if (z >= row->pos()) {
1897                         row->pos(z + 1);
1898                         
1899                         // set the dimensions of the row above
1900                         row->previous()->fill(fill(bview,
1901                                                    row->previous(),
1902                                                    workWidth(bview)));
1903
1904                         setHeightOfRow(bview, row->previous());
1905              
1906                         y -= row->previous()->height();
1907                         refresh_y = y;
1908                         refresh_row = row->previous();
1909                         status(bview, LyXText::NEED_MORE_REFRESH);
1910              
1911                         breakAgainOneRow(bview, row);
1912
1913                         current_font = rawtmpfont;
1914                         real_current_font = realtmpfont;
1915                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1916                                   false, cursor.boundary());
1917                         // cursor MUST be in row now.
1918              
1919                         if (row->next() && row->next()->par() == row->par())
1920                                 need_break_row = row->next();
1921                         else
1922                                 need_break_row = 0;
1923              
1924                         // check, wether the last characters font has changed.
1925                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1926                             && rawparfont != rawtmpfont)
1927                                 redoHeightOfParagraph(bview, cursor);
1928                         
1929                         charInserted();
1930                         return;
1931                 }
1932         }
1933    
1934         // recalculate the fill of the row
1935         if (row->fill() >= 0)  /* needed because a newline
1936                               * will set fill to -1. Otherwise
1937                               * we would not get a rebreak! */
1938                 row->fill(fill(bview, row, workWidth(bview)));
1939         if (row->fill() < 0) {
1940                 refresh_y = y;
1941                 refresh_row = row; 
1942                 refresh_x = cursor.x();
1943                 refresh_pos = cursor.pos();
1944                 status(bview, LyXText::NEED_MORE_REFRESH);
1945                 breakAgainOneRow(bview, row); 
1946                 // will the cursor be in another row now?
1947                 if (rowLast(row) <= cursor.pos() + 1 && row->next()) {
1948                         if (row->next() && row->next()->par() == row->par())
1949                                 // this should always be true
1950                                 row = row->next();
1951                         breakAgainOneRow(bview, row);
1952                 }
1953                 current_font = rawtmpfont;
1954                 real_current_font = realtmpfont;
1955
1956                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1957                           cursor.boundary());
1958                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1959                     != cursor.boundary())
1960                         setCursor(bview, cursor.par(), cursor.pos(), false,
1961                           !cursor.boundary());
1962                 if (row->next() && row->next()->par() == row->par())
1963                         need_break_row = row->next();
1964                 else
1965                         need_break_row = 0;             
1966         } else {
1967                 refresh_y = y;
1968                 refresh_x = cursor.x();
1969                 refresh_row = row;
1970                 refresh_pos = cursor.pos();
1971                 
1972                 int const tmpheight = row->height();
1973                 setHeightOfRow(bview, row);
1974                 if (tmpheight == row->height())
1975                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1976                 else
1977                         status(bview, LyXText::NEED_MORE_REFRESH);
1978             
1979                 current_font = rawtmpfont;
1980                 real_current_font = realtmpfont;
1981                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1982                           cursor.boundary());
1983         }
1984
1985         // check, wether the last characters font has changed.
1986         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1987             && rawparfont != rawtmpfont) {
1988                 redoHeightOfParagraph(bview, cursor);
1989         } else {
1990                 // now the special right address boxes
1991                 if (textclasslist.Style(bview->buffer()->params.textclass,
1992                                    cursor.par()->getLayout()).margintype
1993                     == MARGIN_RIGHT_ADDRESS_BOX) {
1994                         redoDrawingOfParagraph(bview, cursor); 
1995                 }
1996         }
1997
1998         charInserted();
1999 }
2000    
2001
2002 void LyXText::charInserted()
2003 {
2004         // Here we could call FinishUndo for every 20 characters inserted.
2005         // This is from my experience how emacs does it.
2006         static unsigned int counter;
2007         if (counter < 20) {
2008                 ++counter;
2009         } else {
2010                 finishUndo();
2011                 counter = 0;
2012         }
2013 }
2014
2015
2016 void LyXText::prepareToPrint(BufferView * bview,
2017                              Row * row, float & x,
2018                              float & fill_separator, 
2019                              float & fill_hfill,
2020                              float & fill_label_hfill,
2021                              bool bidi) const
2022 {
2023         float nlh;
2024         float ns;
2025         
2026         float w = row->fill();
2027         fill_hfill = 0;
2028         fill_label_hfill = 0;
2029         fill_separator = 0;
2030         fill_label_hfill = 0;
2031
2032         bool const is_rtl =
2033                 row->par()->isRightToLeftPar(bview->buffer()->params);
2034         if (is_rtl) {
2035                 x = (workWidth(bview) > 0)
2036                         ? rightMargin(bview->buffer(), row) : 0;
2037         } else
2038                 x = (workWidth(bview) > 0) ? leftMargin(bview, row) : 0;
2039         
2040         // is there a manual margin with a manual label
2041         if (textclasslist.Style(bview->buffer()->params.textclass,
2042                            row->par()->getLayout()).margintype == MARGIN_MANUAL
2043             && textclasslist.Style(bview->buffer()->params.textclass,
2044                               row->par()->getLayout()).labeltype == LABEL_MANUAL) {
2045                
2046                 /* one more since labels are left aligned */ 
2047                 nlh = numberOfLabelHfills(bview->buffer(), row) + 1;
2048                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2049                         fill_label_hfill = labelFill(bview, row) / nlh;
2050                 }
2051         }
2052                 
2053         // are there any hfills in the row?
2054         float const nh = numberOfHfills(bview->buffer(), row);
2055
2056         if (nh) {
2057                 if (w > 0)
2058                         fill_hfill = w / nh;
2059         } else  {
2060                 // is it block, flushleft or flushright? 
2061                 // set x how you need it
2062                 int align;
2063                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
2064                         align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->getLayout()).align;
2065                 } else {
2066                         align = row->par()->params().align();
2067                 }
2068                 
2069                 // center displayed insets 
2070                 Inset * inset;
2071                 if (row->par()->getChar(row->pos()) == Paragraph::META_INSET
2072                     && (inset=row->par()->getInset(row->pos()))
2073                     && (inset->display())) // || (inset->scroll() < 0)))
2074                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
2075                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2076                 
2077                 switch (align) {
2078             case LYX_ALIGN_BLOCK:
2079                         ns = numberOfSeparators(bview->buffer(), row);
2080                         if (ns && row->next() && row->next()->par() == row->par() &&
2081                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
2082                             && !(row->next()->par()->getChar(row->next()->pos()) == Paragraph::META_INSET
2083                                  && row->next()->par()->getInset(row->next()->pos())
2084                                  && row->next()->par()->getInset(row->next()->pos())->display())
2085                                 )
2086                         {
2087                                 fill_separator = w / ns;
2088                         } else if (is_rtl) {
2089                                 x += w;
2090                         }
2091                         break;
2092             case LYX_ALIGN_RIGHT:
2093                         x += w;
2094                         break;
2095             case LYX_ALIGN_CENTER:
2096                         x += w / 2;
2097                         break;
2098                 }
2099         }
2100         if (!bidi)
2101                 return;
2102
2103         computeBidiTables(bview->buffer(), row);
2104         if (is_rtl) {
2105                 Paragraph::size_type main_body = 
2106                         beginningOfMainBody(bview->buffer(), row->par());
2107                 Paragraph::size_type last = rowLast(row);
2108
2109                 if (main_body > 0 &&
2110                     (main_body-1 > last || 
2111                      !row->par()->isLineSeparator(main_body-1))) {
2112                         LyXLayout const & layout =
2113                                 textclasslist.Style(bview->buffer()->params.textclass,
2114                                                     row->par()->getLayout());
2115                         x += lyxfont::width(layout.labelsep,
2116                                             getLabelFont(bview->buffer(), row->par()));
2117                         if (main_body-1 <= last)
2118                                 x += fill_label_hfill;
2119                 }
2120         }
2121 }
2122       
2123 /* important for the screen */
2124
2125
2126 /* the cursor set functions have a special mechanism. When they
2127 * realize, that you left an empty paragraph, they will delete it.
2128 * They also delete the corresponding row */
2129
2130 void LyXText::cursorRightOneWord(BufferView * bview) const
2131 {
2132         // treat floats, HFills and Insets as words
2133         LyXCursor tmpcursor = cursor;
2134         // CHECK See comment on top of text.C
2135
2136         if (tmpcursor.pos() == tmpcursor.par()->size()
2137             && tmpcursor.par()->next()) {
2138                         tmpcursor.par(tmpcursor.par()->next());
2139                         tmpcursor.pos(0);
2140         } else {
2141                 int steps = 0;
2142
2143                 // Skip through initial nonword stuff.
2144                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2145                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2146                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2147                         tmpcursor.pos(tmpcursor.pos() + 1);
2148                         ++steps;
2149                 }
2150                 // Advance through word.
2151                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2152                         tmpcursor.par()->isWord( tmpcursor.pos())) {
2153                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2154                         tmpcursor.pos(tmpcursor.pos() + 1);
2155                         ++steps;
2156                 }
2157         }
2158         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2159 }
2160
2161
2162 void LyXText::cursorTab(BufferView * bview) const
2163 {
2164     LyXCursor tmpcursor = cursor;
2165     while (tmpcursor.pos() < tmpcursor.par()->size()
2166            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2167         tmpcursor.pos(tmpcursor.pos() + 1);
2168
2169     if (tmpcursor.pos() == tmpcursor.par()->size()){
2170         if (tmpcursor.par()->next()) {
2171             tmpcursor.par(tmpcursor.par()->next());
2172             tmpcursor.pos(0);
2173         }
2174     } else
2175         tmpcursor.pos(tmpcursor.pos() + 1);
2176     setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2177 }
2178
2179
2180 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2181             of prior word, not to end of next prior word. */
2182
2183 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2184 {
2185         LyXCursor tmpcursor = cursor;
2186         cursorLeftOneWord(tmpcursor);
2187         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2188 }
2189
2190 void LyXText::cursorLeftOneWord(LyXCursor  & cur)  const
2191 {
2192         // treat HFills, floats and Insets as words
2193         cur = cursor;
2194         while (cur.pos() 
2195                && (cur.par()->isSeparator(cur.pos() - 1) 
2196                    || cur.par()->isKomma(cur.pos() - 1))
2197                && !(cur.par()->isHfill(cur.pos() - 1)
2198                     || cur.par()->isInset(cur.pos() - 1)))
2199                 cur.pos(cur.pos() - 1);
2200
2201         if (cur.pos()
2202             && (cur.par()->isInset(cur.pos() - 1)
2203                 || cur.par()->isHfill(cur.pos() - 1))) {
2204                 cur.pos(cur.pos() - 1);
2205         } else if (!cur.pos()) {
2206                 if (cur.par()->previous()){
2207                         cur.par(cur.par()->previous());
2208                         cur.pos(cur.par()->size());
2209                 }
2210         } else {                // Here, cur != 0 
2211                 while (cur.pos() > 0 &&
2212                        cur.par()->isWord(cur.pos()-1) )
2213                         cur.pos(cur.pos() - 1);
2214         }
2215 }
2216
2217 /* -------> Select current word. This depends on behaviour of
2218 CursorLeftOneWord(), so it is patched as well. */
2219 void LyXText::getWord(LyXCursor & from, LyXCursor & to, 
2220                       word_location const loc) const
2221 {
2222         // first put the cursor where we wana start to select the word
2223         from = cursor;
2224         switch(loc) {
2225         case WHOLE_WORD_STRICT:
2226                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2227                     || cursor.par()->isSeparator(cursor.pos())
2228                     || cursor.par()->isKomma(cursor.pos())
2229                     || cursor.par()->isSeparator(cursor.pos() -1)
2230                     || cursor.par()->isKomma(cursor.pos() -1)) {
2231                         to = from;
2232                         return;
2233                 }
2234                 // no break here, we go to the next
2235                 
2236         case WHOLE_WORD:
2237                 // Move cursor to the beginning, when not already there.
2238                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2239                     && !from.par()->isKomma(from.pos() - 1))
2240                         cursorLeftOneWord(from);
2241                 break;
2242         case PREVIOUS_WORD:
2243                 // always move the cursor to the beginning of previous word
2244                 cursorLeftOneWord(from);
2245                 break;
2246         case NEXT_WORD:
2247                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2248                 break;
2249         case PARTIAL_WORD:
2250                 break;
2251         }
2252         to = from;
2253         while (to.pos() < to.par()->size()
2254                && !to.par()->isSeparator(to.pos())
2255                && !to.par()->isKomma(to.pos())
2256                && !to.par()->isHfill(to.pos()) )
2257         {
2258                 to.pos(to.pos() + 1);
2259         }
2260 }
2261
2262
2263 void LyXText::selectWord(BufferView * bview, word_location const loc) 
2264 {
2265         LyXCursor from;
2266         LyXCursor to;
2267         getWord(from, to, loc);
2268         if (cursor != from)
2269                 setCursor(bview, from.par(), from.pos());
2270         if (to == from)
2271                 return;
2272         selection.cursor = cursor;
2273         setCursor(bview, to.par(), to.pos() );
2274         setSelection(bview);
2275 }
2276
2277
2278 /* -------> Select the word currently under the cursor when no
2279         selection is currently set */
2280 bool LyXText::selectWordWhenUnderCursor(BufferView * bview, 
2281                                         word_location const loc) 
2282 {
2283         if (!selection.set()) {
2284                 selectWord(bview, loc);
2285                 return selection.set();
2286         }
2287         return false;
2288 }
2289
2290
2291 // This function is only used by the spellchecker for NextWord().
2292 // It doesn't handle LYX_ACCENTs and probably never will.
2293 string const LyXText::selectNextWordToSpellcheck(BufferView * bview,
2294                                                  float & value) const
2295 {
2296         if (the_locking_inset) {
2297                 string str = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2298                 if (!str.empty()) {
2299                         value += float(cursor.y())/float(height);
2300                         return str;
2301                 }
2302 #warning Dekel please have a look on this one RTL? (Jug)
2303 #warning DEKEL!
2304                 // we have to go on checking so move cusor to the right
2305                 if (cursor.pos() == cursor.par()->size()) {
2306                         if (!cursor.par()->next())
2307                                 return str;
2308                         cursor.par(cursor.par()->next());
2309                         cursor.pos(0);
2310                 } else
2311                         cursor.pos(cursor.pos() + 1);
2312         }
2313         Paragraph * tmppar = cursor.par();
2314         
2315         // If this is not the very first word, skip rest of
2316         // current word because we are probably in the middle
2317         // of a word if there is text here.
2318         if (cursor.pos() || cursor.par()->previous()) {
2319                 while (cursor.pos() < cursor.par()->size()
2320                        && cursor.par()->isLetter(cursor.pos()))
2321                         cursor.pos(cursor.pos() + 1);
2322         }
2323         
2324         // Now, skip until we have real text (will jump paragraphs)
2325         while ((cursor.par()->size() > cursor.pos()
2326                && (!cursor.par()->isLetter(cursor.pos()))
2327                && (!cursor.par()->isInset(cursor.pos()) ||
2328                            !cursor.par()->getInset(cursor.pos())->allowSpellcheck()))
2329                || (cursor.par()->size() == cursor.pos()
2330                    && cursor.par()->next()))
2331         {      
2332                 if (cursor.pos() == cursor.par()->size()) {
2333                         cursor.par(cursor.par()->next());
2334                         cursor.pos(0);
2335                 } else
2336                         cursor.pos(cursor.pos() + 1);
2337         }
2338
2339         // now check if we hit an inset so it has to be a inset containing text!
2340         if (cursor.pos() < cursor.par()->size() &&
2341             cursor.par()->isInset(cursor.pos()))
2342         {
2343                 // lock the inset!
2344                 cursor.par()->getInset(cursor.pos())->edit(bview);
2345                 // now call us again to do the above trick
2346                 // but obviously we have to start from down below ;)
2347                 return bview->text->selectNextWordToSpellcheck(bview, value);
2348         }               
2349   
2350         // Update the value if we changed paragraphs
2351         if (cursor.par() != tmppar){
2352                 setCursor(bview, cursor.par(), cursor.pos());
2353                 value = float(cursor.y())/float(height);
2354         }
2355
2356         // Start the selection from here
2357         selection.cursor = cursor;
2358         
2359         // and find the end of the word (insets like optional hyphens
2360         // and ligature break are part of a word)
2361         while (cursor.pos() < cursor.par()->size()
2362                && (cursor.par()->isLetter(cursor.pos()))) 
2363                 cursor.pos(cursor.pos() + 1);
2364
2365         // Finally, we copy the word to a string and return it
2366         string str;
2367         if (selection.cursor.pos() < cursor.pos()) {
2368                 Paragraph::size_type i;
2369                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2370                         if (!cursor.par()->isInset(i))
2371                                 str += cursor.par()->getChar(i);
2372                 }
2373         }
2374         return str;
2375 }
2376
2377
2378 // This one is also only for the spellchecker
2379 void LyXText::selectSelectedWord(BufferView * bview)
2380 {
2381         if (the_locking_inset) {
2382                 the_locking_inset->selectSelectedWord(bview);
2383                 return;
2384         }
2385         // move cursor to the beginning
2386         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2387         
2388         // set the sel cursor
2389         selection.cursor = cursor;
2390         
2391         // now find the end of the word
2392         while (cursor.pos() < cursor.par()->size()
2393                && (cursor.par()->isLetter(cursor.pos())))
2394                 cursor.pos(cursor.pos() + 1);
2395         
2396         setCursor(bview, cursor.par(), cursor.pos());
2397         
2398         // finally set the selection
2399         setSelection(bview);
2400 }
2401
2402
2403 /* -------> Delete from cursor up to the end of the current or next word. */
2404 void LyXText::deleteWordForward(BufferView * bview)
2405 {
2406         if (!cursor.par()->size())
2407                 cursorRight(bview);
2408         else {
2409                 LyXCursor tmpcursor = cursor;
2410                 tmpcursor.row(0); // ??
2411                 selection.set(true); // to avoid deletion
2412                 cursorRightOneWord(bview);
2413                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2414                 selection.cursor = cursor;
2415                 cursor = tmpcursor;
2416                 setSelection(bview);
2417                 
2418                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2419                 cutSelection(bview, true, false);
2420         }
2421 }
2422
2423
2424 /* -------> Delete from cursor to start of current or prior word. */
2425 void LyXText::deleteWordBackward(BufferView * bview)
2426 {
2427        if (!cursor.par()->size())
2428                cursorLeft(bview);
2429        else {
2430                LyXCursor tmpcursor = cursor;
2431                tmpcursor.row(0); // ??
2432                selection.set(true); // to avoid deletion
2433                cursorLeftOneWord(bview);
2434                setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2435                selection.cursor = cursor;
2436                cursor = tmpcursor;
2437                setSelection(bview);
2438                cutSelection(bview, true, false);
2439        }
2440 }
2441
2442
2443 /* -------> Kill to end of line. */
2444 void LyXText::deleteLineForward(BufferView * bview)
2445 {
2446         if (!cursor.par()->size())
2447                 // Paragraph is empty, so we just go to the right
2448                 cursorRight(bview);
2449         else {
2450                 LyXCursor tmpcursor = cursor;
2451                 // We can't store the row over a regular setCursor
2452                 // so we set it to 0 and reset it afterwards.
2453                 tmpcursor.row(0); // ??
2454                 selection.set(true); // to avoid deletion
2455                 cursorEnd(bview);
2456                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2457                 selection.cursor = cursor;
2458                 cursor = tmpcursor;
2459                 setSelection(bview);
2460                 // What is this test for ??? (JMarc)
2461                 if (!selection.set()) {
2462                         deleteWordForward(bview);
2463                 } else {
2464                         cutSelection(bview, true, false);
2465                 }
2466         }
2467 }
2468
2469
2470 // Change the case of a word at cursor position. 
2471 // This function directly manipulates Paragraph::text because there
2472 // is no Paragraph::SetChar currently. I did what I could to ensure
2473 // that it is correct. I guess part of it should be moved to
2474 // Paragraph, but it will have to change for 1.1 anyway. At least
2475 // it does not access outside of the allocated array as the older
2476 // version did. (JMarc) 
2477 void LyXText::changeCase(BufferView * bview, LyXText::TextCase action)
2478 {
2479         LyXCursor from;
2480         LyXCursor to;
2481
2482         if (selection.set()) {
2483                 from = selection.start;
2484                 to = selection.end;
2485         } else {
2486                 getWord(from, to, PARTIAL_WORD);
2487                 setCursor(bview, to.par(), to.pos() + 1);
2488         }
2489
2490         changeRegionCase(bview, from, to, action);
2491 }
2492
2493
2494 void LyXText::changeRegionCase(BufferView * bview,
2495                                LyXCursor const & from,
2496                                LyXCursor const & to,
2497                                LyXText::TextCase action)
2498 {
2499         lyx::Assert(from <= to);
2500         
2501         setUndo(bview, Undo::FINISH,
2502                 from.par(), to.par()->next());
2503
2504         Paragraph::size_type pos = from.pos();
2505         Paragraph * par = from.par();
2506
2507         while (par && (pos != to.pos() || par != to.par())) {
2508                 unsigned char c = par->getChar(pos);
2509                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2510                         switch (action) {
2511                         case text_lowercase:
2512                                 c = lowercase(c);
2513                                 break;
2514                         case text_capitalization:
2515                                 c = uppercase(c);
2516                                 action = text_lowercase;
2517                                 break;
2518                         case text_uppercase:
2519                                 c = uppercase(c);
2520                                 break;
2521                         }
2522                 }
2523                 par->setChar(pos, c);
2524                 checkParagraph(bview, par, pos);
2525
2526                 ++pos;
2527                 if (pos == par->size()) {
2528                         par = par->next();
2529                         pos = 0;
2530                 }
2531         }
2532         if (to.row() != from.row()) {
2533                 refresh_y = from.y() - from.row()->baseline();
2534                 refresh_row = from.row();
2535                 status(bview, LyXText::NEED_MORE_REFRESH);
2536         }
2537 }
2538
2539
2540 void LyXText::transposeChars(BufferView & bview)
2541 {
2542         Paragraph * tmppar = cursor.par();
2543
2544         setUndo(&bview, Undo::FINISH,
2545                 tmppar, tmppar->next()); 
2546
2547         Paragraph::size_type tmppos = cursor.pos();
2548
2549         // First decide if it is possible to transpose at all
2550
2551         // We are at the beginning of a paragraph.
2552         if (tmppos == 0) return;
2553
2554         // We are at the end of a paragraph.
2555         if (tmppos == tmppar->size() - 1) return;
2556
2557         unsigned char c1 = tmppar->getChar(tmppos);
2558         unsigned char c2 = tmppar->getChar(tmppos - 1);
2559
2560         if (c1 != Paragraph::META_INSET
2561             && c2 != Paragraph::META_INSET) {
2562                 tmppar->setChar(tmppos, c2);
2563                 tmppar->setChar(tmppos - 1, c1);
2564         }
2565         // We should have an implementation that handles insets
2566         // as well, but that will have to come later. (Lgb)
2567         checkParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2568 }
2569
2570
2571 void LyXText::Delete(BufferView * bview)
2572 {
2573         // this is a very easy implementation
2574
2575         LyXCursor old_cursor = cursor;
2576         int const old_cur_par_id = old_cursor.par()->id();
2577         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2578                 old_cursor.par()->previous()->id() : 0;
2579         
2580         // just move to the right
2581         cursorRight(bview);
2582
2583         // CHECK Look at the comment here.
2584         // This check is not very good...
2585         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2586         // and that can very well delete the par or par->previous in
2587         // old_cursor. Will a solution where we compare paragraph id's
2588         //work better?
2589         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2590             == old_cur_par_prev_id
2591             && cursor.par()->id() != old_cur_par_id) {
2592                 // delete-empty-paragraph-mechanism has done it
2593                 return;
2594         }
2595
2596         // if you had success make a backspace
2597         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2598                 LyXCursor tmpcursor = cursor;
2599                 // to make sure undo gets the right cursor position
2600                 cursor = old_cursor;
2601                 setUndo(bview, Undo::DELETE,
2602                         cursor.par(), cursor.par()->next()); 
2603                 cursor = tmpcursor;
2604                 backspace(bview);
2605         }
2606 }
2607
2608
2609 void LyXText::backspace(BufferView * bview)
2610 {
2611         // Get the font that is used to calculate the baselineskip
2612         Paragraph::size_type lastpos = cursor.par()->size();
2613         LyXFont rawparfont =
2614                 cursor.par()->getFontSettings(bview->buffer()->params,
2615                                               lastpos - 1);
2616
2617         if (cursor.pos() == 0) {
2618                 // The cursor is at the beginning of a paragraph,
2619                 // so the the backspace will collapse two paragraphs into one.
2620                 
2621                 // we may paste some paragraphs
2622       
2623                 // is it an empty paragraph?
2624       
2625                 if ((lastpos == 0
2626                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2627                         // This is an empty paragraph and we delete it just by moving the cursor one step
2628                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2629                         // of the paragraph.
2630                         
2631                         if (cursor.par()->previous()) {
2632                                 Paragraph * tmppar = cursor.par()->previous();
2633                                 if (cursor.par()->getLayout() == tmppar->getLayout()
2634                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2635                                         // Inherit bottom DTD from the paragraph below.
2636                                         // (the one we are deleting)
2637                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2638                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2639                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2640                                 }
2641                                 
2642                                 cursorLeft(bview);
2643                      
2644                                 // the layout things can change the height of a row !
2645                                 int const tmpheight = cursor.row()->height();
2646                                 setHeightOfRow(bview, cursor.row());
2647                                 if (cursor.row()->height() != tmpheight) {
2648                                         refresh_y = cursor.y() - cursor.row()->baseline();
2649                                         refresh_row = cursor.row();
2650                                         status(bview, LyXText::NEED_MORE_REFRESH);
2651                                 }
2652                                 return;
2653                         }
2654                 }
2655
2656                 if (cursor.par()->previous()) {
2657                         setUndo(bview, Undo::DELETE,
2658                                 cursor.par()->previous(), cursor.par()->next());
2659                 }
2660                 
2661                 Paragraph * tmppar = cursor.par();
2662                 Row * tmprow = cursor.row();
2663
2664                 // We used to do cursorLeftIntern() here, but it is
2665                 // not a good idea since it triggers the auto-delete
2666                 // mechanism. So we do a cursorLeftIntern()-lite,
2667                 // without the dreaded mechanism. (JMarc)
2668                 if (cursor.par()->previous()) { 
2669                         // steps into the above paragraph.
2670                         setCursorIntern(bview, cursor.par()->previous(),
2671                                         cursor.par()->previous()->size(),
2672                                         false);
2673                 }
2674
2675                 /* Pasting is not allowed, if the paragraphs have different
2676                    layout. I think it is a real bug of all other
2677                    word processors to allow it. It confuses the user.
2678                    Even so with a footnote paragraph and a non-footnote
2679                    paragraph. I will not allow pasting in this case, 
2680                    because the user would be confused if the footnote behaves 
2681                    different wether it is open or closed.
2682                   
2683                    Correction: Pasting is always allowed with standard-layout
2684                 */
2685                 if (cursor.par() != tmppar
2686                     && (cursor.par()->getLayout() == tmppar->getLayout()
2687                         || tmppar->getLayout() == 0 /*standard*/)
2688                     && cursor.par()->getAlign() == tmppar->getAlign())
2689                 {
2690                         removeParagraph(tmprow);
2691                         removeRow(tmprow);
2692                         cursor.par()->pasteParagraph(bview->buffer()->params);
2693                         
2694                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2695                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2696                         // strangely enough it seems that commenting out the line above removes
2697                         // most or all of the segfaults. I will however also try to move the
2698                         // two Remove... lines in front of the PasteParagraph too.
2699                         else
2700                                 if (cursor.pos())
2701                                         cursor.pos(cursor.pos() - 1);
2702                         
2703                         status(bview, LyXText::NEED_MORE_REFRESH);
2704                         refresh_row = cursor.row();
2705                         refresh_y = cursor.y() - cursor.row()->baseline();
2706                         
2707                         // remove the lost paragraph
2708                         // This one is not safe, since the paragraph that the tmprow and the
2709                         // following rows belong to has been deleted by the PasteParagraph
2710                         // above. The question is... could this be moved in front of the
2711                         // PasteParagraph?
2712                         //RemoveParagraph(tmprow);
2713                         //RemoveRow(tmprow);  
2714                         
2715                         // This rebuilds the rows.
2716                         appendParagraph(bview, cursor.row());
2717                         updateCounters(bview, cursor.row());
2718                         
2719                         // the row may have changed, block, hfills etc.
2720                         setCursor(bview, cursor.par(), cursor.pos(), false);
2721                 }
2722         } else {
2723                 /* this is the code for a normal backspace, not pasting
2724                  * any paragraphs */ 
2725                 setUndo(bview, Undo::DELETE,
2726                         cursor.par(), cursor.par()->next()); 
2727                 // We used to do cursorLeftIntern() here, but it is
2728                 // not a good idea since it triggers the auto-delete
2729                 // mechanism. So we do a cursorLeftIntern()-lite,
2730                 // without the dreaded mechanism. (JMarc)
2731                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2732                                 false, cursor.boundary());
2733                 
2734                 // some insets are undeletable here
2735                 if (cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET) {
2736                         if (!cursor.par()->getInset(cursor.pos())->deletable())
2737                                 return; 
2738                         // force complete redo when erasing display insets
2739                         // this is a cruel method but safe..... Matthias 
2740                         if (cursor.par()->getInset(cursor.pos())->display() ||
2741                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2742                                 cursor.par()->erase(cursor.pos());
2743                                 redoParagraph(bview);
2744                                 return;
2745                         }
2746                 }
2747                 
2748                 Row * row = cursor.row();
2749                 int y = cursor.y() - row->baseline();
2750                 Paragraph::size_type z;
2751                 /* remember that a space at the end of a row doesnt count
2752                  * when calculating the fill */ 
2753                 if (cursor.pos() < rowLast(row) ||
2754                     !cursor.par()->isLineSeparator(cursor.pos())) {
2755                         row->fill(row->fill() + singleWidth(bview,
2756                                                             cursor.par(),
2757                                                             cursor.pos()));
2758                 }
2759                 
2760                 /* some special code when deleting a newline. This is similar
2761                  * to the behavior when pasting paragraphs */ 
2762                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2763                         cursor.par()->erase(cursor.pos());
2764                         // refresh the positions
2765                         Row * tmprow = row;
2766                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2767                                 tmprow = tmprow->next();
2768                                 tmprow->pos(tmprow->pos() - 1);
2769                         }
2770                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2771                                 cursor.pos(cursor.pos() - 1);
2772
2773                         if (cursor.pos() < cursor.par()->size()
2774                             && !cursor.par()->isSeparator(cursor.pos())) {
2775                                 cursor.par()->insertChar(cursor.pos(), ' ');
2776                                 setCharFont(bview->buffer(), cursor.par(), 
2777                                             cursor.pos(), current_font);
2778                                 // refresh the positions
2779                                 tmprow = row;
2780                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2781                                         tmprow = tmprow->next();
2782                                         tmprow->pos(tmprow->pos() + 1);
2783                                 }
2784                         }
2785                 } else {
2786                         cursor.par()->erase(cursor.pos());
2787                         
2788                         // refresh the positions
2789                         Row * tmprow = row;
2790                         while (tmprow->next()
2791                                && tmprow->next()->par() == row->par()) {
2792                                 tmprow = tmprow->next();
2793                                 tmprow->pos(tmprow->pos() - 1);
2794                         }
2795
2796                         // delete newlines at the beginning of paragraphs
2797                         while (cursor.par()->size() &&
2798                                cursor.par()->isNewline(cursor.pos()) &&
2799                                cursor.pos() == beginningOfMainBody(bview->buffer(),
2800                                                                    cursor.par())) {
2801                                 cursor.par()->erase(cursor.pos());
2802                                 // refresh the positions
2803                                 tmprow = row;
2804                                 while (tmprow->next() && 
2805                                        tmprow->next()->par() == row->par()) {
2806                                         tmprow = tmprow->next();
2807                                         tmprow->pos(tmprow->pos() - 1);
2808                                 }
2809                         }
2810                 }
2811                 
2812                 // is there a break one row above
2813                 if (row->previous() && row->previous()->par() == row->par()) {
2814                         z = nextBreakPoint(bview, row->previous(),
2815                                            workWidth(bview));
2816                         if (z >= row->pos()) {
2817                                 row->pos(z + 1);
2818                                 
2819                                 Row * tmprow = row->previous();
2820                                 
2821                                 // maybe the current row is now empty
2822                                 if (row->pos() >= row->par()->size()) {
2823                                         // remove it
2824                                         removeRow(row);
2825                                         need_break_row = 0;
2826                                 } else {
2827                                         breakAgainOneRow(bview, row);
2828                                         if (row->next() && row->next()->par() == row->par())
2829                                                 need_break_row = row->next();
2830                                         else
2831                                                 need_break_row = 0;
2832                                 }
2833                                 
2834                                 // set the dimensions of the row above
2835                                 y -= tmprow->height();
2836                                 tmprow->fill(fill(bview, tmprow,
2837                                                   workWidth(bview)));
2838                                 setHeightOfRow(bview, tmprow);
2839                                 
2840                                 refresh_y = y;
2841                                 refresh_row = tmprow;
2842                                 status(bview, LyXText::NEED_MORE_REFRESH);
2843                                 setCursor(bview, cursor.par(), cursor.pos(),
2844                                           false, cursor.boundary());
2845                                 //current_font = rawtmpfont;
2846                                 //real_current_font = realtmpfont;
2847                                 // check, whether the last character's font has changed.
2848                                 if (rawparfont !=
2849                                     cursor.par()->getFontSettings(bview->buffer()->params,
2850                                                                   cursor.par()->size() - 1))
2851                                         redoHeightOfParagraph(bview, cursor);
2852                                 return;
2853                         }
2854                 }
2855                 
2856                 // break the cursor row again
2857                 if (row->next() && row->next()->par() == row->par() &&
2858                     (rowLast(row) == row->par()->size() - 1 ||
2859                      nextBreakPoint(bview, row, workWidth(bview)) != rowLast(row))) {
2860                         
2861                         /* it can happen that a paragraph loses one row
2862                          * without a real breakup. This is when a word
2863                          * is to long to be broken. Well, I don t care this 
2864                          * hack ;-) */
2865                         if (rowLast(row) == row->par()->size() - 1)
2866                                 removeRow(row->next());
2867                         
2868                         refresh_y = y;
2869                         refresh_row = row;
2870                         status(bview, LyXText::NEED_MORE_REFRESH);
2871                         
2872                         breakAgainOneRow(bview, row);
2873                         // will the cursor be in another row now?
2874                         if (row->next() && row->next()->par() == row->par() &&
2875                             rowLast(row) <= cursor.pos()) {
2876                                 row = row->next();
2877                                 breakAgainOneRow(bview, row);
2878                         }
2879
2880                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2881
2882                         if (row->next() && row->next()->par() == row->par())
2883                                 need_break_row = row->next();
2884                         else
2885                                 need_break_row = 0;
2886                 } else  {
2887                         // set the dimensions of the row
2888                         row->fill(fill(bview, row, workWidth(bview)));
2889                         int const tmpheight = row->height();
2890                         setHeightOfRow(bview, row);
2891                         if (tmpheight == row->height())
2892                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2893                         else
2894                                 status(bview, LyXText::NEED_MORE_REFRESH);
2895                         refresh_y = y;
2896                         refresh_row = row;
2897                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2898                 }
2899         }
2900
2901         // current_font = rawtmpfont;
2902         // real_current_font = realtmpfont;
2903
2904         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2905             != cursor.boundary())
2906                 setCursor(bview, cursor.par(), cursor.pos(), false,
2907                           !cursor.boundary());
2908
2909         lastpos = cursor.par()->size();
2910         if (cursor.pos() == lastpos)
2911                 setCurrentFont(bview);
2912         
2913         // check, whether the last characters font has changed.
2914         if (rawparfont != 
2915             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2916                 redoHeightOfParagraph(bview, cursor);
2917         } else {
2918                 // now the special right address boxes
2919                 if (textclasslist.Style(bview->buffer()->params.textclass,
2920                                         cursor.par()->getLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
2921                         redoDrawingOfParagraph(bview, cursor); 
2922                 }
2923         }
2924 }
2925
2926
2927 bool LyXText::paintRowBackground(DrawRowParams & p)
2928 {
2929         bool clear_area = true;
2930         Inset * inset = 0;
2931         LyXFont font(LyXFont::ALL_SANE);
2932
2933         Paragraph::size_type const last = rowLastPrintable(p.row);
2934
2935         if (!p.bv->screen()->forceClear() && last == p.row->pos()
2936                 && isMetaInset(p.row->par(), p.row->pos())) {
2937                 inset = p.row->par()->getInset(p.row->pos());
2938                 if (inset) {
2939                         clear_area = inset->doClearArea();
2940                 }
2941         }
2942  
2943         if (p.cleared) {
2944                 return true;
2945         } 
2946         
2947         if (clear_area) {
2948                 int const x = p.xo;
2949                 int const y = p.yo < 0 ? 0 : p.yo;
2950                 int const h = p.yo < 0 ? p.row->height() + p.yo : p.row->height();
2951                 p.pain->fillRectangle(x, y, p.width, h, backgroundColor());
2952                 return true;
2953         }
2954  
2955         if (inset == 0)
2956                 return false;
2957  
2958         int h = p.row->baseline() - inset->ascent(p.bv, font);
2959  
2960         // first clear the whole row above the inset!
2961         if (h > 0) {
2962                 p.pain->fillRectangle(p.xo, p.yo, p.width, h, backgroundColor());
2963         }
2964
2965         // clear the space below the inset!
2966         h += inset->ascent(p.bv, font) + inset->descent(p.bv, font);
2967         if ((p.row->height() - h) > 0) {
2968                 p.pain->fillRectangle(p.xo, p.yo + h, 
2969                         p.width, p.row->height() - h, backgroundColor());
2970         }
2971
2972         // clear the space behind the inset, if needed
2973         if (!inset->display() && !inset->needFullRow()) {
2974                 int const xp = int(p.x) + inset->width(p.bv, font);
2975                 if (p.width - xp > 0) {
2976                         p.pain->fillRectangle(xp, p.yo, p.width - xp,
2977                                 p.row->height(), backgroundColor());
2978                 }
2979         }
2980  
2981         return false;
2982 }
2983
2984
2985 void LyXText::paintRowSelection(DrawRowParams & p)
2986 {
2987         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
2988
2989         // the current selection
2990         int const startx = selection.start.x();
2991         int const endx = selection.end.x();
2992         int const starty = selection.start.y();
2993         int const endy = selection.end.y();
2994         Row const * startrow = selection.start.row();
2995         Row const * endrow = selection.end.row();
2996  
2997         Row * row = p.row;
2998  
2999         if (bidi_same_direction) {
3000                 int x;
3001                 int y = p.yo;
3002                 int w;
3003                 int h = row->height();
3004  
3005                 if (startrow == row && endrow == row) {
3006                         if (startx < endx) {
3007                                 x = p.xo + startx;
3008                                 w = endx - startx;
3009                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3010                         } else {
3011                                 x = p.xo + endx;
3012                                 w = startx - endx;
3013                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3014                         }
3015                 } else if (startrow == row) {
3016                         int const x = (is_rtl) ? p.xo : (p.xo + startx);
3017                         int const w = (is_rtl) ? startx : (p.width - startx);
3018                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3019                 } else if (endrow == row) {
3020                         int const x = (is_rtl) ? (p.xo + endx) : p.xo;
3021                         int const w = (is_rtl) ? (p.width - endx) : endx;
3022                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3023                 } else if (p.y > starty && p.y < endy) {
3024                         p.pain->fillRectangle(p.xo, y, p.width, h, LColor::selection);
3025                 }
3026                 return;
3027         } else if (startrow != row && endrow != row) {
3028                 int w = p.width;
3029                 int h = row->height();
3030                 if (p.y > starty && p.y < endy) {
3031                         p.pain->fillRectangle(p.xo, p.yo, w, h, LColor::selection);
3032                 }
3033                 return;
3034         }
3035  
3036         if (!((startrow != row && !is_rtl) || (endrow != row && is_rtl))) {
3037                 return;
3038         }
3039  
3040         float tmpx = p.x;
3041  
3042         p.pain->fillRectangle(p.xo, p.yo, int(p.x), row->height(), LColor::selection);
3043  
3044         Buffer const * buffer = p.bv->buffer();
3045         Paragraph * par = row->par();
3046         Paragraph::size_type main_body = beginningOfMainBody(buffer, par);
3047         Paragraph::size_type const last = rowLastPrintable(row);
3048  
3049         for (Paragraph::size_type vpos = row->pos(); vpos <= last; ++vpos)  {
3050                 Paragraph::size_type pos = vis2log(vpos);
3051                 float const old_tmpx = tmpx;
3052                 if (main_body > 0 && pos == main_body - 1) {
3053                         LyXLayout const & layout = textclasslist.Style(buffer->params.textclass,
3054                                 par->getLayout());
3055                         LyXFont const lfont = getLabelFont(buffer, par);
3056                          
3057  
3058                         tmpx += p.label_hfill + lyxfont::width(layout.labelsep, lfont);
3059
3060                         if (par->isLineSeparator(main_body - 1))
3061                                 tmpx -= singleWidth(p.bv, par, main_body - 1);
3062                 }
3063  
3064                 if (hfillExpansion(buffer, row, pos)) {
3065                         tmpx += singleWidth(p.bv, par, pos);
3066                         if (pos >= main_body)
3067                                 tmpx += p.hfill;
3068                         else 
3069                                 tmpx += p.label_hfill;
3070                 }
3071  
3072                 else if (par->isSeparator(pos)) {
3073                         tmpx += singleWidth(p.bv, par, pos);
3074                         if (pos >= main_body)
3075                                 tmpx += p.separator;
3076                 } else {
3077                         tmpx += singleWidth(p.bv, par, pos);
3078                 }
3079                 
3080                 if ((startrow != row || selection.start.pos() <= pos) &&
3081                         (endrow != row || pos < selection.end.pos())) {
3082                         // Here we do not use p.x as p.xo was added to p.x.
3083                         p.pain->fillRectangle(int(old_tmpx), p.yo,
3084                                 int(tmpx - old_tmpx + 1),
3085                                 row->height(), LColor::selection);
3086                 }
3087
3088                 if ((startrow != row && is_rtl) || (endrow != row && !is_rtl)) {
3089                         p.pain->fillRectangle(p.xo + int(tmpx),
3090                                 p.yo, int(p.bv->workWidth() - tmpx),
3091                                 row->height(), LColor::selection);
3092                 }
3093         }
3094 }
3095  
3096
3097 void LyXText::paintRowAppendix(DrawRowParams & p)
3098 {
3099         // FIXME: can be just p.width ?
3100         int const ww = p.bv->workWidth();
3101         Paragraph * firstpar = p.row->par();
3102
3103         if (firstpar->params().appendix()) {
3104                 p.pain->line(1, p.yo, 1, p.yo + p.row->height(), LColor::appendixline);
3105                 p.pain->line(ww - 2, p.yo, ww - 2, p.yo + p.row->height(), LColor::appendixline);
3106         }
3107 }
3108
3109  
3110 void LyXText::paintRowDepthBar(DrawRowParams & p)
3111 {
3112         Paragraph::depth_type const depth = p.row->par()->getDepth();
3113  
3114         if (depth <= 0)
3115                 return;
3116
3117         Paragraph::depth_type prev_depth = 0;
3118         if (p.row->previous())
3119                 prev_depth = p.row->previous()->par()->getDepth();
3120         Paragraph::depth_type next_depth = 0;
3121         if (p.row->next())
3122                 next_depth = p.row->next()->par()->getDepth();
3123
3124         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3125                 int const x = (LYX_PAPER_MARGIN / 5) * i + p.xo;
3126                 int const h = p.yo + p.row->height() - 1 - (i - next_depth - 1) * 3;
3127  
3128                 p.pain->line(x, p.yo, x, h, LColor::depthbar);
3129         
3130                 int const w = LYX_PAPER_MARGIN / 5;
3131  
3132                 if (i > prev_depth) {
3133                         p.pain->fillRectangle(x, p.yo, w, 2, LColor::depthbar);
3134                 }
3135                 if (i > next_depth) {
3136                         p.pain->fillRectangle(x, h, w, 2, LColor::depthbar);
3137                 }
3138         }
3139 }
3140
3141  
3142 void LyXText::paintFirstRow(DrawRowParams & p)
3143 {
3144         Paragraph * par = p.row->par(); 
3145         ParagraphParameters const & parparams = par->params();
3146  
3147         // start of appendix?
3148         if (parparams.startOfAppendix()) {
3149                 p.pain->line(1, p.yo, p.width - 2, p.yo, LColor::appendixline);
3150         }
3151         
3152         int y_top = 0;
3153                 
3154         // think about the margins
3155         if (!p.row->previous() && bv_owner)
3156                 y_top += LYX_PAPER_MARGIN;
3157
3158         // draw a top pagebreak
3159         if (parparams.pagebreakTop()) {
3160                 int const y = p.yo + y_top + 2*defaultHeight();
3161                 p.pain->line(0, y, p.width, y, LColor::pagebreak, Painter::line_onoffdash);
3162  
3163                 int w = 0;
3164                 int a = 0;
3165                 int d = 0;
3166  
3167                 LyXFont pb_font;
3168                 pb_font.setColor(LColor::pagebreak).decSize();
3169                 lyxfont::rectText(_("Page Break (top)"), pb_font, w, a, d);
3170                 p.pain->rectText((p.width - w)/2, y + d,
3171                               _("Page Break (top)"), pb_font,
3172                               backgroundColor(),
3173                               backgroundColor());
3174                 y_top += 3 * defaultHeight();
3175         }
3176         
3177         // draw a vfill top
3178         if (parparams.spaceTop().kind() == VSpace::VFILL) {
3179                 int const y1 = p.yo + y_top + 3 * defaultHeight();
3180                 int const y2 = p.yo + 2 + y_top;
3181  
3182                 p.pain->line(0, y1, LYX_PAPER_MARGIN, y1, LColor::vfillline);
3183                 
3184                 p.pain->line(0, y2, LYX_PAPER_MARGIN, y2, LColor::vfillline);
3185
3186                 int const x = LYX_PAPER_MARGIN / 2;
3187  
3188                 p.pain->line(x, y2, x, y1, LColor::vfillline);
3189                 
3190                 y_top += 3 * defaultHeight();
3191         }
3192         
3193         // think about user added space
3194         y_top += int(parparams.spaceTop().inPixels(p.bv));
3195         
3196         Buffer const * buffer = p.bv->buffer();
3197  
3198         LyXLayout const & layout =
3199                 textclasslist.Style(buffer->params.textclass, par->getLayout());
3200
3201         // think about the parskip
3202         // some parskips VERY EASY IMPLEMENTATION
3203         if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3204                 if (par->previous()) {
3205                         if (layout.latextype == LATEX_PARAGRAPH
3206                                 && !par->getDepth()) {
3207                                 y_top += buffer->params.getDefSkip().inPixels(p.bv);
3208                         } else {
3209                                 LyXLayout const & playout =
3210                                         textclasslist.Style(buffer->params.textclass,
3211                                                 par->previous()->getLayout()); 
3212                                 if (playout.latextype == LATEX_PARAGRAPH
3213                                         && !par->previous()->getDepth()) {
3214                                         // is it right to use defskip here, too? (AS) 
3215                                         y_top += buffer->params.getDefSkip().inPixels(p.bv);
3216                                 }
3217                         }
3218                 }
3219         }
3220         
3221         int const ww = p.bv->workWidth();
3222  
3223         // draw a top line
3224         if (parparams.lineTop()) {
3225                 LyXFont font(LyXFont::ALL_SANE);
3226                 int const asc = lyxfont::ascent('x', getFont(buffer, par, 0));
3227  
3228                 y_top += asc;
3229  
3230                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3231                 int const xp = static_cast<int>(inset_owner ? p.x : 0);
3232                 p.pain->line(xp, p.yo + y_top, w, p.yo + y_top,
3233                         LColor::topline, Painter::line_solid,
3234                         Painter::line_thick);
3235                 
3236                 y_top += asc;
3237         }
3238         
3239         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3240
3241         // should we print a label?
3242         if (layout.labeltype >= LABEL_STATIC
3243             && (layout.labeltype != LABEL_STATIC
3244                 || layout.latextype != LATEX_ENVIRONMENT
3245                 || par->isFirstInSequence())) {
3246  
3247                 LyXFont font = getLabelFont(buffer, par);
3248                 if (!par->getLabelstring().empty()) {
3249                         float x = p.x;
3250                         string const str = par->getLabelstring();
3251                         
3252                         // this is special code for the chapter layout. This is
3253                         // printed in an extra row and has a pagebreak at
3254                         // the top.
3255                         if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3256                                 if (buffer->params.secnumdepth >= 0) {
3257                                         float spacing_val = 1.0;
3258                                         if (!parparams.spacing().isDefault()) {
3259                                                 spacing_val = parparams.spacing().getValue();
3260                                         } else {
3261                                                 spacing_val = buffer->params.spacing.getValue();
3262                                         }
3263  
3264                                         int const maxdesc = 
3265                                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3266                                                 + int(layout.parsep) * defaultHeight();
3267  
3268                                         if (is_rtl) {
3269                                                 x = ww - leftMargin(p.bv, p.row) - 
3270                                                         lyxfont::width(str, font);
3271                                         }
3272  
3273                                         p.pain->text(int(x), p.yo +
3274                                                 p.yo + p.row->baseline() - 
3275                                                 p.row->ascent_of_text() - maxdesc,
3276                                                 str, font);
3277                                 }
3278                         } else {
3279                                 if (is_rtl) {
3280                                         x = ww - leftMargin(p.bv, p.row)
3281                                                 + lyxfont::width(layout.labelsep, font);
3282                                 } else
3283                                         x = p.x - lyxfont::width(layout.labelsep, font)
3284                                                 - lyxfont::width(str, font);
3285
3286                                 p.pain->text(int(x), p.yo + p.row->baseline(), str, font);
3287                         }
3288                 }
3289         // the labels at the top of an environment.
3290         // More or less for bibliography
3291         } else if (par->isFirstInSequence() &&
3292                 (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3293                 layout.labeltype == LABEL_BIBLIO ||
3294                 layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
3295                 LyXFont font = getLabelFont(buffer, par);
3296                 if (!par->getLabelstring().empty()) {
3297                         string const str = par->getLabelstring();
3298                         float spacing_val = 1.0;
3299                         if (!parparams.spacing().isDefault()) {
3300                                 spacing_val = parparams.spacing().getValue();
3301                         } else {
3302                                 spacing_val = buffer->params.spacing.getValue();
3303                         }
3304  
3305                         int maxdesc = 
3306                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3307                                 + (layout.labelbottomsep * defaultHeight()));
3308                         
3309                         float x = p.x;
3310                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3311                                 x = ((is_rtl ? leftMargin(p.bv, p.row) : p.x)
3312                                          + ww - rightMargin(buffer, p.row) ) / 2; 
3313                                 x -= lyxfont::width(str, font) / 2;
3314                         } else if (is_rtl) {
3315                                 x = ww - leftMargin(p.bv, p.row) - 
3316                                         lyxfont::width(str, font);
3317                         }
3318                         p.pain->text(int(x), p.yo + p.row->baseline()
3319                                   - p.row->ascent_of_text() - maxdesc,
3320                                   str, font);
3321                 }
3322         }
3323  
3324         if (layout.labeltype == LABEL_BIBLIO && par->bibkey) {
3325                 LyXFont font = getLayoutFont(buffer, par);
3326                 float x;
3327                 if (is_rtl) {
3328                         x = ww - leftMargin(p.bv, p.row)
3329                                 + lyxfont::width(layout.labelsep, font);
3330                 } else {
3331                         x = p.x - lyxfont::width(layout.labelsep, font)
3332                                 - par->bibkey->width(p.bv, font);
3333                 }
3334                 par->bibkey->draw(p.bv, font, p.yo + p.row->baseline(), x, p.cleared);
3335         }
3336 }
3337         
3338  
3339 void LyXText::paintLastRow(DrawRowParams & p)
3340 {
3341         Paragraph * par = p.row->par();
3342         ParagraphParameters const & parparams = par->params();
3343         int y_bottom = p.row->height();
3344         
3345         // think about the margins
3346         if (!p.row->next() && bv_owner)
3347                 y_bottom -= LYX_PAPER_MARGIN;
3348         
3349         int const ww = p.bv->workWidth();
3350  
3351         // draw a bottom pagebreak
3352         if (parparams.pagebreakBottom()) {
3353                 LyXFont pb_font;
3354                 pb_font.setColor(LColor::pagebreak).decSize();
3355                 int const y = p.yo + y_bottom - 2 * defaultHeight();
3356  
3357                 p.pain->line(0, y, ww, y, LColor::pagebreak, Painter::line_onoffdash);
3358  
3359                 int w = 0;
3360                 int a = 0;
3361                 int d = 0;
3362                 lyxfont::rectText(_("Page Break (bottom)"), pb_font, w, a, d);
3363                 p.pain->rectText((ww - w) / 2, y + d,
3364                         _("Page Break (bottom)"),
3365                         pb_font, backgroundColor(), backgroundColor());
3366  
3367                 y_bottom -= 3 * defaultHeight();
3368         }
3369         
3370         // draw a vfill bottom
3371         if (parparams.spaceBottom().kind() == VSpace::VFILL) {
3372                 int const x = LYX_PAPER_MARGIN / 2; 
3373                 int const x2 = LYX_PAPER_MARGIN;
3374                 int const y = p.yo + y_bottom - 3 * defaultHeight();
3375                 int const y2 = p.yo + y_bottom - 2;
3376                 
3377                 p.pain->line(0, y, x2, y, LColor::vfillline);
3378                 p.pain->line(0, y2, x2, y2, LColor::vfillline);
3379                 p.pain->line(x, y, x, y2, LColor::vfillline);
3380  
3381                 y_bottom -= 3 * defaultHeight();
3382         }
3383         
3384         // think about user added space
3385         y_bottom -= int(parparams.spaceBottom().inPixels(p.bv));
3386         
3387         Buffer const * buffer = p.bv->buffer();
3388  
3389         // draw a bottom line
3390         if (parparams.lineBottom()) {
3391                 LyXFont font(LyXFont::ALL_SANE);
3392                 int const asc = lyxfont::ascent('x',
3393                         getFont(buffer, par,
3394                         max(Paragraph::size_type(0), par->size() - 1)));
3395  
3396                 y_bottom -= asc;
3397  
3398                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3399                 int const xp = static_cast<int>(inset_owner ? p.x : 0);
3400                 int const y = p.yo + y_bottom; 
3401                 p.pain->line(xp, y, w, y, LColor::topline, Painter::line_solid,
3402                           Painter::line_thick);
3403  
3404                 y_bottom -= asc;
3405         }
3406
3407         Paragraph::size_type const last = rowLastPrintable(p.row);
3408         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3409         int const endlabel = par->getEndLabel(buffer->params);
3410  
3411         // draw an endlabel
3412         switch (endlabel) {
3413         case END_LABEL_BOX:
3414         case END_LABEL_FILLED_BOX:
3415         {
3416                 LyXFont const font = getFont(buffer, par, last);
3417                 int const size = int(0.75 * lyxfont::maxAscent(font));
3418                 int const y = (p.yo + p.row->baseline()) - size;
3419                 int x = is_rtl ? LYX_PAPER_MARGIN : ww - LYX_PAPER_MARGIN - size;
3420
3421                 if (p.row->fill() <= size)
3422                         x += (size - p.row->fill() + 1) * (is_rtl ? -1 : 1);
3423  
3424                 if (endlabel == END_LABEL_BOX) {
3425                         p.pain->line(x, y, x, y + size, LColor::eolmarker);
3426                         p.pain->line(x + size, y, x + size , y + size, LColor::eolmarker);
3427                         p.pain->line(x, y, x + size, y, LColor::eolmarker);
3428                         p.pain->line(x, y + size, x + size, y + size, LColor::eolmarker);
3429                 } else {
3430                         p.pain->fillRectangle(x, y, size, size, LColor::eolmarker);
3431                 }
3432                 break;
3433         }
3434         case END_LABEL_STATIC:
3435         {
3436                 LyXFont font(LyXFont::ALL_SANE);
3437                 LyXTextClass::LayoutList::size_type layout = par->getLayout();
3438                 string const str = textclasslist.
3439                         Style(buffer->params.textclass, layout).endlabelstring();
3440                 font = getLabelFont(buffer, par);
3441                 int const x = is_rtl ?
3442                         int(p.x) - lyxfont::width(str, font)
3443                         : ww - rightMargin(buffer, p.row) - p.row->fill();
3444                 p.pain->text(x, p.yo + p.row->baseline(), str, font);
3445                 break;
3446         }
3447         case END_LABEL_NO_LABEL:
3448                 break;
3449         }
3450 }
3451
3452 void LyXText::paintRowText(DrawRowParams & p)
3453 {
3454         Paragraph * par = p.row->par();
3455         Buffer const * buffer = p.bv->buffer(); 
3456  
3457         Paragraph::size_type const last = rowLastPrintable(p.row);
3458         Paragraph::size_type main_body = 
3459                 beginningOfMainBody(buffer, par);
3460         if (main_body > 0 && 
3461                 (main_body - 1 > last || 
3462                 !par->isLineSeparator(main_body - 1))) {
3463                 main_body = 0;
3464         }
3465         
3466         LyXLayout const & layout =
3467                 textclasslist.Style(buffer->params.textclass, par->getLayout());
3468
3469         Paragraph::size_type vpos = p.row->pos();
3470         while (vpos <= last) {
3471                 Paragraph::size_type pos = vis2log(vpos);
3472                 if (main_body > 0 && pos == main_body - 1) {
3473                         int const lwidth = lyxfont::width(layout.labelsep,
3474                                 getLabelFont(buffer, par));
3475
3476                         p.x += p.label_hfill + lwidth
3477                                 - singleWidth(p.bv, par, main_body - 1);
3478                 }
3479                 
3480                 if (par->isHfill(pos)) {
3481                         p.x += 1;
3482
3483                         int const y0 = p.yo + p.row->baseline();
3484                         int const y1 = y0 - defaultHeight() / 2;
3485
3486                         p.pain->line(int(p.x), y1, int(p.x), y0,
3487                                      LColor::vfillline);
3488                         
3489                         if (hfillExpansion(buffer, p.row, pos)) {
3490                                 int const y2 = (y0 + y1) / 2;
3491                                 
3492                                 if (pos >= main_body) {
3493                                         p.pain->line(int(p.x), y2,
3494                                                   int(p.x + p.hfill), y2,
3495                                                   LColor::vfillline,
3496                                                   Painter::line_onoffdash);
3497                                         p.x += p.hfill;
3498                                 } else {
3499                                         p.pain->line(int(p.x), y2,
3500                                                   int(p.x + p.label_hfill), y2,
3501                                                   LColor::vfillline,
3502                                                   Painter::line_onoffdash);
3503                                         p.x += p.label_hfill;
3504                                 }
3505                                 p.pain->line(int(p.x), y1,
3506                                              int(p.x), y0,
3507                                              LColor::vfillline);
3508                         }
3509                         p.x += 2;
3510                         ++vpos;
3511                 } else if (par->isSeparator(pos)) {
3512                         p.x += singleWidth(p.bv, par, pos);
3513                         if (pos >= main_body)
3514                                 p.x += p.separator;
3515                         ++vpos;
3516                 } else {
3517                         draw(p.bv, p.row, vpos, p.yo, p.x, p.cleared);
3518                 }
3519         }
3520 }
3521
3522
3523 void LyXText::getVisibleRow(BufferView * bv, int y_offset, int x_offset,
3524                             Row * row, int y, bool cleared)
3525 {
3526         if (row->height() <= 0) {
3527                 lyxerr << "LYX_ERROR: row.height: "
3528                        << row->height() << endl;
3529                 return;
3530         }
3531
3532         DrawRowParams p;
3533
3534         // set up drawing parameters
3535         p.bv = bv;
3536         p.pain = &bv->painter();
3537         p.row = row;
3538         p.xo = x_offset;
3539         p.yo = y_offset;
3540         prepareToPrint(bv, row, p.x, p.separator, p.hfill, p.label_hfill);
3541         if (inset_owner && (p.x < 0))
3542                 p.x = 0;
3543         p.x += p.xo;
3544         p.y = y;
3545         p.width = inset_owner ? inset_owner->textWidth(bv, true) : bv->workWidth();
3546         p.cleared = cleared;
3547          
3548         // start painting
3549
3550         // clear to background if necessary
3551         p.cleared = paintRowBackground(p);
3552
3553         // paint the selection background
3554         if (selection.set()) {
3555                 paintRowSelection(p);
3556         }
3557
3558         // vertical lines for appendix
3559         paintRowAppendix(p);
3560
3561         // environment depth brackets
3562         paintRowDepthBar(p);
3563  
3564         // draw any stuff wanted for a first row of a paragraph
3565         if (!row->pos()) {
3566                 paintFirstRow(p);
3567         }
3568
3569         // draw any stuff wanted for the last row of a paragraph
3570         if (!row->next() || (row->next()->par() != row->par())) {
3571                 paintLastRow(p);
3572         } 
3573
3574         // paint text
3575         paintRowText(p); 
3576 }
3577
3578
3579 int LyXText::defaultHeight() const
3580 {
3581         LyXFont font(LyXFont::ALL_SANE);
3582         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3583 }
3584
3585    
3586 /* returns the column near the specified x-coordinate of the row 
3587 * x is set to the real beginning of this column  */ 
3588 Paragraph::size_type
3589 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3590                         bool & boundary) const
3591 {
3592         float tmpx = 0.0;
3593         float fill_separator;
3594         float fill_hfill;
3595         float fill_label_hfill;
3596    
3597         prepareToPrint(bview, row, tmpx, fill_separator,
3598                        fill_hfill, fill_label_hfill);
3599
3600         Paragraph::size_type vc = row->pos();
3601         Paragraph::size_type last = rowLastPrintable(row);
3602         Paragraph::size_type c = 0;
3603         LyXLayout const & layout =
3604                 textclasslist.Style(bview->buffer()->params.textclass,
3605                                     row->par()->getLayout());
3606         bool left_side = false;
3607
3608         Paragraph::size_type
3609                 main_body = beginningOfMainBody(bview->buffer(), row->par());
3610         float last_tmpx = tmpx;
3611         
3612         if (main_body > 0 &&
3613             (main_body - 1 > last || 
3614              !row->par()->isLineSeparator(main_body - 1)))
3615                 main_body = 0;
3616         
3617         while (vc <= last && tmpx <= x) {
3618                 c = vis2log(vc);
3619                 last_tmpx = tmpx;
3620                 if (main_body > 0 && c == main_body-1) {
3621                         tmpx += fill_label_hfill +
3622                                 lyxfont::width(layout.labelsep,
3623                                                getLabelFont(bview->buffer(), row->par()));
3624                         if (row->par()->isLineSeparator(main_body - 1))
3625                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3626                 }
3627                 
3628                 if (hfillExpansion(bview->buffer(), row, c)) {
3629                         x += singleWidth(bview, row->par(), c);
3630                         if (c >= main_body)
3631                                 tmpx += fill_hfill;
3632                         else
3633                                 tmpx += fill_label_hfill;
3634                 }
3635                 else if (row->par()->isSeparator(c)) {
3636                         tmpx += singleWidth(bview, row->par(), c);
3637                         if (c >= main_body)
3638                                 tmpx+= fill_separator;
3639                 } else
3640                         tmpx += singleWidth(bview, row->par(), c);
3641                 ++vc;
3642         }
3643         
3644         if ((tmpx + last_tmpx) / 2 > x) {
3645                 tmpx = last_tmpx;
3646                 left_side = true;
3647         }
3648
3649         if (vc > last + 1)  // This shouldn't happen.
3650                 vc = last + 1;
3651
3652         boundary = false;
3653         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3654                                          // some speedup if rtl_support=false
3655                 && (!row->next() || row->next()->par() != row->par());
3656         bool const rtl = (lastrow)
3657                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3658                 : false; // If lastrow is false, we don't need to compute
3659                          // the value of rtl.
3660
3661         if (row->pos() > last)  // Row is empty?
3662                 c = row->pos();
3663         else if (lastrow &&
3664                  ( ( rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3665                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5) ))
3666                 c = last + 1;
3667         else if (vc == row->pos()) {
3668                 c = vis2log(vc);
3669                 if (bidi_level(c) % 2 == 1)
3670                         ++c;
3671         } else {
3672                 c = vis2log(vc - 1);
3673                 bool const rtl = (bidi_level(c) % 2 == 1);
3674                 if (left_side == rtl) {
3675                         ++c;
3676                         boundary = isBoundary(bview->buffer(), row->par(), c);
3677                 }
3678         }
3679
3680         if (row->pos() <= last && c > last
3681             && row->par()->isNewline(last)) {
3682                 if (bidi_level(last) % 2 == 0)
3683                         tmpx -= singleWidth(bview, row->par(), last);
3684                 else
3685                         tmpx += singleWidth(bview, row->par(), last);
3686                 c = last;
3687         }
3688
3689         c -= row->pos();
3690         x = int(tmpx);
3691         return c;
3692 }
3693
3694
3695 // returns pointer to a specified row
3696 Row * LyXText::getRow(Paragraph * par,
3697                       Paragraph::size_type pos, int & y) const
3698 {
3699         if (!firstrow)
3700                 return 0;
3701         
3702         Row * tmprow = firstrow;
3703         y = 0;
3704         
3705         // find the first row of the specified paragraph
3706         while (tmprow->next() && tmprow->par() != par) {
3707                 y += tmprow->height();
3708                 tmprow = tmprow->next();
3709         }
3710         
3711         // now find the wanted row
3712         while (tmprow->pos() < pos
3713                && tmprow->next()
3714                && tmprow->next()->par() == par
3715                && tmprow->next()->pos() <= pos) {
3716                 y += tmprow->height();
3717                 tmprow = tmprow->next();
3718         }
3719         
3720         return tmprow;
3721 }