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