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