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