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