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