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