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