]> git.lyx.org Git - lyx.git/blob - src/text.C
5f3e19075db868636e72942ca22cda2460652475
[lyx.git] / src / text.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12 #include <cstdlib>
13 #include <cctype>
14 #include <algorithm>
15
16 #include "layout.h"
17 #include "lyxparagraph.h"
18 #include "lyxtext.h"
19 #include "support/textutils.h"
20 #include "insets/insetbib.h"
21 #include "insets/insettext.h"
22 #include "lyx_gui_misc.h"
23 #include "gettext.h"
24 #include "bufferparams.h"
25 #include "buffer.h"
26 #include "minibuffer.h"
27 #include "debug.h"
28 #include "lyxrc.h"
29 #include "LyXView.h"
30 #include "lyxrow.h"
31 #include "Painter.h"
32 #include "tracer.h"
33 #include "font.h"
34 #include "encoding.h"
35 #include "lyxscreen.h"
36
37 using std::max;
38 using std::min;
39 using std::endl;
40 using std::pair;
41
42 static const int LYX_PAPER_MARGIN = 20;
43
44 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
45
46
47 int LyXText::workWidth(BufferView * bview) const
48 {
49         if (inset_owner) {
50                 return inset_owner->textWidth(bview->painter());
51         }
52         return bview->workWidth();
53 }
54
55
56 unsigned char LyXText::TransformChar(unsigned char c, LyXParagraph * par,
57                         LyXParagraph::size_type pos) const
58 {
59         if (!Encoding::is_arabic(c))
60                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && isdigit(c))
61                         return c + (0xb0 - '0');
62                 else
63                         return c;
64
65         unsigned char prev_char = pos > 0 ? par->GetChar(pos-1) : ' ';
66         unsigned char next_char = ' ';
67         for (LyXParagraph::size_type i = pos+1; i < par->Last(); ++i)
68                 if (!Encoding::IsComposeChar_arabic(par->GetChar(i))) {
69                         next_char = par->GetChar(i);
70                         break;
71                 }
72
73         if (Encoding::is_arabic(next_char)) {
74                 if (Encoding::is_arabic(prev_char))
75                         return Encoding::TransformChar(c, Encoding::FORM_MEDIAL);
76                 else
77                         return Encoding::TransformChar(c, Encoding::FORM_INITIAL);
78         } else {
79                 if (Encoding::is_arabic(prev_char))
80                         return Encoding::TransformChar(c, Encoding::FORM_FINAL);
81                 else
82                         return Encoding::TransformChar(c, Encoding::FORM_ISOLATED);
83         }
84 }
85
86 // This is the comments that some of the warnings below refers to.
87 // There are some issues in this file and I don't think they are
88 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
89 // this is a problem that has been here almost from day one and that a
90 // larger userbase with differenct access patters triggers the bad
91 // behaviour. (segfaults.) What I think happen is: In several places
92 // we store the paragraph in the current cursor and then moves the
93 // cursor. This movement of the cursor will delete paragraph at the
94 // old position if it is now empty. This will make the temporary
95 // pointer to the old cursor paragraph invalid and dangerous to use.
96 // And is some cases this will trigger a segfault. I have marked some
97 // of the cases where this happens with a warning, but I am sure there
98 // are others in this file and in text2.C. There is also a note in
99 // Delete() that you should read. In Delete I store the paragraph->id
100 // instead of a pointer to the paragraph. I am pretty sure this faulty
101 // use of temporary pointers to paragraphs that might have gotten
102 // invalidated (through a cursor movement) before they are used, are
103 // the cause of the strange crashes we get reported often.
104 //
105 // It is very tiresom to change this code, especially when it is as
106 // hard to read as it is. Help to fix all the cases where this is done
107 // would be greately appreciated.
108 //
109 // Lgb
110
111 int LyXText::SingleWidth(BufferView * bview, LyXParagraph * par,
112                          LyXParagraph::size_type pos) const
113 {
114         char const c = par->GetChar(pos);
115         return SingleWidth(bview, par, pos, c);
116 }
117
118
119 int LyXText::SingleWidth(BufferView * bview, LyXParagraph * par,
120                          LyXParagraph::size_type pos, char c) const
121 {
122         LyXFont font = GetFont(bview->buffer(), par, pos);
123
124         // The most common case is handled first (Asger)
125         if (IsPrintable(c)) {
126                 if (font.language()->RightToLeft()) {
127                         if (font.language()->lang() == "arabic" &&
128                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
129                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
130                                 if (Encoding::IsComposeChar_arabic(c))
131                                         return 0;
132                                 else
133                                         c = TransformChar(c, par, pos);
134                         else if (font.language()->lang() == "hebrew" &&
135                                  Encoding::IsComposeChar_hebrew(c))
136                                 return 0;
137                 }
138                 return lyxfont::width(c, font);
139
140         } else if (IsHfillChar(c)) {
141                 return 3;       /* Because of the representation
142                                  * as vertical lines */
143 #ifndef NEW_INSETS
144         } else if (c == LyXParagraph::META_FOOTNOTE ||
145                    c == LyXParagraph::META_MARGIN ||
146                    c == LyXParagraph::META_FIG ||
147                    c == LyXParagraph::META_TAB ||
148                    c == LyXParagraph::META_WIDE_FIG ||
149                    c == LyXParagraph::META_WIDE_TAB ||
150                    c == LyXParagraph::META_ALGORITHM) {
151                 string fs;
152                 switch (c) {
153                 case LyXParagraph::META_MARGIN:
154                         fs = "margin";
155                         break;
156                 case LyXParagraph::META_FIG:
157                         fs = "fig";
158                         break;
159                 case LyXParagraph::META_TAB:
160                         fs = "tab";
161                         break;
162                 case LyXParagraph::META_ALGORITHM:
163                         fs = "alg";
164                         break;
165                 case LyXParagraph::META_WIDE_FIG:
166                         fs = "wide-fig";
167                         break;
168                 case LyXParagraph::META_WIDE_TAB:
169                         fs = "wide-tab";
170                         break;
171                 case LyXParagraph::META_FOOTNOTE:
172                         fs = "foot";
173                         break;
174                 }
175                 font.decSize();
176                 font.decSize();
177                 return lyxfont::width(fs, font);
178 #endif
179         } else if (c == LyXParagraph::META_INSET) {
180                 Inset * tmpinset = par->GetInset(pos);
181                 if (tmpinset) {
182                         tmpinset->update(bview, font);
183                         return tmpinset->width(bview, font);
184                 } else
185                         return 0;
186
187         } else if (IsSeparatorChar(c))
188                 c = ' ';
189         else if (IsNewlineChar(c))
190                 c = 'n';
191         return lyxfont::width(c, font);
192 }
193
194
195 // Returns the paragraph position of the last character in the specified row
196 LyXParagraph::size_type LyXText::RowLast(Row const * row) const
197 {
198         if (row->next() == 0)
199                 return row->par()->Last() - 1;
200         else if (row->next()->par() != row->par()) 
201                 return row->par()->Last() - 1;
202         else 
203                 return row->next()->pos() - 1;
204 }
205
206
207 LyXParagraph::size_type LyXText::RowLastPrintable(Row const * row) const
208 {
209         LyXParagraph::size_type last = RowLast(row);
210         if (last >= row->pos()
211             && row->next()
212             && row->next()->par() == row->par()
213             && row->par()->IsSeparator(last))
214                 return last - 1;
215         else
216                 return last;
217 }
218
219
220 void LyXText::ComputeBidiTables(Buffer const * buf, Row * row) const
221 {
222         bidi_same_direction = true;
223         if (!lyxrc.rtl_support) {
224                 bidi_start = -1;
225                 return;
226         }
227
228         bidi_start = row->pos();
229         bidi_end = RowLastPrintable(row);
230
231         if (bidi_start > bidi_end) {
232                 bidi_start = -1;
233                 return;
234         }
235
236         if (bidi_end + 2 - bidi_start >
237             static_cast<LyXParagraph::size_type>(log2vis_list.size())) {
238                 LyXParagraph::size_type new_size = 
239                         (bidi_end + 2 - bidi_start < 500) ?
240                         500 : 2 * (bidi_end + 2 - bidi_start);
241                 log2vis_list.resize(new_size);
242                 vis2log_list.resize(new_size);
243                 bidi_levels.resize(new_size);
244         }
245
246         vis2log_list[bidi_end + 1 - bidi_start] = -1;
247         log2vis_list[bidi_end + 1 - bidi_start] = -1;
248
249         LyXParagraph::size_type stack[2];
250         bool rtl_par = row->par()->getParLanguage(buf->params)->RightToLeft();
251         int level = 0;
252         bool rtl = false;
253         bool rtl0 = false;
254         LyXParagraph::size_type main_body = BeginningOfMainBody(buf, row->par());
255
256         for (LyXParagraph::size_type lpos = bidi_start;
257              lpos <= bidi_end; ++lpos) {
258                 bool is_space = row->par()->IsLineSeparator(lpos);
259                 LyXParagraph::size_type pos =
260                         (is_space && lpos + 1 <= bidi_end &&
261                          !row->par()->IsLineSeparator(lpos + 1) &&
262                          !row->par()->IsNewline(lpos + 1))
263                         ? lpos + 1 : lpos;
264                 LyXFont font = row->par()->GetFontSettings(buf->params, pos);
265                 bool new_rtl = font.isVisibleRightToLeft();
266                 bool new_rtl0 = font.isRightToLeft();
267                 int new_level;
268
269                 if (lpos == main_body - 1
270                     && row->pos() < main_body - 1
271                     && row->par()->IsLineSeparator(lpos)) {
272                         new_level = (rtl_par) ? 1 : 0;
273                         new_rtl = new_rtl0 = rtl_par;
274                 } else if (new_rtl0)
275                         new_level = (new_rtl) ? 1 : 2;
276                 else
277                         new_level = (rtl_par) ? 2 : 0;
278
279                 if (is_space && new_level >= level) {
280                         new_level = level;
281                         new_rtl = rtl;
282                         new_rtl0 = rtl0;
283                 }
284
285                 int new_level2 = new_level;
286
287                 if (level == new_level && rtl0 != new_rtl0) {
288                         --new_level2;
289                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
290                 } else if (level < new_level) {
291                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
292                         if (new_level > rtl_par)
293                                 bidi_same_direction = false;
294                 } else
295                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
296                 rtl = new_rtl;
297                 rtl0 = new_rtl0;
298                 bidi_levels[lpos - bidi_start] = new_level;
299
300                 while (level > new_level2) {
301                         LyXParagraph::size_type old_lpos =
302                                 stack[--level];
303                         int delta = lpos - old_lpos - 1;
304                         if (level % 2)
305                                 delta = -delta;
306                         log2vis_list[lpos - bidi_start] += delta;
307                         log2vis_list[old_lpos - bidi_start] += delta;
308                 }
309                 while (level < new_level)
310                         stack[level++] = lpos;
311         }
312
313         while (level > 0) {
314                 LyXParagraph::size_type old_lpos = stack[--level];
315                 int delta = bidi_end - old_lpos;
316                 if (level % 2)
317                         delta = -delta;
318                 log2vis_list[old_lpos - bidi_start] += delta;
319         }
320
321         LyXParagraph::size_type vpos = bidi_start - 1;
322         for (LyXParagraph::size_type lpos = bidi_start;
323              lpos <= bidi_end; ++lpos) {
324                 vpos += log2vis_list[lpos - bidi_start];
325                 vis2log_list[vpos - bidi_start] = lpos;
326                 log2vis_list[lpos - bidi_start] = vpos;
327         }
328 }
329
330
331 // This method requires a previous call to ComputeBidiTables()
332 bool LyXText::IsBoundary(Buffer const * buf, LyXParagraph * par,
333                          LyXParagraph::size_type pos) const
334 {
335         if (!lyxrc.rtl_support)
336                 return false;    // This is just for speedup
337
338         if (!bidi_InRange(pos - 1))
339                 return false;
340
341         bool const rtl = bidi_level(pos - 1) % 2;
342         bool rtl2 = rtl;
343         if (pos == par->Last())
344                 rtl2 = par->isRightToLeftPar(buf->params);
345         else if (bidi_InRange(pos))
346                 rtl2 = bidi_level(pos) % 2;
347         return rtl != rtl2;
348 }
349
350
351 bool LyXText::IsBoundary(Buffer const * buf, LyXParagraph * par,
352                          LyXParagraph::size_type pos,
353                          LyXFont const & font) const
354 {
355         if (!lyxrc.rtl_support)
356                 return false;    // This is just for speedup
357
358         bool const rtl = font.isVisibleRightToLeft();
359         bool rtl2 = rtl;
360         if (pos == par->Last())
361                 rtl2 = par->isRightToLeftPar(buf->params);
362         else if (bidi_InRange(pos))
363                 rtl2 =  bidi_level(pos) % 2;
364         return rtl != rtl2;
365 }
366
367
368 void LyXText::draw(BufferView * bview, Row const * row,
369                    LyXParagraph::size_type & vpos,
370                    int offset, float & x, bool cleared)
371 {
372         Painter & pain = bview->painter();
373         
374         LyXParagraph::size_type pos = vis2log(vpos);
375         char c = row->par()->GetChar(pos);
376         float tmpx = x;
377
378         if (IsNewlineChar(c)) {
379                 ++vpos;
380                 // Draw end-of-line marker
381                 LyXFont font = GetFont(bview->buffer(), row->par(), pos);
382                 int wid = lyxfont::width('n', font);
383                 int asc = lyxfont::maxAscent(font);
384                 int y = offset + row->baseline();
385                 int xp[3], yp[3];
386                 
387                 if (bidi_level(pos) % 2 == 0) {
388                         xp[0] = int(x + wid * 0.375);
389                         yp[0] = int(y - 0.875 * asc * 0.75);
390                         
391                         xp[1] = int(x);
392                         yp[1] = int(y - 0.500 * asc * 0.75);
393                         
394                         xp[2] = int(x + wid * 0.375);
395                         yp[2] = int(y - 0.125 * asc * 0.75);
396                         
397                         pain.lines(xp, yp, 3, LColor::eolmarker);
398                         
399                         xp[0] = int(x);
400                         yp[0] = int(y - 0.500 * asc * 0.75);
401                         
402                         xp[1] = int(x + wid);
403                         yp[1] = int(y - 0.500 * asc * 0.75);
404                         
405                         xp[2] = int(x + wid);
406                         yp[2] = int(y - asc * 0.75);
407                         
408                         pain.lines(xp, yp, 3, LColor::eolmarker);
409                 } else {
410                         xp[0] = int(x + wid * 0.625);
411                         yp[0] = int(y - 0.875 * asc * 0.75);
412                         
413                         xp[1] = int(x + wid);
414                         yp[1] = int(y - 0.500 * asc * 0.75);
415                         
416                         xp[2] = int(x + wid * 0.625);
417                         yp[2] = int(y - 0.125 * asc * 0.75);
418                         
419                         pain.lines(xp, yp, 3, LColor::eolmarker);
420                         
421                         xp[0] = int(x + wid);
422                         yp[0] = int(y - 0.500 * asc * 0.75);
423                         
424                         xp[1] = int(x);
425                         yp[1] = int(y - 0.500 * asc * 0.75);
426                         
427                         xp[2] = int(x);
428                         yp[2] = int(y - asc * 0.75);
429                         
430                         pain.lines(xp, yp, 3, LColor::eolmarker);
431                 }
432                 x += wid;
433                 return;
434         }
435
436         LyXFont font = GetFont(bview->buffer(), row->par(), pos);
437         LyXFont font2 = font;
438 #ifndef NEW_INSETS
439         if (c == LyXParagraph::META_FOOTNOTE
440             || c == LyXParagraph::META_MARGIN
441             || c == LyXParagraph::META_FIG
442             || c == LyXParagraph::META_TAB
443             || c == LyXParagraph::META_WIDE_FIG
444             || c == LyXParagraph::META_WIDE_TAB
445             || c == LyXParagraph::META_ALGORITHM) {
446                 string fs;
447                 switch (c) {
448                 case LyXParagraph::META_MARGIN:
449                         fs = "margin";
450                         break;
451                 case LyXParagraph::META_FIG:
452                         fs = "fig";
453                         break;
454                 case LyXParagraph::META_TAB:
455                         fs = "tab";
456                         break;
457                 case LyXParagraph::META_ALGORITHM:
458                         fs = "alg";
459                         break;
460                 case LyXParagraph::META_WIDE_FIG:
461                         fs = "wide-fig";
462                         break;
463                 case LyXParagraph::META_WIDE_TAB:
464                         fs = "wide-tab";
465                         break;
466                 case LyXParagraph::META_FOOTNOTE:
467                         fs = "foot";
468                         break;
469                 }
470                 font.decSize();
471                 font.decSize();
472           
473                 // calculate the position of the footnotemark
474                 int y = (row->baseline() - lyxfont::maxAscent(font2) 
475                          + lyxfont::maxAscent(font));
476           
477                 font.setColor(LColor::footnote);
478
479                 // draw it and set new x position
480                 
481                 pain.text(int(x), offset + y, fs, font);
482                 x += lyxfont::width(fs, font);
483                 pain.line(int(tmpx), offset + row->baseline(),
484                           int(x), offset + row->baseline(),
485                           LColor::footnote);
486
487                 ++vpos;
488                 return;
489         } else
490 #endif
491                 if (c == LyXParagraph::META_INSET) {
492                 Inset * tmpinset = row->par()->GetInset(pos);
493                 if (tmpinset) {
494 //                      tmpinset->update(bview, font, false);
495                         tmpinset->draw(bview, font, offset+row->baseline(), x,
496                                        cleared);
497                         if (status == CHANGED_IN_DRAW) {
498                                 UpdateInset(bview, tmpinset);
499                                 status = CHANGED_IN_DRAW;
500                         }
501                 }
502                 ++vpos;
503
504                 if (lyxrc.mark_foreign_language &&
505                     font.language()->lang() != "default" &&
506                     font.language() != bview->buffer()->params.language_info) {
507                         int y = offset + row->height() - 1;
508                         pain.line(int(tmpx), y, int(x), y,
509                                   LColor::language);
510                 }
511
512                 return;
513         }
514
515         /* usual characters, no insets */
516
517         // Collect character that we can draw in one command
518
519         // This is dirty, but fast. Notice that it will never be too small.
520         // For the record, I'll note that Microsoft Word has a limit
521         // of 768 here. We have none :-) (Asger)
522         // Ok. I am the first to admit that the use of std::string will be
523         // a tiny bit slower than using a POD char array. However, I claim
524         // that this slowdown is so small that it is close to inperceptive.
525         // So IMHO we should go with the easier and clearer implementation.
526         // And even if 1024 is a large number here it might overflow, string
527         // will only overflow if the machine is out of memory...
528         static string textstring;
529         textstring = c;
530         ++vpos;
531
532         LyXParagraph::size_type last = RowLastPrintable(row);
533
534         if (font.language()->lang() == "hebrew") {
535                 if (Encoding::IsComposeChar_hebrew(c)) {
536                         int width = lyxfont::width(c, font2);
537                         int dx = 0;
538                         for (LyXParagraph::size_type i = pos-1; i >= 0; --i) {
539                                 c = row->par()->GetChar(i);
540                                 if (!Encoding::IsComposeChar_hebrew(c)) {
541                                         if (IsPrintableNonspace(c)) {
542                                                 int width2 = SingleWidth(bview, row->par(), i, c);
543                                                 dx = (c == 'ø' || c == 'ã') // dalet / resh
544                                                         ? width2 - width : (width2 - width) / 2;
545                                         }
546                                         break;
547                                 }
548                         }
549                         // Draw nikud
550                         pain.text(int(x) + dx, offset + row->baseline(),
551                                   textstring, font);
552                 } else {
553                         while (vpos <= last &&
554                                (pos = vis2log(vpos)) >= 0
555                                && IsPrintableNonspace(c = row->par()->GetChar(pos))
556                                && !Encoding::IsComposeChar_hebrew(c)
557                                && font2 == GetFont(bview->buffer(), row->par(), pos)) {
558                                 textstring += c;
559                                 ++vpos;
560                         }
561                         // Draw text and set the new x position
562                         pain.text(int(x), offset + row->baseline(),
563                                   textstring, font);
564                         x += lyxfont::width(textstring, font);
565                 }
566         } else if (font.language()->lang() == "arabic" &&
567                    (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
568                     lyxrc.font_norm_type == LyXRC::ISO_10646_1)) {
569                 if (Encoding::IsComposeChar_arabic(c)) {
570                         c = TransformChar(c, row->par(), pos);
571                         textstring = c;
572                         int width = lyxfont::width(c, font2);
573                         int dx = 0;
574                         for (LyXParagraph::size_type i = pos-1; i >= 0; --i) {
575                                 c = row->par()->GetChar(i);
576                                 if (!Encoding::IsComposeChar_arabic(c)) {
577                                         if (IsPrintableNonspace(c)) {
578                                                 int width2 = SingleWidth(bview, row->par(), i, c);
579                                                 dx = (width2 - width) / 2;
580                                         }
581                                         break;
582                                 }
583                         }
584                         // Draw nikud
585                         pain.text(int(x) + dx, offset + row->baseline(), 
586                                   textstring, font);
587                 } else {
588                         textstring = TransformChar(c, row->par(), pos);
589                         while (vpos <= last &&
590                                (pos = vis2log(vpos)) >= 0
591                                && IsPrintableNonspace(c = row->par()->GetChar(pos))
592                                && !Encoding::IsComposeChar_arabic(c)
593                                && font2 == GetFont(bview->buffer(), row->par(), pos)) {
594                                 c = TransformChar(c, row->par(), pos);
595                                 textstring += c;
596                                 ++vpos;
597                         }
598                         // Draw text and set the new x position
599                         pain.text(int(x), offset + row->baseline(),
600                                   textstring, font);
601                         x += lyxfont::width(textstring, font);
602                 }
603         } else {
604                 while (vpos <= last &&
605                        (pos = vis2log(vpos)) >= 0
606                        && IsPrintableNonspace(c = row->par()->GetChar(pos))
607                        && font2 == GetFont(bview->buffer(), row->par(), pos)) {
608                         textstring += c;
609                         ++vpos;
610                 }
611                 // Draw text and set the new x position
612                 pain.text(int(x), offset + row->baseline(), textstring, font);
613                 x += lyxfont::width(textstring, font);
614         }
615
616         if (lyxrc.mark_foreign_language &&
617             font.language()->lang() != "default" &&
618             font.language() != bview->buffer()->params.language_info) {
619                 int y = offset + row->height() - 1;
620                 pain.line(int(tmpx), y, int(x), y,
621                           LColor::language);
622         }
623
624         // If we want ulem.sty support, drawing
625         // routines should go here. (Asger)
626         // Why shouldn't LyXFont::drawText handle it internally?
627 }
628
629
630 // Returns the left beginning of the text. 
631 // This information cannot be taken from the layouts-objekt, because in 
632 // LaTeX the beginning of the text fits in some cases (for example sections)
633 // exactly the label-width.
634 int LyXText::LeftMargin(BufferView * bview, Row const * row) const
635 {
636         LyXLayout const & layout =
637                 textclasslist.Style(bview->buffer()->params.textclass,
638                                     row->par()->GetLayout());
639         
640         string parindent = layout.parindent; 
641
642         int x = LYX_PAPER_MARGIN;
643         
644         x += lyxfont::signedWidth(textclasslist
645                                   .TextClass(bview->buffer()->params.textclass)
646                                   .leftmargin(),
647                                   textclasslist
648                                   .TextClass(bview->buffer()->params.textclass)
649                                   .defaultfont());
650 #ifndef NEW_INSETS
651         if (row->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
652                 LyXFont font(LyXFont::ALL_SANE);
653                 font.setSize(LyXFont::SIZE_SMALL);
654                 x += lyxfont::width("Mwide-figM", font)
655                         + LYX_PAPER_MARGIN/2;
656         }
657 #endif
658         // this is the way, LyX handles the LaTeX-Environments.
659         // I have had this idea very late, so it seems to be a
660         // later added hack and this is true
661         if (!row->par()->GetDepth()) {
662                 if (!row->par()->GetLayout()) {
663                         // find the previous same level paragraph
664 #ifndef NEW_INSETS
665                         if (row->par()->FirstPhysicalPar()->Previous()) {
666 #else
667                         if (row->par()->Previous()) {
668 #endif
669                                 LyXParagraph * newpar = row->par()
670                                         ->DepthHook(row->par()->GetDepth());
671                                 if (newpar &&
672                                     textclasslist.Style(bview->buffer()->params.textclass,
673                                                         newpar->GetLayout())
674                                     .nextnoindent)
675                                         parindent.erase();
676                         }
677                 }
678         } else {
679                 // find the next level paragraph
680                 
681                 LyXParagraph * newpar =
682                         row->par()->DepthHook(row->par()->GetDepth()-1);
683                 
684                 // make a corresponding row. Needed to call LeftMargin()
685                 
686                 // check wether it is a sufficent paragraph 
687                 if (newpar
688 #ifndef NEW_INSETS
689                     && newpar->footnoteflag == row->par()->footnoteflag
690 #endif
691                     && textclasslist
692                         .Style(bview->buffer()->params.textclass, 
693                                newpar->GetLayout()).isEnvironment()) {
694                         Row dummyrow;
695                         dummyrow.par(newpar);
696                         dummyrow.pos(newpar->Last());
697                         x = LeftMargin(bview, &dummyrow);
698                 } else {
699                         // this is no longer an error, because this function
700                         // is used to clear impossible depths after changing
701                         // a layout. Since there is always a redo,
702                         // LeftMargin() is always called
703 #ifndef NEW_INSETS
704                         row->par()->FirstPhysicalPar()->depth = 0;
705 #else
706                         row->par()->depth = 0;
707 #endif
708                 }
709                 
710                 if (newpar && !row->par()->GetLayout()) {
711 #ifndef NEW_INSETS
712                         if (newpar->FirstPhysicalPar()->noindent)
713 #else
714                         if (newpar->noindent)
715 #endif
716                                 parindent.erase();
717                         else
718                                 parindent = textclasslist
719                                         .Style(bview->buffer()->params.textclass, 
720                                                newpar->GetLayout()).parindent;
721                 }
722                 
723         }
724         
725         LyXFont const labelfont = GetFont(bview->buffer(), row->par(), -2);
726         switch (layout.margintype) {
727         case MARGIN_DYNAMIC:
728                 if (!layout.leftmargin.empty()) {
729                         x += lyxfont::signedWidth(layout.leftmargin,
730                                                   textclasslist
731                                                   .TextClass(bview->buffer()->params.
732                                                              textclass)
733                                                   .defaultfont());
734                 }
735                 if (!row->par()->GetLabelstring().empty()) {
736                         x += lyxfont::signedWidth(layout.labelindent,
737                                                   labelfont);
738                         x += lyxfont::width(row->par()->GetLabelstring(),
739                                             labelfont);
740                         x += lyxfont::width(layout.labelsep, labelfont);
741                 }
742                 break;
743         case MARGIN_MANUAL:
744                 x += lyxfont::signedWidth(layout.labelindent, labelfont);
745                 if (row->pos() >= BeginningOfMainBody(bview->buffer(), row->par())) {
746                         if (!row->par()->GetLabelWidthString().empty()) {
747                                 x += lyxfont::width(row->par()->GetLabelWidthString(),
748                                                labelfont);
749                                 x += lyxfont::width(layout.labelsep, labelfont);
750                         }
751                 }
752                 break;
753         case MARGIN_STATIC:
754                 x += lyxfont::signedWidth(layout.leftmargin, textclasslist.TextClass(bview->buffer()->params.textclass).defaultfont()) * 4
755                         / (row->par()->GetDepth() + 4);
756                 break;
757         case MARGIN_FIRST_DYNAMIC:
758                 if (layout.labeltype == LABEL_MANUAL) {
759                         if (row->pos() >= BeginningOfMainBody(bview->buffer(), row->par())) {
760                                 x += lyxfont::signedWidth(layout.leftmargin,
761                                                           labelfont);
762                         } else {
763                                 x += lyxfont::signedWidth(layout.labelindent,
764                                                           labelfont);
765                         }
766                 } else if (row->pos()
767                            // Special case to fix problems with
768                            // theorems (JMarc)
769                            || (layout.labeltype == LABEL_STATIC
770                                && layout.latextype == LATEX_ENVIRONMENT
771                                && ! row->par()->IsFirstInSequence())) {
772                         x += lyxfont::signedWidth(layout.leftmargin,
773                                                   labelfont);
774                 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
775                            && layout.labeltype != LABEL_BIBLIO
776                            && layout.labeltype !=
777                            LABEL_CENTERED_TOP_ENVIRONMENT) {
778                         x += lyxfont::signedWidth(layout.labelindent,
779                                                   labelfont);
780                         x += lyxfont::width(layout.labelsep, labelfont);
781                         x += lyxfont::width(row->par()->GetLabelstring(),
782                                             labelfont);
783                 } 
784                 break;
785                 
786         case MARGIN_RIGHT_ADDRESS_BOX:
787         {
788                 // ok, a terrible hack. The left margin depends on the widest
789                 // row in this paragraph. Do not care about footnotes, they
790                 // are *NOT* allowed in the LaTeX realisation of this layout.
791                 
792                 // find the first row of this paragraph
793                 Row const * tmprow = row;
794                 while (tmprow->previous()
795                        && tmprow->previous()->par() == row->par())
796                         tmprow = tmprow->previous();
797                 
798                 int minfill = tmprow->fill();
799                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
800                         tmprow = tmprow->next();
801                         if (tmprow->fill() < minfill)
802                                 minfill = tmprow->fill();
803                 }
804                 
805                 x += lyxfont::signedWidth(layout.leftmargin,
806                                           textclasslist
807                                           .TextClass(bview->buffer()->params.textclass)
808                                           .defaultfont());
809                 x += minfill;
810         }
811         break;
812         }
813         if ((workWidth(bview) > 0) &&
814             (row->par()->pextra_type == LyXParagraph::PEXTRA_INDENT)) {
815                 if (!row->par()->pextra_widthp.empty()) {
816                         x += workWidth(bview) *
817                                 lyx::atoi(row->par()->pextra_widthp) / 100;
818                 } else if (!row->par()->pextra_width.empty()) {
819                         int xx = VSpace(row->par()->pextra_width).inPixels(bview);
820                         if (xx > workWidth(bview))
821                                 xx = workWidth(bview) * 80 / 100;
822                         x += xx;
823                 } else { // should not happen
824                         LyXFont font(LyXFont::ALL_SANE);
825                         x += lyxfont::width("XXXXXX", font);
826                 }
827         }
828         
829         int align; // wrong type
830 #ifndef NEW_INSETS
831         if (row->par()->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
832                 align = layout.align;
833         else
834                 align = row->par()->FirstPhysicalPar()->align;
835 #else
836         if (row->par()->align == LYX_ALIGN_LAYOUT)
837                 align = layout.align;
838         else
839                 align = row->par()->align;
840 #endif  
841         // set the correct parindent
842         if (row->pos() == 0) {
843                 if ((layout.labeltype == LABEL_NO_LABEL 
844                      || layout.labeltype == LABEL_TOP_ENVIRONMENT 
845                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
846                      || (layout.labeltype == LABEL_STATIC
847                          && layout.latextype == LATEX_ENVIRONMENT
848                          && ! row->par()->IsFirstInSequence()))
849 #ifndef NEW_INSETS
850                     && row->par() == row->par()->FirstPhysicalPar()
851 #endif
852                     && align == LYX_ALIGN_BLOCK
853                     && !row->par()->noindent
854                     && (row->par()->layout ||
855                         bview->buffer()->params.paragraph_separation ==
856                         BufferParams::PARSEP_INDENT))
857                         x += lyxfont::signedWidth(parindent,
858                                                   textclasslist
859                                                   .TextClass(bview->buffer()->params
860                                                              .textclass)
861                                                   .defaultfont());
862                 else if (layout.labeltype == LABEL_BIBLIO) {
863                         // ale970405 Right width for bibitems
864                         x += bibitemMaxWidth(bview,textclasslist
865                                              .TextClass(bview->buffer()->params
866                                                         .textclass)
867                                              .defaultfont());
868                 }
869         }
870         return x;
871 }
872
873
874 int LyXText::RightMargin(Buffer const * buf, Row const * row) const
875 {
876         LyXLayout const & layout =
877                 textclasslist.Style(buf->params.textclass,
878                                     row->par()->GetLayout());
879         
880         int x = LYX_PAPER_MARGIN
881                 + lyxfont::signedWidth(textclasslist
882                                        .TextClass(buf->params.textclass)
883                                        .rightmargin(),
884                                        textclasslist
885                                        .TextClass(buf->params.textclass)
886                                        .defaultfont());
887
888 #ifndef NEW_INSETS
889         if (row->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
890                 x += LYX_PAPER_MARGIN / 2;
891         }
892 #endif
893         // this is the way, LyX handles the LaTeX-Environments.
894         // I have had this idea very late, so it seems to be a
895         // later added hack and this is true
896         if (row->par()->GetDepth()) {
897                 // find the next level paragraph
898                 
899                 LyXParagraph * newpar = row->par();
900                 
901 #ifndef NEW_INSETS
902                 do {
903                         newpar = newpar->FirstPhysicalPar()->Previous();
904                         if (newpar) 
905                                 newpar = newpar->FirstPhysicalPar();
906                 } while (newpar && newpar->GetDepth() >= row->par()->GetDepth()
907                          && newpar->footnoteflag == row->par()->footnoteflag);
908 #else
909                 do {
910                         newpar = newpar->Previous();
911                 } while (newpar
912                          && newpar->GetDepth() >= row->par()->GetDepth());
913 #endif
914                 
915                 // make a corresponding row. Needed to call LeftMargin()
916                 
917                 // check wether it is a sufficent paragraph
918                 if (newpar
919 #ifndef NEW_INSETS
920                     && newpar->footnoteflag == row->par()->footnoteflag
921 #endif
922                     && textclasslist.Style(buf->params.textclass,
923                                            newpar->GetLayout())
924                        .isEnvironment()) {
925                         Row dummyrow;
926                         dummyrow.par(newpar);
927                         dummyrow.pos(0);
928                         x = RightMargin(buf, &dummyrow);
929                 } else {
930                         // this is no longer an error, because this function
931                         // is used to clear impossible depths after changing
932                         // a layout. Since there is always a redo,
933                         // LeftMargin() is always called
934 #ifndef NEW_INSETS
935                         row->par()->FirstPhysicalPar()->depth = 0;
936 #else
937                         row->par()->depth = 0;
938 #endif
939                 }
940         }
941         
942         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
943         x += lyxfont::signedWidth(layout.rightmargin, textclasslist
944                                   .TextClass(buf->params.textclass)
945                                   .defaultfont()) * 4 / (row->par()->GetDepth()
946                                                          + 4);
947         return x;
948 }
949
950
951 int LyXText::LabelEnd (BufferView * bview, Row const * row) const
952 {
953         if (textclasslist.Style(bview->buffer()->params.textclass,
954                                 row->par()->GetLayout()).margintype
955             == MARGIN_MANUAL) {
956                 Row tmprow;
957                 tmprow = *row;
958                 tmprow.pos(row->par()->Last());
959                 return LeftMargin(bview, &tmprow);  /* just the beginning 
960                                                 of the main body */
961         } else
962                 return 0;  /* LabelEnd is only needed, if the  
963                               layout fills a flushleft
964                               label. */
965 }
966
967
968 // get the next breakpoint in a given paragraph
969 LyXParagraph::size_type
970 LyXText::NextBreakPoint(BufferView * bview, Row const * row, int width) const
971 {
972         LyXParagraph * par = row->par();
973         LyXParagraph::size_type pos = row->pos();
974
975         if (width < 0)
976                 return par->Last();
977
978         // position of the last possible breakpoint 
979         // -1 isn't a suitable value, but a flag
980         LyXParagraph::size_type last_separator = -1;
981         width -= RightMargin(bview->buffer(), row);
982         
983         LyXParagraph::size_type main_body = BeginningOfMainBody(bview->buffer(), par);
984         LyXLayout const & layout =
985                 textclasslist.Style(bview->buffer()->params.textclass, par->GetLayout());
986         LyXParagraph::size_type i = pos;
987
988         if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
989                 /* special code for right address boxes, only newlines count */
990                 while (i < par->Last()) {
991                         if (par->IsNewline(i)) {
992                                 last_separator = i;
993                                 i = par->Last() - 1; // this means break
994                                 //x = width;
995                         } else if (par->GetChar(i) == LyXParagraph::META_INSET &&
996                                    par->GetInset(i) && par->GetInset(i)->display()){
997                                 par->GetInset(i)->display(false);
998                         }
999                         ++i;
1000                 }
1001         } else {
1002                 // Last position is an invariant
1003                 LyXParagraph::size_type const last = 
1004                         par->Last();
1005                 // this is the usual handling
1006                 int x = LeftMargin(bview, row);
1007                 bool doitonetime = true;
1008                 while (doitonetime || ((x < width) && (i < last))) {
1009                         doitonetime = false;
1010                         char c = par->GetChar(i);
1011                         if (IsNewlineChar(c)) {
1012                                 last_separator = i;
1013                                 x = width; // this means break
1014                         } else if (c == LyXParagraph::META_INSET &&
1015                                    par->GetInset(i)) {
1016                                 
1017                                 // check wether a Display() inset is
1018                                 // valid here. if not, change it to
1019                                 // non-display
1020                                 if (par->GetInset(i)->display() &&
1021                                     (layout.isCommand() ||
1022                                      ((layout.labeltype == LABEL_MANUAL) &&
1023                                       (i < BeginningOfMainBody(bview->buffer(), par))))) {
1024                                         // display istn't allowd
1025                                         par->GetInset(i)->display(false);
1026                                         x += SingleWidth(bview, par, i, c);
1027                                 } else if (par->GetInset(i)->display() ||
1028                                          par->GetInset(i)->needFullRow()) {
1029                                         // So break the line here
1030                                         if (i == pos) {
1031                                                 if (pos < last-1) {
1032                                                         last_separator = i;
1033                                                         if (IsLineSeparatorChar(par->GetChar(i+1)))
1034                                                                 ++last_separator;
1035                                                 } else
1036                                                         last_separator = last; // to avoid extra rows
1037                                         } else
1038                                                 last_separator = i - 1;
1039                                         x = width;  // this means break
1040                                 } else {
1041 #if 0
1042                                         last_separator = i;
1043                                         x += width;
1044 #else
1045                                         x += SingleWidth(bview, par, i, c);
1046 #endif
1047                                 }
1048                         } else  {
1049                                 if (IsLineSeparatorChar(c))
1050                                         last_separator = i;
1051                                 x += SingleWidth(bview, par, i, c);
1052                         }
1053                         ++i;
1054                         if (i == main_body) {
1055                                 x += lyxfont::width(layout.labelsep,
1056                                                     GetFont(bview->buffer(), par, -2));
1057                                 if (par->IsLineSeparator(i - 1))
1058                                         x-= SingleWidth(bview, par, i - 1);
1059                                 int left_margin = LabelEnd(bview, row);
1060                                 if (x < left_margin)
1061                                         x = left_margin;
1062                         }
1063                 }
1064                 // end of paragraph is always a suitable separator
1065                 if (i == last && x < width)
1066                         last_separator = i;
1067         }
1068         
1069         // well, if last_separator is still 0, the line isn't breakable. 
1070         // don't care and cut simply at the end
1071         if (last_separator < 0) {
1072                 last_separator = i;
1073         }
1074         
1075         // manual labels cannot be broken in LaTeX, do not care
1076         if (main_body && last_separator < main_body)
1077                 last_separator = main_body - 1;
1078         
1079         return last_separator;
1080 }
1081
1082
1083 // returns the minimum space a row needs on the screen in pixel
1084 int LyXText::Fill(BufferView * bview, Row * row, int paper_width) const
1085 {
1086         if (paper_width < 0)
1087                 return 0;
1088
1089         int w;
1090         // get the pure distance
1091         LyXParagraph::size_type last = RowLastPrintable(row);
1092         
1093         // special handling of the right address boxes
1094         if (textclasslist.Style(bview->buffer()->params.textclass,
1095                                 row->par()->GetLayout()).margintype
1096             == MARGIN_RIGHT_ADDRESS_BOX) {
1097                 int tmpfill = row->fill();
1098                 row->fill(0); // the minfill in MarginLeft()
1099                 w = LeftMargin(bview, row);
1100                 row->fill(tmpfill);
1101         } else
1102                 w = LeftMargin(bview, row);
1103         
1104         LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
1105                                                        row->par()->GetLayout());
1106         LyXParagraph::size_type main_body = 
1107                 BeginningOfMainBody(bview->buffer(), row->par());
1108         LyXParagraph::size_type i = row->pos();
1109
1110         while (i <= last) {
1111                 if (main_body > 0 && i == main_body) {
1112                         w += lyxfont::width(layout.labelsep, GetFont(bview->buffer(), row->par(), -2));
1113                         if (row->par()->IsLineSeparator(i - 1))
1114                                 w -= SingleWidth(bview, row->par(), i - 1);
1115                         int left_margin = LabelEnd(bview, row);
1116                         if (w < left_margin)
1117                                 w = left_margin;
1118                 }
1119                 w += SingleWidth(bview, row->par(), i);
1120                 ++i;
1121         }
1122         if (main_body > 0 && main_body > last) {
1123                 w += lyxfont::width(layout.labelsep, GetFont(bview->buffer(), row->par(), -2));
1124                 if (last >= 0 && row->par()->IsLineSeparator(last))
1125                         w -= SingleWidth(bview, row->par(), last);
1126                 int left_margin = LabelEnd(bview, row);
1127                 if (w < left_margin)
1128                         w = left_margin;
1129         }
1130         
1131         int const fill = paper_width - w - RightMargin(bview->buffer(), row);
1132         return fill;
1133 }
1134
1135
1136 // returns the minimum space a manual label needs on the screen in pixel
1137 int LyXText::LabelFill(BufferView * bview, Row const * row) const
1138 {
1139         LyXParagraph::size_type last = BeginningOfMainBody(bview->buffer(), row->par()) - 1;
1140         // -1 because a label ends either with a space that is in the label, 
1141         // or with the beginning of a footnote that is outside the label.
1142
1143         // I don't understand this code in depth, but sometimes "last" is
1144         // less than 0 and this causes a crash. This fix seems to work
1145         // correctly, but I bet the real error is elsewhere.  The bug is
1146         // triggered when you have an open footnote in a paragraph
1147         // environment with a manual label. (Asger)
1148         if (last < 0) last = 0;
1149         
1150         if (row->par()->IsLineSeparator(last)) /* a sepearator at this end 
1151                                                 does not count */
1152                 --last;
1153         
1154         int w = 0;
1155         int i = row->pos();
1156         while (i <= last) {
1157                 w += SingleWidth(bview, row->par(), i);
1158                 ++i;
1159         }
1160         
1161         int fill = 0;
1162         if (!row->par()->labelwidthstring.empty()) {
1163                 fill = max(lyxfont::width(row->par()->labelwidthstring,
1164                                           GetFont(bview->buffer(), row->par(), -2)) - w,
1165                            0);
1166         }
1167         
1168         return fill;
1169 }
1170
1171
1172 // returns the number of separators in the specified row. The separator 
1173 // on the very last column doesnt count
1174 int LyXText::NumberOfSeparators(Buffer const * buf, Row const * row) const
1175 {
1176         LyXParagraph::size_type const last = RowLast(row);
1177         LyXParagraph::size_type p =
1178                 max(row->pos(), BeginningOfMainBody(buf, row->par()));
1179         int n = 0;
1180         for (; p < last; ++p) {
1181                 if (row->par()->IsSeparator(p)) {
1182                         ++n;
1183                 }
1184         }
1185         return n;
1186 }
1187
1188
1189 // returns the number of hfills in the specified row. The LyX-Hfill is
1190 // a LaTeX \hfill so that the hfills at the beginning and at the end were 
1191 // ignored. This is *MUCH* more usefull than not to ignore!
1192 int LyXText::NumberOfHfills(Buffer const * buf, Row const * row) const
1193 {
1194         LyXParagraph::size_type const last = RowLast(row);
1195         LyXParagraph::size_type first = row->pos();
1196         if (first) { /* hfill *DO* count at the beginning 
1197                       * of paragraphs! */
1198                 while(first <= last && row->par()->IsHfill(first))
1199                         ++first;
1200         }
1201
1202         first = max(first, BeginningOfMainBody(buf, row->par()));
1203         int n = 0;
1204         for (int p = first; p <= last; ++p) { // last, because the end is ignored!
1205                 if (row->par()->IsHfill(p)) {
1206                         ++n;
1207                 }
1208         }
1209         return n;
1210 }
1211
1212
1213 // like NumberOfHfills, but only those in the manual label!
1214 int LyXText::NumberOfLabelHfills(Buffer const * buf, Row const * row) const
1215 {
1216         LyXParagraph::size_type last = RowLast(row);
1217         LyXParagraph::size_type first = row->pos();
1218         if (first) { /* hfill *DO* count at the beginning 
1219                       * of paragraphs! */
1220                 while(first < last && row->par()->IsHfill(first))
1221                         ++first;
1222         }
1223
1224         last = min(last, BeginningOfMainBody(buf, row->par()));
1225         int n = 0;
1226         for (LyXParagraph::size_type p = first;
1227              p < last; ++p) {  // last, because the end is ignored!
1228                 if (row->par()->IsHfill(p)) {
1229                         ++n;
1230                 }
1231         }
1232         return n;
1233 }
1234
1235
1236 // returns true, if a expansion is needed.
1237 // Rules are given by LaTeX
1238 bool LyXText::HfillExpansion(Buffer const * buf, Row const * row_ptr,
1239                              LyXParagraph::size_type pos) const
1240 {
1241         // by the way, is it a hfill?
1242         if (!row_ptr->par()->IsHfill(pos))
1243                 return false;
1244         
1245         // at the end of a row it does not count
1246         if (pos >= RowLast(row_ptr))
1247                 return false;
1248         
1249         // at the beginning of a row it does not count, if it is not 
1250         // the first row of a paragaph
1251         if (!row_ptr->pos())
1252                 return true;
1253         
1254         // in some labels  it does not count
1255         if (textclasslist.Style(buf->params.textclass,
1256                                 row_ptr->par()->GetLayout()).margintype
1257             != MARGIN_MANUAL
1258             && pos < BeginningOfMainBody(buf, row_ptr->par()))
1259                 return false; 
1260         
1261         // if there is anything between the first char of the row and
1262         // the sepcified position that is not a newline and not a hfill,
1263         // the hfill will count, otherwise not
1264         LyXParagraph::size_type i = row_ptr->pos();
1265         while (i < pos && (row_ptr->par()->IsNewline(i)
1266                            || row_ptr->par()->IsHfill(i)))
1267                 ++i;
1268         
1269         return i != pos;
1270 }
1271
1272
1273 void LyXText::SetHeightOfRow(BufferView * bview, Row * row_ptr) const
1274 {
1275     /* get the maximum ascent and the maximum descent */
1276    int asc = 0;
1277    int desc = 0;
1278    float layoutasc = 0;
1279    float layoutdesc = 0;
1280    float tmptop = 0;
1281    LyXFont tmpfont;
1282    Inset * tmpinset = 0;
1283
1284    /* this must not happen before the currentrow for clear reasons.
1285       so the trick is just to set the current row onto this row */
1286    long unused_y;
1287    GetRow(row_ptr->par(), row_ptr->pos(), unused_y);
1288
1289    /* ok , let us initialize the maxasc and maxdesc value. 
1290     * This depends in LaTeX of the font of the last character
1291     * in the paragraph. The hack below is necessary because
1292     * of the possibility of open footnotes */
1293
1294    /* Correction: only the fontsize count. The other properties
1295       are taken from the layoutfont. Nicer on the screen :) */
1296 #ifndef NEW_INSETS   
1297    LyXParagraph * par = row_ptr->par()->LastPhysicalPar();
1298    LyXParagraph * firstpar = row_ptr->par()->FirstPhysicalPar();
1299 #else
1300    LyXParagraph * par = row_ptr->par();
1301    LyXParagraph * firstpar = row_ptr->par();
1302 #endif
1303    
1304    LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
1305                                                   firstpar->GetLayout());
1306    
1307    LyXFont font = GetFont(bview->buffer(), par, par->Last() - 1);
1308    LyXFont::FONT_SIZE size = font.size();
1309    font = GetFont(bview->buffer(), par, -1);
1310    font.setSize(size);
1311
1312    LyXFont labelfont = GetFont(bview->buffer(), par, -2);
1313
1314    float spacing_val = 1.0;
1315    if (!row_ptr->par()->spacing.isDefault()) {
1316            spacing_val = row_ptr->par()->spacing.getValue();
1317    } else {
1318            spacing_val = bview->buffer()->params.spacing.getValue();
1319    }
1320    //lyxerr << "spacing_val = " << spacing_val << endl;
1321    
1322    int maxasc = int(lyxfont::maxAscent(font) *
1323                    layout.spacing.getValue() *
1324                    spacing_val);
1325    int maxdesc = int(lyxfont::maxDescent(font) *
1326                     layout.spacing.getValue() *
1327                     spacing_val);
1328    int pos_end = RowLast(row_ptr);
1329    int labeladdon = 0;
1330    int maxwidth = 0;
1331
1332    // Check if any insets are larger
1333    for (int pos = row_ptr->pos(); pos <= pos_end; ++pos) {
1334            if (row_ptr->par()->GetChar(pos) == LyXParagraph::META_INSET) {
1335                    tmpfont = GetFont(bview->buffer(), row_ptr->par(), pos);
1336                    tmpinset = row_ptr->par()->GetInset(pos);
1337                    if (tmpinset) {
1338                            tmpinset->update(bview, tmpfont);
1339                            asc = tmpinset->ascent(bview, tmpfont);
1340                            desc = tmpinset->descent(bview, tmpfont);
1341                            maxwidth += tmpinset->width(bview, tmpfont);
1342                            maxasc = max(maxasc, asc);
1343                            maxdesc = max(maxdesc, desc);
1344                    }
1345            } else {
1346                    maxwidth += SingleWidth(bview, row_ptr->par(), pos);
1347            }
1348    }
1349
1350    // Check if any custom fonts are larger (Asger)
1351    // This is not completely correct, but we can live with the small,
1352    // cosmetic error for now.
1353    LyXFont::FONT_SIZE maxsize =
1354            row_ptr->par()->HighestFontInRange(row_ptr->pos(),
1355                                               pos_end);
1356    if (maxsize > font.size()) {
1357         font.setSize(maxsize);
1358
1359         asc = lyxfont::maxAscent(font);
1360         desc = lyxfont::maxDescent(font);
1361         if (asc > maxasc) 
1362                 maxasc = asc;
1363         if (desc > maxdesc)
1364                 maxdesc = desc;
1365    }
1366
1367    // This is nicer with box insets:
1368    ++maxasc;
1369    ++maxdesc;
1370
1371    row_ptr->ascent_of_text(maxasc);
1372    
1373    /* is it a top line? */ 
1374    if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
1375       
1376       /* some parksips VERY EASY IMPLEMENTATION */ 
1377       if (bview->buffer()->params.paragraph_separation ==
1378           BufferParams::PARSEP_SKIP) {
1379          if (layout.isParagraph()
1380              && firstpar->GetDepth() == 0
1381              && firstpar->Previous())
1382             maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1383          else if (firstpar->Previous()
1384                   && textclasslist.Style(bview->buffer()->params.textclass,
1385                            firstpar->Previous()->GetLayout()).isParagraph()
1386                   && firstpar->Previous()->GetDepth() == 0)
1387            // is it right to use defskip here too? (AS)
1388            maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1389       }
1390       
1391       /* the paper margins */ 
1392       if (!row_ptr->par()->previous && bv_owner)
1393          maxasc += LYX_PAPER_MARGIN;
1394       
1395       /* add the vertical spaces, that the user added */
1396       if (firstpar->added_space_top.kind() != VSpace::NONE)
1397          maxasc += int(firstpar->added_space_top.inPixels(bview));
1398       
1399       /* do not forget the DTP-lines! 
1400        * there height depends on the font of the nearest character */
1401       if (firstpar->line_top)
1402          maxasc += 2 * lyxfont::ascent('x', GetFont(bview->buffer(),
1403                                                     firstpar, 0));
1404       
1405       /* and now the pagebreaks */ 
1406       if (firstpar->pagebreak_top)
1407          maxasc += 3 * DefaultHeight();
1408       
1409       /*  this is special code for the chapter, since the label of this
1410        * layout is printed in an extra row */ 
1411       if (layout.labeltype == LABEL_COUNTER_CHAPTER
1412           && bview->buffer()->params.secnumdepth >= 0) {
1413               float spacing_val = 1.0;
1414               if (!row_ptr->par()->spacing.isDefault()) {
1415                       spacing_val = row_ptr->par()->spacing.getValue();
1416               } else {
1417                       spacing_val = bview->buffer()->params.spacing.getValue();
1418               }
1419               
1420               labeladdon = int(lyxfont::maxDescent(labelfont) *
1421                                layout.spacing.getValue() *
1422                                spacing_val)
1423                       + int(lyxfont::maxAscent(labelfont) *
1424                             layout.spacing.getValue() *
1425                             spacing_val);
1426       }
1427       
1428       /* special code for the top label */ 
1429       if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1430            || layout.labeltype == LABEL_BIBLIO
1431            || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1432           && row_ptr->par()->IsFirstInSequence()
1433           && !row_ptr->par()->GetLabelstring().empty()) {
1434               float spacing_val = 1.0;
1435               if (!row_ptr->par()->spacing.isDefault()) {
1436                       spacing_val = row_ptr->par()->spacing.getValue();
1437               } else {
1438                       spacing_val = bview->buffer()->params.spacing.getValue();
1439               }
1440               
1441               labeladdon = int(
1442                       (lyxfont::maxAscent(labelfont) *
1443                        layout.spacing.getValue() *
1444                        spacing_val)
1445                       +(lyxfont::maxDescent(labelfont) *
1446                         layout.spacing.getValue() *
1447                         spacing_val)
1448                       + layout.topsep * DefaultHeight()
1449                       + layout.labelbottomsep *  DefaultHeight());
1450       }
1451    
1452       /* and now the layout spaces, for example before and after a section, 
1453        * or between the items of a itemize or enumerate environment */ 
1454       
1455       if (!firstpar->pagebreak_top) {
1456          LyXParagraph * prev = row_ptr->par()->Previous();
1457          if (prev)
1458             prev = row_ptr->par()->DepthHook(row_ptr->par()->GetDepth());
1459          if (prev && prev->GetLayout() == firstpar->GetLayout()
1460              && prev->GetDepth() == firstpar->GetDepth()
1461              && prev->GetLabelWidthString() == firstpar->GetLabelWidthString())
1462            {
1463               layoutasc = (layout.itemsep * DefaultHeight());
1464            }
1465          else if (row_ptr->previous()) {
1466             tmptop = layout.topsep;
1467             
1468             if (row_ptr->previous()->par()->GetDepth() >= row_ptr->par()->GetDepth())
1469                tmptop -= textclasslist.Style(bview->buffer()->params.textclass,
1470                                              row_ptr->previous()->par()->
1471                                              GetLayout()).bottomsep;
1472             
1473             if (tmptop > 0)
1474                layoutasc = (tmptop * DefaultHeight());
1475          }
1476          else if (row_ptr->par()->line_top){
1477             tmptop = layout.topsep;
1478             
1479             if (tmptop > 0)
1480                layoutasc = (tmptop * DefaultHeight());
1481          }
1482          
1483          prev = row_ptr->par()->DepthHook(row_ptr->par()->GetDepth()-1);
1484          if (prev)  {
1485             maxasc += int(textclasslist.Style(bview->buffer()->params.textclass,
1486                                          prev->GetLayout()).parsep * DefaultHeight());
1487          }
1488          else {
1489                 if (firstpar->Previous()
1490                     && firstpar->Previous()->GetDepth() == 0
1491                     && firstpar->Previous()->GetLayout() != firstpar->GetLayout()) {
1492                    /* avoid parsep */ 
1493                 }
1494             else if (firstpar->Previous()){
1495                maxasc += int(layout.parsep * DefaultHeight());
1496             }
1497          }
1498       }
1499    }
1500    
1501    /* is it a bottom line? */ 
1502    if (
1503 #ifndef NEW_INSETS
1504            row_ptr->par()->ParFromPos(RowLast(row_ptr) + 1) == par
1505 #else
1506            row_ptr->par() == par
1507 #endif
1508        && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par())) {     
1509           
1510           /* the paper margins */ 
1511           if (!par->next && bv_owner)
1512             maxdesc += LYX_PAPER_MARGIN;
1513         
1514           /* add the vertical spaces, that the user added */
1515           if (firstpar->added_space_bottom.kind() != VSpace::NONE)
1516                   maxdesc += int(firstpar->added_space_bottom.inPixels(bview));
1517           
1518           /* do not forget the DTP-lines! 
1519            * there height depends on the font of the nearest character */
1520           if (firstpar->line_bottom)
1521                   maxdesc += 2 * lyxfont::ascent('x', GetFont(bview->buffer(),
1522                                                               par, par->Last() - 1));
1523           
1524           /* and now the pagebreaks */
1525           if (firstpar->pagebreak_bottom)
1526             maxdesc += 3 * DefaultHeight();
1527           
1528           /* and now the layout spaces, for example before and after a section, 
1529            * or between the items of a itemize or enumerate environment */
1530           if (!firstpar->pagebreak_bottom && row_ptr->par()->Next()) {
1531              LyXParagraph * nextpar = row_ptr->par()->Next();
1532              LyXParagraph * comparepar = row_ptr->par();
1533              float usual = 0;
1534              float unusual = 0;
1535              
1536              if (comparepar->GetDepth() > nextpar->GetDepth()) {
1537                 usual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1538                 comparepar = comparepar->DepthHook(nextpar->GetDepth());
1539                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1540                     || nextpar->GetLabelWidthString() != 
1541                         comparepar->GetLabelWidthString())
1542                   unusual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1543                 
1544                 if (unusual > usual)
1545                   layoutdesc = unusual;
1546                 else
1547                   layoutdesc = usual;
1548              }
1549              else if (comparepar->GetDepth() ==  nextpar->GetDepth()) {
1550                 
1551                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1552                     || nextpar->GetLabelWidthString() != 
1553                         comparepar->GetLabelWidthString())
1554                   layoutdesc = int(textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1555              }
1556           }
1557        }
1558    
1559    /* incalculate the layout spaces */ 
1560    maxasc += int(layoutasc * 2 / (2 + firstpar->GetDepth()));
1561    maxdesc += int(layoutdesc * 2 / (2 + firstpar->GetDepth()));
1562
1563    /* calculate the new height of the text */ 
1564    height -= row_ptr->height();
1565    
1566    row_ptr->height(maxasc + maxdesc + labeladdon);
1567    row_ptr->baseline(maxasc + labeladdon);
1568    
1569    height += row_ptr->height();
1570    float x, dummy;
1571    PrepareToPrint(bview, row_ptr, x, dummy, dummy, dummy, false);
1572    row_ptr->width(int(maxwidth + x));
1573    if (inset_owner) {
1574            Row * r = firstrow;
1575            width = max(0,workWidth(bview));
1576            while(r) {
1577                    if (r->width() > width)
1578                            width = r->width();
1579                    r = r->next();
1580            }
1581    }
1582 }
1583
1584
1585 /* Appends the implicit specified paragraph behind the specified row,
1586  * start at the implicit given position */
1587 void LyXText::AppendParagraph(BufferView * bview, Row * row) const
1588 {
1589    bool not_ready = true;
1590    
1591    // The last character position of a paragraph is an invariant so we can 
1592    // safely get it here. (Asger)
1593    int const lastposition = row->par()->Last();
1594
1595    do {
1596       // Get the next breakpoint
1597       int z = NextBreakPoint(bview, row, workWidth(bview));
1598       
1599       Row * tmprow = row;
1600
1601       // Insert the new row
1602       if (z < lastposition) {
1603          ++z;
1604          InsertRow(row, row->par(), z);
1605          row = row->next();
1606
1607          row->height(0);
1608       } else
1609          not_ready = false;
1610       
1611       // Set the dimensions of the row
1612       tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1613       SetHeightOfRow(bview, tmprow);
1614
1615    } while (not_ready);
1616 }
1617
1618
1619 void LyXText::BreakAgain(BufferView * bview, Row * row) const
1620 {
1621    bool not_ready = true;
1622    
1623    do  {
1624       /* get the next breakpoint */
1625         LyXParagraph::size_type z = NextBreakPoint(bview, row, workWidth(bview));
1626       Row * tmprow = row;
1627       
1628       if (z < row->par()->Last() ) {
1629          if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1630                  // insert a new row
1631             ++z;
1632             InsertRow(row, row->par(), z);
1633             row = row->next();
1634             row->height(0);
1635          } else  {
1636             row = row->next();
1637             ++z;
1638             if (row->pos() == z)
1639                     not_ready = false;     // the rest will not change
1640             else {
1641                row->pos(z);
1642             }
1643          }
1644       } else {
1645          /* if there are some rows too much, delete them */
1646          /* only if you broke the whole paragraph! */ 
1647          Row * tmprow2 = row;
1648          while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1649             tmprow2 = tmprow2->next();
1650          }
1651          while (tmprow2 != row) {
1652             tmprow2 = tmprow2->previous();
1653             RemoveRow(tmprow2->next());
1654          }
1655          not_ready = false;
1656       }
1657        
1658       /* set the dimensions of the row */ 
1659       tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1660       SetHeightOfRow(bview, tmprow);
1661    } while (not_ready);
1662 }
1663
1664
1665 // this is just a little changed version of break again
1666 void LyXText::BreakAgainOneRow(BufferView * bview, Row * row)
1667 {
1668         // get the next breakpoint
1669         LyXParagraph::size_type z = NextBreakPoint(bview, row, workWidth(bview));
1670         Row * tmprow = row;
1671         
1672         if (z < row->par()->Last() ) {
1673                 if (!row->next()
1674                     || (row->next() && row->next()->par() != row->par())) {
1675                         /* insert a new row */ 
1676                         ++z;
1677                         InsertRow(row, row->par(), z);
1678                         row = row->next();
1679                         row->height(0);
1680                 } else  {
1681                         row= row->next();
1682                         ++z;
1683                         if (row->pos() != z)
1684                                 row->pos(z);
1685                 }
1686         } else {
1687                 // if there are some rows too much, delete them
1688                 // only if you broke the whole paragraph!
1689                 Row * tmprow2 = row;
1690                 while (tmprow2->next()
1691                        && tmprow2->next()->par() == row->par()) {
1692                         tmprow2 = tmprow2->next();
1693                 }
1694                 while (tmprow2 != row) {
1695                         tmprow2 = tmprow2->previous();
1696                         RemoveRow(tmprow2->next());
1697                 }
1698         }
1699         
1700         // set the dimensions of the row
1701         tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1702         SetHeightOfRow(bview, tmprow);
1703 }
1704
1705
1706 void LyXText::BreakParagraph(BufferView * bview, char keep_layout)
1707 {
1708    LyXLayout const & layout =
1709            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                         CursorRight(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         CursorRight(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                                 CursorLeft(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 }