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