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