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