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