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