]> git.lyx.org Git - lyx.git/blob - src/text.C
Changes to make text-inset work better (f.ex. cursor), and now we have
[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                         tmpinset->update(bview, font);
252                         return tmpinset->width(bview->painter(), 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    int pos_end = RowLast(row_ptr);
1428    int labeladdon = 0;
1429    int maxwidth = 0;
1430
1431    // Check if any insets are larger
1432    for (pos = row_ptr->pos(); pos <= pos_end; ++pos) {
1433            if (row_ptr->par()->GetChar(pos) == LyXParagraph::META_INSET) {
1434                    tmpfont = GetFont(bview->buffer(), row_ptr->par(), pos);
1435                    tmpinset = row_ptr->par()->GetInset(pos);
1436                    if (tmpinset) {
1437                            tmpinset->update(bview, tmpfont);
1438                            asc = tmpinset->ascent(bview->painter(), tmpfont);
1439                            desc = tmpinset->descent(bview->painter(), tmpfont);
1440                            maxwidth += tmpinset->width(bview->painter(), tmpfont);
1441                            maxasc = max(maxasc, asc);
1442                            maxdesc = max(maxdesc, desc);
1443                    }
1444            } else {
1445                    maxwidth += SingleWidth(bview, row_ptr->par(), pos);
1446            }
1447    }
1448
1449    // Check if any custom fonts are larger (Asger)
1450    // This is not completely correct, but we can live with the small,
1451    // cosmetic error for now.
1452    LyXFont::FONT_SIZE maxsize =
1453            row_ptr->par()->HighestFontInRange(row_ptr->pos(),
1454                                               pos_end);
1455    if (maxsize > font.size()) {
1456         font.setSize(maxsize);
1457
1458         asc = lyxfont::maxAscent(font);
1459         desc = lyxfont::maxDescent(font);
1460         if (asc > maxasc) 
1461                 maxasc = asc;
1462         if (desc > maxdesc)
1463                 maxdesc = desc;
1464    }
1465
1466 #ifndef NEW_TABULAR
1467    /* table stuff -- begin*/
1468    if (row_ptr->par()->table){
1469      // stretch the rows a bit
1470       maxasc += 1;
1471       maxdesc += 1;
1472    }
1473    /* table stuff -- end*/
1474 #endif
1475    
1476    // This is nicer with box insets:
1477    ++maxasc;
1478    ++maxdesc;
1479
1480    row_ptr->ascent_of_text(maxasc);
1481    
1482    /* is it a top line? */ 
1483    if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
1484       
1485       /* some parksips VERY EASY IMPLEMENTATION */ 
1486       if (bview->buffer()->params.paragraph_separation ==
1487           BufferParams::PARSEP_SKIP) {
1488          if (layout.isParagraph()
1489              && firstpar->GetDepth() == 0
1490              && firstpar->Previous())
1491             maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1492          else if (firstpar->Previous()
1493                   && textclasslist.Style(bview->buffer()->params.textclass,
1494                            firstpar->Previous()->GetLayout()).isParagraph()
1495                   && firstpar->Previous()->GetDepth() == 0)
1496            // is it right to use defskip here too? (AS)
1497            maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1498       }
1499       
1500       /* the paper margins */ 
1501       if (!row_ptr->par()->previous && bv_owner)
1502          maxasc += LYX_PAPER_MARGIN;
1503       
1504       /* add the vertical spaces, that the user added */
1505       if (firstpar->added_space_top.kind() != VSpace::NONE)
1506          maxasc += int(firstpar->added_space_top.inPixels(bview));
1507       
1508       /* do not forget the DTP-lines! 
1509        * there height depends on the font of the nearest character */
1510       if (firstpar->line_top)
1511          maxasc += 2 * lyxfont::ascent('x', GetFont(bview->buffer(),
1512                                                     firstpar, 0));
1513       
1514       /* and now the pagebreaks */ 
1515       if (firstpar->pagebreak_top)
1516          maxasc += 3 * DefaultHeight();
1517       
1518       /*  this is special code for the chapter, since the label of this
1519        * layout is printed in an extra row */ 
1520       if (layout.labeltype == LABEL_COUNTER_CHAPTER
1521           && bview->buffer()->params.secnumdepth >= 0) {
1522               float spacing_val = 1.0;
1523               if (!row_ptr->par()->spacing.isDefault()) {
1524                       spacing_val = row_ptr->par()->spacing.getValue();
1525               } else {
1526                       spacing_val = bview->buffer()->params.spacing.getValue();
1527               }
1528               
1529               labeladdon = int(lyxfont::maxDescent(labelfont) *
1530                                layout.spacing.getValue() *
1531                                spacing_val)
1532                       + int(lyxfont::maxAscent(labelfont) *
1533                             layout.spacing.getValue() *
1534                             spacing_val);
1535       }
1536       
1537       /* special code for the top label */ 
1538       if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1539            || layout.labeltype == LABEL_BIBLIO
1540            || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1541           && row_ptr->par()->IsFirstInSequence()
1542           && !row_ptr->par()->GetLabelstring().empty()) {
1543               float spacing_val = 1.0;
1544               if (!row_ptr->par()->spacing.isDefault()) {
1545                       spacing_val = row_ptr->par()->spacing.getValue();
1546               } else {
1547                       spacing_val = bview->buffer()->params.spacing.getValue();
1548               }
1549               
1550               labeladdon = int(
1551                       (lyxfont::maxAscent(labelfont) *
1552                        layout.spacing.getValue() *
1553                        spacing_val)
1554                       +(lyxfont::maxDescent(labelfont) *
1555                         layout.spacing.getValue() *
1556                         spacing_val)
1557                       + layout.topsep * DefaultHeight()
1558                       + layout.labelbottomsep *  DefaultHeight());
1559       }
1560    
1561       /* and now the layout spaces, for example before and after a section, 
1562        * or between the items of a itemize or enumerate environment */ 
1563       
1564       if (!firstpar->pagebreak_top) {
1565          LyXParagraph * prev = row_ptr->par()->Previous();
1566          if (prev)
1567             prev = row_ptr->par()->DepthHook(row_ptr->par()->GetDepth());
1568          if (prev && prev->GetLayout() == firstpar->GetLayout()
1569              && prev->GetDepth() == firstpar->GetDepth()
1570              && prev->GetLabelWidthString() == firstpar->GetLabelWidthString())
1571            {
1572               layoutasc = (layout.itemsep * DefaultHeight());
1573            }
1574          else if (row_ptr->previous()) {
1575             tmptop = layout.topsep;
1576             
1577             if (row_ptr->previous()->par()->GetDepth() >= row_ptr->par()->GetDepth())
1578                tmptop -= textclasslist.Style(bview->buffer()->params.textclass,
1579                                              row_ptr->previous()->par()->
1580                                              GetLayout()).bottomsep;
1581             
1582             if (tmptop > 0)
1583                layoutasc = (tmptop * DefaultHeight());
1584          }
1585          else if (row_ptr->par()->line_top){
1586             tmptop = layout.topsep;
1587             
1588             if (tmptop > 0)
1589                layoutasc = (tmptop * DefaultHeight());
1590          }
1591          
1592          prev = row_ptr->par()->DepthHook(row_ptr->par()->GetDepth()-1);
1593          if (prev)  {
1594             maxasc += int(textclasslist.Style(bview->buffer()->params.textclass,
1595                                          prev->GetLayout()).parsep * DefaultHeight());
1596          }
1597          else {
1598                 if (firstpar->Previous()
1599                     && firstpar->Previous()->GetDepth() == 0
1600                     && firstpar->Previous()->GetLayout() != firstpar->GetLayout()) {
1601                    /* avoid parsep */ 
1602                 }
1603             else if (firstpar->Previous()){
1604                maxasc += int(layout.parsep * DefaultHeight());
1605             }
1606          }
1607       }
1608    }
1609    
1610    /* is it a bottom line? */ 
1611    if (row_ptr->par()->ParFromPos(RowLast(row_ptr) + 1) == par
1612        && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par())) {     
1613           
1614           /* the paper margins */ 
1615           if (!par->next && bv_owner)
1616             maxdesc += LYX_PAPER_MARGIN;
1617         
1618           /* add the vertical spaces, that the user added */
1619           if (firstpar->added_space_bottom.kind() != VSpace::NONE)
1620                   maxdesc += int(firstpar->added_space_bottom.inPixels(bview));
1621           
1622           /* do not forget the DTP-lines! 
1623            * there height depends on the font of the nearest character */
1624           if (firstpar->line_bottom)
1625                   maxdesc += 2 * lyxfont::ascent('x', GetFont(bview->buffer(),
1626                                                               par, par->Last() - 1));
1627           
1628           /* and now the pagebreaks */
1629           if (firstpar->pagebreak_bottom)
1630             maxdesc += 3 * DefaultHeight();
1631           
1632           /* and now the layout spaces, for example before and after a section, 
1633            * or between the items of a itemize or enumerate environment */
1634           if (!firstpar->pagebreak_bottom && row_ptr->par()->Next()) {
1635              LyXParagraph * nextpar = row_ptr->par()->Next();
1636              LyXParagraph * comparepar = row_ptr->par();
1637              float usual = 0;
1638              float  unusual = 0;
1639              
1640              if (comparepar->GetDepth() > nextpar->GetDepth()) {
1641                 usual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1642                 comparepar = comparepar->DepthHook(nextpar->GetDepth());
1643                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1644                     || nextpar->GetLabelWidthString() != 
1645                         comparepar->GetLabelWidthString())
1646                   unusual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1647                 
1648                 if (unusual > usual)
1649                   layoutdesc = unusual;
1650                 else
1651                   layoutdesc = usual;
1652              }
1653              else if (comparepar->GetDepth() ==  nextpar->GetDepth()) {
1654                 
1655                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1656                     || nextpar->GetLabelWidthString() != 
1657                         comparepar->GetLabelWidthString())
1658                   layoutdesc = int(textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1659              }
1660           }
1661        }
1662    
1663    /* incalculate the layout spaces */ 
1664    maxasc += int(layoutasc * 2 / (2 + firstpar->GetDepth()));
1665    maxdesc += int(layoutdesc * 2 / (2 + firstpar->GetDepth()));
1666
1667 #ifndef NEW_TABULAR
1668    /* table stuff -- begin*/
1669    if (row_ptr->par()->table){
1670       maxasc += row_ptr->par()->table->
1671         AdditionalHeight(NumberOfCell(row_ptr->par(), row_ptr->pos()));
1672    }
1673    /* table stuff -- end*/
1674 #endif
1675    /* calculate the new height of the text */ 
1676    height -= row_ptr->height();
1677    
1678    row_ptr->height(maxasc + maxdesc + labeladdon);
1679    row_ptr->baseline(maxasc + labeladdon);
1680    
1681    height += row_ptr->height();
1682    width = maxwidth;
1683 }
1684
1685
1686 /* Appends the implicit specified paragraph behind the specified row,
1687  * start at the implicit given position */
1688 void LyXText::AppendParagraph(BufferView * bview, Row * row) const
1689 {
1690    bool not_ready = true;
1691    
1692    // The last character position of a paragraph is an invariant so we can 
1693    // safely get it here. (Asger)
1694    int lastposition = row->par()->Last();
1695
1696    do {
1697       // Get the next breakpoint
1698       int z = NextBreakPoint(bview, row, workWidth(bview));
1699       
1700       Row * tmprow = row;
1701
1702       // Insert the new row
1703       if (z < lastposition) {
1704          ++z;
1705          InsertRow(row, row->par(), z);
1706          row = row->next();
1707
1708          row->height(0);
1709       } else
1710          not_ready = false;
1711       
1712       // Set the dimensions of the row
1713       tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1714       SetHeightOfRow(bview, tmprow);
1715
1716    } while (not_ready);
1717 }
1718
1719
1720 void LyXText::BreakAgain(BufferView * bview, Row * row) const
1721 {
1722    bool not_ready = true;
1723    
1724    do  {
1725       /* get the next breakpoint */
1726         LyXParagraph::size_type z = NextBreakPoint(bview, row, workWidth(bview));
1727       Row * tmprow = row;
1728       
1729       if (z < row->par()->Last() ) {
1730          if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1731                  // insert a new row
1732             ++z;
1733             InsertRow(row, row->par(), z);
1734             row = row->next();
1735             row->height(0);
1736          } else  {
1737             row = row->next();
1738             ++z;
1739             if (row->pos() == z)
1740                     not_ready = false;     // the rest will not change
1741             else {
1742                row->pos(z);
1743             }
1744          }
1745       } else {
1746          /* if there are some rows too much, delete them */
1747          /* only if you broke the whole paragraph! */ 
1748          Row * tmprow2 = row;
1749          while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1750             tmprow2 = tmprow2->next();
1751          }
1752          while (tmprow2 != row) {
1753             tmprow2 = tmprow2->previous();
1754             RemoveRow(tmprow2->next());
1755          }
1756          not_ready = false;
1757       }
1758        
1759       /* set the dimensions of the row */ 
1760       tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1761       SetHeightOfRow(bview, tmprow);
1762    } while (not_ready);
1763 }
1764
1765
1766 // this is just a little changed version of break again
1767 void LyXText::BreakAgainOneRow(BufferView * bview, Row * row)
1768 {
1769         // get the next breakpoint
1770         LyXParagraph::size_type z = NextBreakPoint(bview, row, workWidth(bview));
1771         Row * tmprow = row;
1772         
1773         if (z < row->par()->Last() ) {
1774                 if (!row->next()
1775                     || (row->next() && row->next()->par() != row->par())) {
1776                         /* insert a new row */ 
1777                         ++z;
1778                         InsertRow(row, row->par(), z);
1779                         row = row->next();
1780                         row->height(0);
1781                 } else  {
1782                         row= row->next();
1783                         ++z;
1784                         if (row->pos() != z)
1785                                 row->pos(z);
1786                 }
1787         } else {
1788                 // if there are some rows too much, delete them
1789                 // only if you broke the whole paragraph!
1790                 Row * tmprow2 = row;
1791                 while (tmprow2->next()
1792                        && tmprow2->next()->par() == row->par()) {
1793                         tmprow2 = tmprow2->next();
1794                 }
1795                 while (tmprow2 != row) {
1796                         tmprow2 = tmprow2->previous();
1797                         RemoveRow(tmprow2->next());
1798                 }
1799         }
1800         
1801         // set the dimensions of the row
1802         tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1803         SetHeightOfRow(bview, tmprow);
1804 }
1805
1806
1807 void LyXText::BreakParagraph(BufferView * bview, char keep_layout)
1808 {
1809    LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
1810                                                   cursor.par()->GetLayout());
1811 #ifndef NEW_TABULAR   
1812    /* table stuff -- begin */
1813    if (cursor.par()->table) {
1814        // breaking of tables is only allowed at the beginning or the end */
1815        if (cursor.pos() && cursor.pos() < cursor.par()->size() &&
1816            !cursor.par()->table->ShouldBeVeryLastCell(NumberOfCell(cursor.par(), cursor.pos())))
1817                return; // no breaking of tables allowed
1818    }
1819    /* table stuff -- end */
1820 #endif
1821    // this is only allowed, if the current paragraph is not empty or caption
1822    if ((cursor.par()->Last() <= 0 && !cursor.par()->IsDummy())
1823        && 
1824        layout.labeltype!= LABEL_SENSITIVE)
1825      return;
1826
1827    SetUndo(bview->buffer(), Undo::INSERT, 
1828            cursor.par()->ParFromPos(cursor.pos())->previous, 
1829            cursor.par()->ParFromPos(cursor.pos())->next); 
1830
1831 #ifndef NEW_TABULAR
1832    /* table stuff -- begin */
1833    if (cursor.par()->table) {
1834        int cell = NumberOfCell(cursor.par(), cursor.pos());
1835        if (cursor.par()->table->ShouldBeVeryLastCell(cell))
1836            SetCursor(bview, cursor.par(), cursor.par()->size());
1837    }
1838    /* table stuff -- end */
1839 #endif
1840    // please break always behind a space
1841    if (cursor.pos() < cursor.par()->Last()
1842        && cursor.par()->IsLineSeparator(cursor.pos()))
1843      cursor.pos(cursor.pos() + 1);
1844    
1845    // break the paragraph
1846    if (keep_layout)
1847      keep_layout = 2;
1848    else 
1849      keep_layout = layout.isEnvironment();
1850    cursor.par()->BreakParagraph(bview->buffer()->params, cursor.pos(),
1851                                 keep_layout);
1852 #ifndef NEW_TABULAR
1853    /* table stuff -- begin */
1854    if (cursor.par()->table){
1855      // the table should stay with the contents
1856      if (!cursor.pos()){
1857        cursor.par()->Next()->table = cursor.par()->table;
1858        cursor.par()->table = 0;
1859      }
1860    }
1861    /* table stuff -- end */
1862 #endif
1863    // well this is the caption hack since one caption is really enough
1864    if (layout.labeltype == LABEL_SENSITIVE) {
1865      if (!cursor.pos())
1866              // set to standard-layout
1867              cursor.par()->SetLayout(bview->buffer()->params, 0);
1868      else
1869              // set to standard-layout
1870              cursor.par()->Next()->SetLayout(bview->buffer()->params, 0);
1871    }
1872    
1873    /* if the cursor is at the beginning of a row without prior newline, 
1874     * move one row up! 
1875     * This touches only the screen-update. Otherwise we would may have
1876     * an empty row on the screen */
1877    if (cursor.pos() && !cursor.row()->par()->IsNewline(cursor.row()->pos() - 1) &&
1878        cursor.row()->pos() == cursor.pos()) {
1879            CursorLeft(bview);
1880    } 
1881    
1882    status = LyXText::NEED_MORE_REFRESH;
1883    refresh_row = cursor.row();
1884    refresh_y = cursor.y() - cursor.row()->baseline();
1885    
1886    // Do not forget the special right address boxes
1887    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1888       while (refresh_row->previous() &&
1889              refresh_row->previous()->par() == refresh_row->par()) {
1890               refresh_row = refresh_row->previous();
1891               refresh_y -= refresh_row->height();
1892       }
1893    }
1894    RemoveParagraph(cursor.row());
1895    
1896    // set the dimensions of the cursor row
1897    cursor.row()->fill(Fill(bview, cursor.row(), workWidth(bview)));
1898
1899    SetHeightOfRow(bview, cursor.row());
1900    
1901    while (!cursor.par()->Next()->table && cursor.par()->Next()->Last()
1902           && cursor.par()->Next()->IsNewline(0))
1903            cursor.par()->Next()->Erase(0);
1904    
1905    InsertParagraph(bview, cursor.par()->Next(), cursor.row());
1906
1907    UpdateCounters(bview, cursor.row()->previous());
1908    
1909    /* This check is necessary. Otherwise the new empty paragraph will
1910     * be deleted automatically. And it is more friendly for the user! */ 
1911    if (cursor.pos())
1912            SetCursor(bview, cursor.par()->Next(), 0);
1913    else
1914            SetCursor(bview, cursor.par(), 0);
1915    
1916    if (cursor.row()->next())
1917            BreakAgain(bview, cursor.row()->next());
1918
1919    need_break_row = 0;
1920 }
1921
1922
1923 void LyXText::OpenFootnote(BufferView * bview)
1924 {
1925    LyXParagraph * endpar,* tmppar;
1926    Row * row;
1927    
1928    LyXParagraph * par = cursor.par()->ParFromPos(cursor.pos());
1929    
1930    /* if there is no footnote in this paragraph, just return. */ 
1931    if (!par->next
1932        || par->next->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE)
1933      return;
1934    
1935    /* ok, move the cursor right before the footnote */ 
1936    
1937    /* just a little faster than using CursorRight() */
1938    for (cursor.pos(0);
1939         cursor.par()->ParFromPos(cursor.pos()) != par;) {
1940            cursor.pos(cursor.pos() + 1);
1941    }
1942    
1943    /* now the cursor is at the beginning of the physical par */
1944    SetCursor(bview, cursor.par(),
1945              cursor.pos() + cursor.par()->ParFromPos(cursor.pos())->size());
1946    
1947    /* the cursor must be exactly before the footnote */ 
1948    par = cursor.par()->ParFromPos(cursor.pos());
1949    
1950    status = LyXText::NEED_MORE_REFRESH;
1951    refresh_row = cursor.row();
1952    refresh_y = cursor.y() - cursor.row()->baseline();
1953    
1954    tmppar = cursor.par();
1955    endpar = cursor.par()->Next();
1956    row = cursor.row();
1957    
1958    tmppar->OpenFootnote(cursor.pos());
1959    RemoveParagraph(row);
1960    /* set the dimensions of the cursor row */
1961    row->fill(Fill(bview, row, workWidth(bview)));
1962    SetHeightOfRow(bview, row);
1963    // CHECK See comment on top of text.C
1964    tmppar = tmppar->Next();
1965    
1966    while (tmppar != endpar) {
1967       if (tmppar) {
1968          InsertParagraph(bview, tmppar, row);
1969          while (row->next() && row->next()->par() == tmppar)
1970            row = row->next();
1971          tmppar = tmppar->Next();
1972       }
1973    }
1974    SetCursor(bview, par->next, 0);
1975    sel_cursor = cursor;
1976 }
1977    
1978
1979 /* table stuff -- begin*/
1980
1981 void LyXText::TableFeatures(BufferView * bview, int feature, string const & val) const
1982 {
1983         if (!cursor.par()->table)
1984                 return; /* this should never happen */
1985   
1986         int actCell = NumberOfCell(cursor.par(), cursor.pos());
1987         SetUndo(bview->buffer(), Undo::FINISH, 
1988                 cursor.par()->ParFromPos(cursor.pos())->previous, 
1989                 cursor.par()->ParFromPos(cursor.pos())->next); 
1990         
1991         switch (feature){
1992         case LyXTable::SET_PWIDTH:
1993                 cursor.par()->table->SetPWidth(actCell, val);
1994                 break;
1995         case LyXTable::SET_SPECIAL_COLUMN:
1996         case LyXTable::SET_SPECIAL_MULTI:
1997                 cursor.par()->table->SetAlignSpecial(actCell, val, feature);
1998                 break;
1999         default:
2000                 break;
2001         }
2002         RedoParagraph(bview);
2003 }
2004
2005
2006 void LyXText::TableFeatures(BufferView * bview, int feature) const
2007 {
2008         int setLines = 0;
2009         int setAlign = LYX_ALIGN_LEFT;
2010         int lineSet;
2011         bool what;
2012     
2013     if (!cursor.par()->table)
2014         return; /* this should never happen */
2015   
2016     int actCell = NumberOfCell(cursor.par(), cursor.pos());
2017     SetUndo(bview->buffer(), Undo::FINISH, 
2018             cursor.par()->ParFromPos(cursor.pos())->previous, 
2019             cursor.par()->ParFromPos(cursor.pos())->next); 
2020
2021     switch (feature){
2022       case LyXTable::ALIGN_LEFT:
2023           setAlign= LYX_ALIGN_LEFT;
2024           break;
2025       case LyXTable::ALIGN_RIGHT:
2026           setAlign= LYX_ALIGN_RIGHT;
2027           break;
2028       case LyXTable::ALIGN_CENTER:
2029           setAlign= LYX_ALIGN_CENTER;
2030           break;
2031       default:
2032           break;
2033     }
2034     switch (feature){
2035       case LyXTable::APPEND_ROW: {
2036               LyXParagraph::size_type pos = cursor.pos();
2037
2038               /* move to the next row */
2039           int cell_org = actCell;
2040           int cell = cell_org;
2041
2042           // if there is a ContRow following this row I have to add
2043           // the row after the ContRow's
2044           if ((pos < cursor.par()->Last()) &&
2045               cursor.par()->table->RowHasContRow(cell_org)) {
2046               while((pos < cursor.par()->Last()) &&
2047                     !cursor.par()->table->IsContRow(cell)) {
2048                   while (pos < cursor.par()->Last() &&
2049                          !cursor.par()->IsNewline(pos))
2050                       ++pos;
2051                   if (pos < cursor.par()->Last())
2052                       ++pos;
2053                   ++cell;
2054               }
2055               while((pos < cursor.par()->Last()) &&
2056                     cursor.par()->table->IsContRow(cell)) {
2057                   while (pos < cursor.par()->Last() &&
2058                          !cursor.par()->IsNewline(pos))
2059                       ++pos;
2060                   if (pos < cursor.par()->Last())
2061                       ++pos;
2062                   ++cell;
2063               }
2064               cell_org = --cell;
2065               if (pos < cursor.par()->Last())
2066                   --pos;
2067           }
2068           while (pos < cursor.par()->Last() && 
2069                  (cell == cell_org || !cursor.par()->table->IsFirstCell(cell))){
2070               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2071                   ++pos;
2072               if (pos < cursor.par()->Last())
2073                   ++pos;
2074               ++cell;
2075           }
2076                 
2077           /* insert the new cells */ 
2078           int number = cursor.par()->table->NumberOfCellsInRow(cell_org);
2079           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2080           LyXFont font(LyXFont::ALL_INHERIT,lang);
2081           for (int i = 0; i < number; ++i) {
2082               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2083               cursor.par()->SetFont(pos, font);
2084           }
2085                 
2086           /* append the row into the table */
2087           cursor.par()->table->AppendRow(cell_org);
2088           RedoParagraph(bview);
2089           return;
2090       }
2091       case LyXTable::APPEND_CONT_ROW: {
2092               LyXParagraph::size_type pos = cursor.pos();
2093           /* move to the next row */
2094           int cell_org = actCell;
2095           int cell = cell_org;
2096
2097           // if there is already a controw but not for this cell
2098           // the AppendContRow sets only the right values but does
2099           // not actually add a row
2100           if (cursor.par()->table->RowHasContRow(cell_org) &&
2101               (cursor.par()->table->CellHasContRow(cell_org)<0)) {
2102               cursor.par()->table->AppendContRow(cell_org);
2103               RedoParagraph(bview);
2104               return;
2105           }
2106           while (pos < cursor.par()->Last() && 
2107                  (cell == cell_org
2108                   || !cursor.par()->table->IsFirstCell(cell))){
2109               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2110                   ++pos;
2111               if (pos < cursor.par()->Last())
2112                   ++pos;
2113               ++cell;
2114           }
2115                 
2116           /* insert the new cells */ 
2117           int number = cursor.par()->table->NumberOfCellsInRow(cell_org);
2118           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2119           LyXFont font(LyXFont::ALL_INHERIT,lang);
2120           for (int i = 0; i < number; ++i) {
2121               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2122               cursor.par()->SetFont(pos, font);
2123           }
2124
2125           /* append the row into the table */
2126           cursor.par()->table->AppendContRow(cell_org);
2127           RedoParagraph(bview);
2128           return;
2129       }
2130       case LyXTable::APPEND_COLUMN: {
2131               LyXParagraph::size_type pos = 0;
2132           int cell_org = actCell;
2133           int cell = 0;
2134           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2135           LyXFont font(LyXFont::ALL_INHERIT,lang);
2136           do{
2137               if (pos && (cursor.par()->IsNewline(pos-1))){
2138                   if (cursor.par()->table->AppendCellAfterCell(cell_org, cell)) {
2139                       cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2140                       cursor.par()->SetFont(pos, font);
2141                       if (pos <= cursor.pos())
2142                           cursor.pos(cursor.pos() + 1);
2143                       ++pos;
2144                   }
2145                   ++cell;
2146               }
2147               ++pos;
2148           } while (pos <= cursor.par()->Last());
2149           /* remember that the very last cell doesn't end with a newline.
2150              This saves one byte memory per table ;-) */
2151           if (cursor.par()->table->AppendCellAfterCell(cell_org, cell)) {
2152                   LyXParagraph::size_type last = cursor.par()->Last();
2153                   cursor.par()->InsertChar(last, LyXParagraph::META_NEWLINE);
2154                   cursor.par()->SetFont(last, font);
2155           }
2156                 
2157           /* append the column into the table */ 
2158           cursor.par()->table->AppendColumn(cell_org);
2159                 
2160           RedoParagraph(bview);
2161           return;
2162       }
2163       case LyXTable::DELETE_ROW:
2164           if (bview->the_locking_inset)
2165               bview->unlockInset(bview->the_locking_inset);
2166           RemoveTableRow(cursor);
2167           RedoParagraph(bview);
2168           return;
2169         
2170       case LyXTable::DELETE_COLUMN: {
2171               LyXParagraph::size_type pos = 0;
2172           int cell_org = actCell;
2173           int cell = 0;
2174           if (bview->the_locking_inset)
2175               bview->unlockInset(bview->the_locking_inset);
2176           do {
2177               if (!pos || (cursor.par()->IsNewline(pos-1))){
2178                   if (cursor.par()->table->DeleteCellIfColumnIsDeleted(cell, cell_org)){
2179                       // delete one cell
2180                       while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2181                           cursor.par()->Erase(pos);
2182                       if (pos < cursor.par()->Last())
2183                           cursor.par()->Erase(pos);
2184                       else 
2185                           cursor.par()->Erase(pos - 1); // the missing newline at the end of a table
2186                       --pos; // because of pos++ below
2187                   }   
2188                   ++cell;
2189               }
2190               ++pos;
2191           } while (pos <= cursor.par()->Last());
2192                 
2193           /* delete the column from the table */ 
2194           cursor.par()->table->DeleteColumn(cell_org);
2195                 
2196           /* set the cursor to the beginning of the table, where else? */ 
2197           cursor.pos(0);
2198           RedoParagraph(bview);
2199           return;
2200       }
2201       case LyXTable::TOGGLE_LINE_TOP:
2202           lineSet = !cursor.par()->table->TopLine(actCell);
2203           if (!selection){
2204               cursor.par()->table->SetTopLine(actCell, lineSet);
2205           } else {
2206                   LyXParagraph::size_type i;
2207                   int n = -1, m = -2;
2208               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2209                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2210                       cursor.par()->table->SetTopLine(n, lineSet);
2211                       m = n;
2212                   }
2213               }
2214           }
2215           RedoParagraph(bview);
2216           return;
2217     
2218       case LyXTable::TOGGLE_LINE_BOTTOM:
2219           lineSet = !cursor.par()->table->BottomLine(actCell);
2220           if (!selection){
2221               cursor.par()->table->SetBottomLine(actCell, lineSet);
2222           } else {
2223                   LyXParagraph::size_type i;
2224                   int n = -1, m = -2;
2225               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2226                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2227                       cursor.par()->table->SetBottomLine(n, lineSet);
2228                       m = n;
2229                   }
2230               }
2231           }
2232           RedoParagraph(bview);
2233           return;
2234                 
2235       case LyXTable::TOGGLE_LINE_LEFT:
2236           lineSet = !cursor.par()->table->LeftLine(actCell);
2237           if (!selection){
2238               cursor.par()->table->SetLeftLine(actCell, lineSet);
2239           } else {
2240                   LyXParagraph::size_type i;
2241                   int n = -1, m = -2;
2242               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2243                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2244                       cursor.par()->table->SetLeftLine(n, lineSet);
2245                       m = n;
2246                   }
2247               }
2248           }
2249           RedoParagraph(bview);
2250           return;
2251
2252       case LyXTable::TOGGLE_LINE_RIGHT:
2253           lineSet = !cursor.par()->table->RightLine(actCell);
2254           if (!selection){
2255               cursor.par()->table->SetRightLine(actCell, lineSet);
2256           } else {
2257                   int n = -1, m = -2;
2258                   LyXParagraph::size_type i = sel_start_cursor.pos();
2259               for (; i <= sel_end_cursor.pos(); ++i) {
2260                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2261                       cursor.par()->table->SetRightLine(n, lineSet);
2262                       m = n;
2263                   }
2264               }
2265           }
2266           RedoParagraph(bview);
2267           return;
2268     
2269       case LyXTable::ALIGN_LEFT:
2270       case LyXTable::ALIGN_RIGHT:
2271       case LyXTable::ALIGN_CENTER:
2272           if (!selection){
2273               cursor.par()->table->SetAlignment(actCell, setAlign);
2274           } else {
2275               int n = -1, m = -2;
2276               LyXParagraph::size_type i = sel_start_cursor.pos();
2277               for (; i <= sel_end_cursor.pos(); ++i) {
2278                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2279                       cursor.par()->table->SetAlignment(n, setAlign);
2280                       m = n;
2281                   }
2282               }
2283           }
2284           RedoParagraph(bview);
2285           return;
2286                 
2287       case LyXTable::DELETE_TABLE:
2288           SetCursorIntern(bview, cursor.par(), 0);
2289           delete cursor.par()->table;
2290           cursor.par()->table = 0;
2291           // temporary: Should put table in simple_cut_buffer (with before and after
2292           // dummy-paragraph !! 
2293           // not necessar anymore with UNDO :)
2294           for (LyXParagraph::size_type i = 
2295                        cursor.par()->size() - 1; i >= 0; --i)
2296               cursor.par()->Erase(i);
2297           RedoParagraph(bview);
2298           return;
2299                 
2300       case LyXTable::MULTICOLUMN: {
2301           int number = 0;
2302           // check wether we are completly in a multicol
2303           int multicol = cursor.par()->table->IsMultiColumn(actCell);
2304           if (multicol && selection && sel_start_cursor.row() == sel_end_cursor.row()) {
2305               multicol = NumberOfCell(sel_start_cursor.par(), sel_start_cursor.pos())
2306                   == NumberOfCell(sel_end_cursor.par(), sel_end_cursor.pos());
2307           }
2308
2309           if (multicol){
2310               int newlines = cursor.par()->table->UnsetMultiColumn(actCell);
2311               LyXParagraph::size_type pos = cursor.pos();
2312               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2313                   ++pos;
2314               for (; newlines; --newlines)
2315                   cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2316               RedoParagraph(bview);
2317               return;
2318           }
2319           else {
2320               // selection must be in one row (or no selection)
2321               if (!selection){
2322                   cursor.par()->table->SetMultiColumn(NumberOfCell(cursor.par(),
2323                                                                  cursor.pos()),
2324                                                     1);
2325                   RedoParagraph(bview);
2326                   return;
2327               }
2328               else {
2329                   if (sel_start_cursor.row() == sel_end_cursor.row()){
2330                       LyXParagraph::size_type i;
2331                       number = 1;
2332                       for (i = sel_start_cursor.pos();
2333                            i < sel_end_cursor.pos(); ++i){
2334                           if (sel_start_cursor.par()->IsNewline(i)){
2335                               sel_start_cursor.par()->Erase(i);
2336                               // check for double-blanks
2337                               if ((i && !sel_start_cursor.par()->IsLineSeparator(i-1))
2338                                   &&
2339                                   (i < sel_start_cursor.par()->Last() 
2340                                    && !sel_start_cursor.par()->IsLineSeparator(i)))
2341                                   sel_start_cursor.par()->InsertChar(i, ' ');
2342                               else {
2343                                   sel_end_cursor.pos(sel_end_cursor.pos() - 1);
2344                                   --i;
2345                               }
2346                               ++number;
2347                           }
2348                       }
2349                       cursor.par()->table->
2350                           SetMultiColumn(NumberOfCell(sel_start_cursor.par(),
2351                                                       sel_start_cursor.pos()),
2352                                          number);
2353                       cursor.pos(sel_start_cursor.pos());
2354                       RedoParagraph(bview);
2355                       return;
2356                   }
2357                   else {
2358                       WriteAlert(_("Impossible Operation!"), 
2359                                  _("Multicolumns can only be horizontally."), 
2360                                  _("Sorry."));
2361                   }
2362               }
2363           }
2364           break;
2365       }
2366       case LyXTable::SET_ALL_LINES:
2367           setLines = 1;
2368       case LyXTable::UNSET_ALL_LINES:
2369           if (!selection){
2370               cursor.par()->table->SetAllLines(NumberOfCell(cursor.par(),
2371                                                           cursor.pos()),
2372                                              setLines);
2373           } else {
2374                   LyXParagraph::size_type i;
2375                   int n = -1, m = -2;
2376               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2377                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2378                       cursor.par()->table->SetAllLines(n, setLines);
2379                       m = n;
2380                   }
2381               }
2382           }
2383           RedoParagraph(bview);
2384           return;
2385       case LyXTable::SET_LONGTABLE:
2386           cursor.par()->table->SetLongTable(true);
2387           return;
2388       case LyXTable::UNSET_LONGTABLE:
2389           cursor.par()->table->SetLongTable(false);
2390           return;
2391       case LyXTable::SET_ROTATE_TABLE:
2392           cursor.par()->table->SetRotateTable(true);
2393           return;
2394       case LyXTable::UNSET_ROTATE_TABLE:
2395           cursor.par()->table->SetRotateTable(false);
2396           return;
2397       case LyXTable::SET_ROTATE_CELL:
2398           if (!selection){
2399               cursor.par()->table->SetRotateCell(actCell, true);
2400           } else {
2401                   LyXParagraph::size_type i;
2402                   int n = -1, m = -2;
2403               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2404                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2405                       cursor.par()->table->SetRotateCell(n, true);
2406                       m = n;
2407                   }
2408               }
2409           }
2410           return;
2411       case LyXTable::UNSET_ROTATE_CELL:
2412           if (!selection){
2413               cursor.par()->table->SetRotateCell(actCell, false);
2414           } else {
2415                   int n = -1, m = -2;
2416                   LyXParagraph::size_type i = sel_start_cursor.pos();
2417               for (; i <= sel_end_cursor.pos(); ++i) {
2418                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2419                       cursor.par()->table->SetRotateCell(n, false);
2420                       m = n;
2421                   }
2422               }
2423           }
2424           return;
2425       case LyXTable::SET_LINEBREAKS:
2426           what = !cursor.par()->table->Linebreaks(cursor.par()->table->FirstVirtualCell(actCell));
2427           if (!selection){
2428               cursor.par()->table->SetLinebreaks(actCell, what);
2429           } else {
2430                   LyXParagraph::size_type i;
2431                   int n = -1, m = -2;
2432               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2433                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2434                       cursor.par()->table->SetLinebreaks(n, what);
2435                       m = n;
2436                   }
2437               }
2438           }
2439           return;
2440       case LyXTable::SET_LTFIRSTHEAD:
2441           cursor.par()->table->SetLTHead(actCell, true);
2442           return;
2443       case LyXTable::SET_LTHEAD:
2444           cursor.par()->table->SetLTHead(actCell, false);
2445           return;
2446       case LyXTable::SET_LTFOOT:
2447           cursor.par()->table->SetLTFoot(actCell, false);
2448           return;
2449       case LyXTable::SET_LTLASTFOOT:
2450           cursor.par()->table->SetLTFoot(actCell, true);
2451           return;
2452       case LyXTable::SET_LTNEWPAGE:
2453           what = !cursor.par()->table->LTNewPage(actCell);
2454           cursor.par()->table->SetLTNewPage(actCell, what);
2455           return;
2456     }
2457 }
2458         
2459
2460 void LyXText::InsertCharInTable(BufferView * bview, char c)
2461 {
2462         Row * row = 0;
2463         Row * tmprow = 0;
2464         long y;
2465         bool jumped_over_space;
2466         
2467         /* first check, if there will be two blanks together or a blank at 
2468          * the beginning of a paragraph. 
2469          * I decided to handle blanks like normal characters, the main 
2470          * difference are the special checks when calculating the row.fill
2471          * (blank does not count at the end of a row) and the check here */ 
2472         
2473         LyXFont realtmpfont = real_current_font;
2474         LyXFont rawtmpfont = current_font; /* store the current font.
2475                                             * This is because of the use
2476                                             * of cursor movements. The moving
2477                                             * cursor would refresh the 
2478                                             * current font */
2479
2480         // Get the font that is used to calculate the baselineskip
2481         LyXParagraph::size_type const lastpos = 
2482                 cursor.par()->Last();
2483         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2484                                                            lastpos - 1);
2485
2486         jumped_over_space = false;
2487         if (IsLineSeparatorChar(c)) {
2488                 if ((cursor.pos() > 0 && 
2489                      cursor.par()->IsLineSeparator(cursor.pos() - 1))
2490                     || (cursor.pos() > 0 && cursor.par()->IsNewline(cursor.pos() - 1))
2491                     || (cursor.pos() == 0 &&
2492                         !(cursor.par()->Previous()
2493                           && cursor.par()->Previous()->footnoteflag
2494                           == LyXParagraph::OPEN_FOOTNOTE)))
2495                         return;
2496         } else if (IsNewlineChar(c)) {
2497             if (!IsEmptyTableCell()) {
2498                 TableFeatures(bview, LyXTable::APPEND_CONT_ROW);
2499                 CursorDown(bview);
2500             }
2501           return;
2502         }
2503    
2504         row = cursor.row();
2505         y = cursor.y() - row->baseline();
2506         if (c != LyXParagraph::META_INSET)      /* in this case LyXText::InsertInset 
2507                                          * already inserted the character */
2508                 cursor.par()->InsertChar(cursor.pos(), c);
2509         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
2510
2511         if (!jumped_over_space) {
2512                 /* refresh the positions */
2513                 tmprow = row;
2514                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2515                         tmprow = tmprow->next();
2516                         tmprow->pos(tmprow->pos() + 1);
2517                 }
2518         }
2519
2520         cursor.pos(cursor.pos() + 1);
2521
2522         CheckParagraphInTable(bview, cursor.par(), cursor.pos());
2523         
2524         current_font = rawtmpfont;
2525         real_current_font = realtmpfont;
2526         
2527         /* check, whether the last character's font has changed. */
2528         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2529             && rawparfont != rawtmpfont)
2530                 RedoHeightOfParagraph(bview, cursor);
2531 }
2532
2533
2534 void LyXText::CheckParagraphInTable(BufferView * bview, LyXParagraph * par,
2535                                     LyXParagraph::size_type pos)
2536 {
2537         
2538         if (par->GetChar(pos) == LyXParagraph::META_INSET &&
2539             par->GetInset(pos) && par->GetInset(pos)->display()){
2540           par->GetInset(pos)->display(false);
2541         }
2542
2543         long y;
2544         Row * row = GetRow(par, pos, y);
2545         
2546         int tmpheight = row->height();
2547         SetHeightOfRow(bview, row);
2548
2549         LyXParagraph::size_type tmp_pos = pos;
2550         /* update the table information */
2551         while (tmp_pos && !par->IsNewline(tmp_pos - 1))
2552                 --tmp_pos;
2553         if (par->table->SetWidthOfCell(NumberOfCell(par, pos),
2554                                        WidthOfCell(bview, par, tmp_pos))) {
2555                 LyXCursor tmpcursor = cursor;
2556                 SetCursorIntern(bview, par, pos, false);
2557                 /* make a complete redraw */
2558                 RedoDrawingOfParagraph(bview, cursor);
2559                 cursor = tmpcursor;
2560         }
2561         else {
2562                 /* redraw only the row */
2563                 LyXCursor tmpcursor = cursor;
2564                 SetCursorIntern(bview, par, pos);
2565                 //CHECK See comment on top of text.C
2566                 refresh_y = y;
2567                 refresh_x = cursor.x();
2568                 refresh_row = row;
2569                 refresh_pos = cursor.pos();
2570                 cursor = tmpcursor;
2571                 
2572                 if (tmpheight == row->height())
2573                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2574                 else
2575                         status = LyXText::NEED_MORE_REFRESH;
2576         }
2577         SetCursorIntern(bview, cursor.par(), cursor.pos(), false,
2578                         cursor.boundary());
2579 }
2580
2581
2582 void LyXText::BackspaceInTable(BufferView * bview)
2583 {
2584         Row * tmprow, * row;
2585         long y;
2586         
2587         LyXFont rawtmpfont = current_font;
2588         LyXFont realtmpfont = real_current_font;
2589
2590         // Get the font that is used to calculate the baselineskip
2591         int const lastpos = cursor.par()->Last();
2592         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2593                                                            lastpos - 1);
2594         
2595         if (cursor.pos() == 0) {
2596                 /* no pasting of table paragraphs */
2597                 
2598                 CursorLeft(bview);
2599         } else {
2600                 /* this is the code for a normal backspace, not pasting
2601                  * any paragraphs */ 
2602                 SetUndo(bview->buffer(), Undo::DELETE, 
2603                         cursor.par()->ParFromPos(cursor.pos())->previous, 
2604                         cursor.par()->ParFromPos(cursor.pos())->next); 
2605           
2606                 CursorLeftIntern(bview);
2607                 
2608                 /* some insets are undeletable here */
2609                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
2610                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
2611                                 return;
2612                 }
2613                 
2614                 row = cursor.row();
2615                 y = cursor.y() - row->baseline();
2616                 
2617                 /* some special code when deleting a newline. */
2618                 if (cursor.par()->IsNewline(cursor.pos())) {
2619                         /* nothing :-) */
2620                         return;
2621                 } else {
2622                         cursor.par()->Erase(cursor.pos());
2623                         
2624                         /* refresh the positions */
2625                         tmprow = row;
2626                         while (tmprow->next()
2627                                && tmprow->next()->par() == row->par()) {
2628                                 tmprow = tmprow->next();
2629                                 tmprow->pos(tmprow->pos() - 1);
2630                         }
2631                 }
2632       
2633                 CheckParagraphInTable(bview, cursor.par(), cursor.pos());
2634       
2635                 /* check, wether the last characters font has changed. */ 
2636                 if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2637                     && rawparfont != rawtmpfont)
2638                         RedoHeightOfParagraph(bview, cursor);
2639
2640                 /* restore the current font 
2641                  * That is what a user expects! */
2642                 current_font = rawtmpfont;
2643                 real_current_font = realtmpfont;
2644         }
2645         SetCursorIntern(bview, cursor.par(), cursor.pos(), true,
2646                         cursor.boundary());
2647         if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos()) != cursor.boundary())
2648                 SetCursor(bview, cursor.par(), cursor.pos(), false, !cursor.boundary());
2649 }
2650
2651 /* table stuff -- end*/
2652
2653
2654 // Just a macro to make some thing easier. 
2655 void LyXText::RedoParagraph(BufferView * bview) const
2656 {
2657         ClearSelection();
2658         RedoParagraphs(bview, cursor, cursor.par()->Next());
2659         SetCursorIntern(bview, cursor.par(), cursor.pos());
2660 }
2661
2662
2663 /* insert a character, moves all the following breaks in the 
2664  * same Paragraph one to the right and make a rebreak */
2665 void LyXText::InsertChar(BufferView * bview, char c)
2666 {
2667         SetUndo(bview->buffer(), Undo::INSERT, 
2668                 cursor.par()->ParFromPos(cursor.pos())->previous, 
2669                 cursor.par()->ParFromPos(cursor.pos())->next);
2670
2671         // When the free-spacing option is set for the current layout,
2672         // disable the double-space checking
2673
2674         bool freeSpacing = 
2675                 textclasslist.Style(bview->buffer()->params.textclass,
2676                                cursor.row()->par()->GetLayout()).free_spacing;
2677
2678 #ifndef NEW_TABULAR
2679         /* table stuff -- begin*/
2680         if (cursor.par()->table) {
2681                 InsertCharInTable(bview, c);
2682                 charInserted();
2683                 return;
2684         }
2685         /* table stuff -- end*/
2686 #endif
2687         /* First check, if there will be two blanks together or a blank at 
2688           the beginning of a paragraph. 
2689           I decided to handle blanks like normal characters, the main 
2690           difference are the special checks when calculating the row.fill
2691           (blank does not count at the end of a row) and the check here */ 
2692
2693         // The bug is triggered when we type in a description environment:
2694         // The current_font is not changed when we go from label to main text
2695         // and it should (along with realtmpfont) when we type the space.
2696         // CHECK There is a bug here! (Asger)
2697         
2698         LyXFont realtmpfont = real_current_font;
2699         LyXFont rawtmpfont = current_font;  /* store the current font.
2700                                      * This is because of the use
2701                                      * of cursor movements. The moving
2702                                      * cursor would refresh the 
2703                                      * current font */
2704
2705         // Get the font that is used to calculate the baselineskip
2706         LyXParagraph::size_type lastpos = cursor.par()->Last();
2707         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2708                                                            lastpos - 1);
2709
2710         bool jumped_over_space = false;
2711    
2712         if (!freeSpacing && IsLineSeparatorChar(c)) {
2713                 if ((cursor.pos() > 0 
2714                      && cursor.par()->IsLineSeparator(cursor.pos() - 1))
2715                     || (cursor.pos() > 0
2716                         && cursor.par()->IsNewline(cursor.pos() - 1))
2717                     || (cursor.pos() == 0
2718                         && !(cursor.par()->Previous()
2719                              && cursor.par()->Previous()->footnoteflag
2720                              == LyXParagraph::OPEN_FOOTNOTE))) {
2721                         if (cursor.pos() == 0 )
2722                                 bview->owner()->getMiniBuffer()->Set(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
2723                         else
2724                                 bview->owner()->getMiniBuffer()->Set(_("You cannot type two spaces this way.  Please read the Tutorial."));
2725                         charInserted();
2726                         return;
2727                 }
2728         } else if (IsNewlineChar(c)) {
2729                 if (cursor.par()->FirstPhysicalPar() == cursor.par()
2730                     && cursor.pos() <= BeginningOfMainBody(bview->buffer(), cursor.par())) {
2731                         charInserted();
2732                         return;
2733                 }
2734                 /* No newline at first position 
2735                  * of a paragraph or behind labels. 
2736                  * TeX does not allow that. */
2737                 
2738                 if (cursor.pos() < cursor.par()->Last() &&
2739                     cursor.par()->IsLineSeparator(cursor.pos()))
2740                         // newline always after a blank!
2741                         CursorRightIntern(bview);
2742                 cursor.row()->fill(-1);        // to force a new break
2743         }
2744    
2745         // the display inset stuff
2746         if (cursor.row()->par()->GetChar(cursor.row()->pos()) == LyXParagraph::META_INSET
2747             && cursor.row()->par()->GetInset(cursor.row()->pos())
2748             && cursor.row()->par()->GetInset(cursor.row()->pos())->display())
2749                 cursor.row()->fill(-1); // to force a new break  
2750
2751         // get the cursor row fist
2752         Row * row = cursor.row();
2753         long y = cursor.y() - row->baseline();
2754         if (c != LyXParagraph::META_INSET) /* Here case LyXText::InsertInset 
2755                                             * already insertet the character */
2756                 cursor.par()->InsertChar(cursor.pos(), c);
2757         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
2758
2759         if (!jumped_over_space) {
2760                 // refresh the positions
2761                 Row * tmprow = row;
2762                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2763                         tmprow = tmprow->next();
2764                         tmprow->pos(tmprow->pos() + 1);
2765                 }
2766         }
2767    
2768         // Is there a break one row above
2769         if ((cursor.par()->IsLineSeparator(cursor.pos())
2770              || cursor.par()->IsNewline(cursor.pos())
2771              || cursor.row()->fill() == -1)
2772             && row->previous() && row->previous()->par() == row->par()) {
2773                 LyXParagraph::size_type z = NextBreakPoint(bview,
2774                                                            row->previous(),
2775                                                            workWidth(bview));
2776                 if ( z >= row->pos()) {
2777                         row->pos(z + 1);
2778                         
2779                         // set the dimensions of the row above
2780                         row->previous()->fill(Fill(bview,
2781                                                    row->previous(),
2782                                                    workWidth(bview)));
2783
2784                         SetHeightOfRow(bview, row->previous());
2785              
2786                         y -= row->previous()->height();
2787                         refresh_y = y;
2788                         refresh_row = row->previous();
2789                         status = LyXText::NEED_MORE_REFRESH;
2790              
2791                         BreakAgainOneRow(bview, row);
2792
2793                         current_font = rawtmpfont;
2794                         real_current_font = realtmpfont;
2795                         SetCursor(bview, cursor.par(), cursor.pos() + 1,
2796                                   false, cursor.boundary());
2797                         // cursor MUST be in row now.
2798              
2799                         if (row->next() && row->next()->par() == row->par())
2800                                 need_break_row = row->next();
2801                         else
2802                                 need_break_row = 0;
2803              
2804                         // check, wether the last characters font has changed. 
2805                         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2806                             && rawparfont != rawtmpfont)
2807                                 RedoHeightOfParagraph(bview, cursor);
2808                         
2809                         charInserted();
2810                         return;
2811                 }
2812         }
2813    
2814         // recalculate the fill of the row
2815         if (row->fill() >= 0)  /* needed because a newline
2816                               * will set fill to -1. Otherwise
2817                               * we would not get a rebreak! */
2818                 row->fill(Fill(bview, row, workWidth(bview)));
2819         if (row->fill() < 0 ) {
2820                 refresh_y = y;
2821                 refresh_row = row; 
2822                 refresh_x = cursor.x();
2823                 refresh_pos = cursor.pos();
2824                 status = LyXText::NEED_MORE_REFRESH;
2825                 BreakAgainOneRow(bview, row); 
2826                 // will the cursor be in another row now?
2827                 if (RowLast(row) <= cursor.pos() + 1 && row->next()) {
2828                         if (row->next() && row->next()->par() == row->par())
2829                                 // this should always be true
2830                                 row = row->next();
2831                         BreakAgainOneRow(bview, row);
2832                 }
2833                 current_font = rawtmpfont;
2834                 real_current_font = realtmpfont;
2835
2836                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
2837                           cursor.boundary());
2838                 if (row->next() && row->next()->par() == row->par())
2839                         need_break_row = row->next();
2840                 else
2841                         need_break_row = 0;             
2842         } else {
2843                 refresh_y = y;
2844                 refresh_x = cursor.x();
2845                 refresh_row = row;
2846                 refresh_pos = cursor.pos();
2847                 
2848                 int tmpheight = row->height();
2849                 SetHeightOfRow(bview, row);
2850                 if (tmpheight == row->height())
2851                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2852                 else
2853                         status = LyXText::NEED_MORE_REFRESH;
2854             
2855                 current_font = rawtmpfont;
2856                 real_current_font = realtmpfont;
2857                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
2858                           cursor.boundary());
2859         }
2860
2861         // check, wether the last characters font has changed.
2862         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2863             && rawparfont != rawtmpfont) {
2864                 RedoHeightOfParagraph(bview, cursor);
2865         } else {
2866                 // now the special right address boxes
2867                 if (textclasslist.Style(bview->buffer()->params.textclass,
2868                                    cursor.par()->GetLayout()).margintype
2869                     == MARGIN_RIGHT_ADDRESS_BOX) {
2870                         RedoDrawingOfParagraph(bview, cursor); 
2871                 }
2872         }
2873
2874         charInserted();
2875 }
2876    
2877
2878 void LyXText::charInserted()
2879 {
2880         // Here we could call FinishUndo for every 20 characters inserted.
2881         // This is from my experience how emacs does it.
2882         static unsigned int counter = 0;
2883         if (counter < 20) {
2884                 ++counter;
2885         } else {
2886                 FinishUndo();
2887                 counter = 0;
2888         }
2889 }
2890
2891 void LyXText::PrepareToPrint(BufferView * bview,
2892                              Row * row, float & x,
2893                              float & fill_separator, 
2894                              float & fill_hfill,
2895                              float & fill_label_hfill,
2896                              bool bidi) const
2897 {
2898         float nlh, ns;
2899         
2900         float w = row->fill();
2901         fill_hfill = 0;
2902         fill_label_hfill = 0;
2903         fill_separator = 0;
2904         fill_label_hfill = 0;
2905
2906         bool is_rtl = row->par()->isRightToLeftPar(bview->buffer()->params);
2907
2908         if (is_rtl) {
2909                 x = RightMargin(bview->buffer(), row);
2910                 if (row->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
2911                         LyXFont font(LyXFont::ALL_SANE);
2912                         font.setSize(LyXFont::SIZE_SMALL);
2913                         x += lyxfont::width("Mwide-figM", font);
2914                 }
2915         } else if (workWidth(bview) > 0)
2916                 x = LeftMargin(bview, row);
2917         else
2918                 x = 0;
2919         
2920         // is there a manual margin with a manual label
2921         if (textclasslist.Style(bview->buffer()->params.textclass,
2922                            row->par()->GetLayout()).margintype == MARGIN_MANUAL
2923             && textclasslist.Style(bview->buffer()->params.textclass,
2924                               row->par()->GetLayout()).labeltype == LABEL_MANUAL) {
2925                
2926                 /* one more since labels are left aligned */ 
2927                 nlh = NumberOfLabelHfills(bview->buffer(), row) + 1;
2928                 if (nlh && !row->par()->GetLabelWidthString().empty()) {
2929                         fill_label_hfill = LabelFill(bview, row) / nlh;
2930                 }
2931         }
2932                 
2933         // are there any hfills in the row?
2934         float nh = NumberOfHfills(bview->buffer(), row);
2935
2936 #ifndef NEW_TABULAR
2937 /* table stuff -- begin*/
2938         if (row->par()->table) {
2939            w = workWidth(bview) - row->par()->table->WidthOfTable()
2940            - x - RightMargin(bview->buffer(), row);
2941            nh = 0; /* ignore hfills in tables */ 
2942         }
2943 /* table stuff -- end*/
2944 #endif
2945         if (nh)
2946           fill_hfill = w /nh;
2947         else  {
2948                 // is it block, flushleft or flushright? 
2949                 // set x how you need it
2950         int align;
2951         if (row->par()->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
2952           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
2953         else
2954           align = row->par()->FirstPhysicalPar()->align;
2955            
2956         // center displayed insets 
2957            if (row->par()->GetChar(row->pos()) == LyXParagraph::META_INSET
2958                && row->par()->GetInset(row->pos())
2959                && row->par()->GetInset(row->pos())->display())
2960              align = LYX_ALIGN_CENTER;
2961
2962            switch (align) {
2963             case LYX_ALIGN_BLOCK:
2964               ns = NumberOfSeparators(bview->buffer(), row);
2965               if (ns && row->next() && row->next()->par() == row->par() &&
2966                   !(row->next()->par()->IsNewline(row->next()->pos() - 1))
2967                   && !(row->next()->par()->GetChar(row->next()->pos()) == LyXParagraph::META_INSET
2968                        && row->next()->par()->GetInset(row->next()->pos())
2969                        && row->next()->par()->GetInset(row->next()->pos())->display())
2970                   )
2971                 fill_separator = w / ns;
2972               else if (is_rtl)
2973                 x += w;
2974               break;
2975             case LYX_ALIGN_RIGHT:
2976               x += w;
2977               break;
2978             case LYX_ALIGN_CENTER:
2979               x += w / 2;
2980               break;
2981            }
2982         }
2983         if (!bidi)
2984                 return;
2985
2986         ComputeBidiTables(bview->buffer(), row);
2987         if (is_rtl) {
2988                 LyXParagraph::size_type main_body = 
2989                         BeginningOfMainBody(bview->buffer(), row->par());
2990                 LyXParagraph::size_type last = RowLast(row);
2991
2992                 if (main_body > 0 &&
2993                     (main_body-1 > last || 
2994                      !row->par()->IsLineSeparator(main_body-1))) {
2995                         LyXLayout const & layout =
2996                                 textclasslist.Style(bview->buffer()->params.textclass,
2997                                                     row->par()->GetLayout());
2998                         x += lyxfont::width(layout.labelsep,
2999                                             GetFont(bview->buffer(), row->par(), -2));
3000                         if (main_body-1 <= last)
3001                                 x += fill_label_hfill;
3002                 }
3003         }
3004 }
3005       
3006 /* important for the screen */
3007
3008
3009 /* the cursor set functions have a special mechanism. When they
3010 * realize, that you left an empty paragraph, they will delete it.
3011 * They also delete the corresponding row */
3012
3013 void LyXText::CursorRightOneWord(BufferView * bview) const
3014 {
3015         // treat floats, HFills and Insets as words
3016         LyXCursor tmpcursor = cursor;
3017         // CHECK See comment on top of text.C
3018
3019         if (tmpcursor.pos() == tmpcursor.par()->Last()
3020             && tmpcursor.par()->Next()) {
3021                         tmpcursor.par(tmpcursor.par()->Next());
3022                         tmpcursor.pos(0);
3023         } else {
3024                 int steps = 0;
3025
3026                 // Skip through initial nonword stuff.
3027                 while ( tmpcursor.pos() < tmpcursor.par()->Last() &&
3028                         ! tmpcursor.par()->IsWord( tmpcursor.pos() ) ) 
3029                 {
3030                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
3031                         tmpcursor.pos(tmpcursor.pos() + 1);
3032                         ++steps;
3033                 }
3034                 // Advance through word.
3035                 while ( tmpcursor.pos() < tmpcursor.par()->Last() &&
3036                         tmpcursor.par()->IsWord( tmpcursor.pos() ) )
3037                 {
3038                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
3039                         tmpcursor.pos(tmpcursor.pos() + 1);
3040                         ++steps;
3041                 }
3042         }
3043         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3044 }
3045
3046
3047 void LyXText::CursorTab(BufferView * bview) const
3048 {
3049 #ifndef NEW_TABULAR
3050     if (cursor.par()->table) {
3051         int cell = NumberOfCell(cursor.par(), cursor.pos());
3052         while(cursor.par()->table->IsContRow(cell)) {
3053             CursorUp(bview);
3054             cell = NumberOfCell(cursor.par(), cursor.pos());
3055         }
3056         if (cursor.par()->table->ShouldBeVeryLastCell(cell))
3057             TableFeatures(bview, LyXTable::APPEND_ROW);
3058     }
3059 #endif
3060     LyXCursor tmpcursor = cursor;
3061     while (tmpcursor.pos() < tmpcursor.par()->Last()
3062            && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
3063         tmpcursor.pos(tmpcursor.pos() + 1);
3064    
3065     if (tmpcursor.pos() == tmpcursor.par()->Last()){
3066         if (tmpcursor.par()->Next()) {
3067             tmpcursor.par(tmpcursor.par()->Next());
3068             tmpcursor.pos(0);
3069         }
3070     } else
3071         tmpcursor.pos(tmpcursor.pos() + 1);
3072     SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3073 #ifndef NEW_TABULAR
3074     if (cursor.par()->table) {
3075         int cell = NumberOfCell(cursor.par(), cursor.pos());
3076         while (cursor.par()->table->IsContRow(cell) &&
3077                !cursor.par()->table->ShouldBeVeryLastCell(cell)) {
3078             tmpcursor = cursor;
3079             while (tmpcursor.pos() < tmpcursor.par()->Last()
3080                    && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
3081                 tmpcursor.pos(tmpcursor.pos() + 1);
3082    
3083             if (tmpcursor.pos() == tmpcursor.par()->Last()){
3084                 if (tmpcursor.par()->Next()) {
3085                     tmpcursor.par(tmpcursor.par()->Next());
3086                     tmpcursor.pos(0);
3087                 }
3088             } else
3089                 tmpcursor.pos(tmpcursor.pos() + 1);
3090             SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3091             cell = NumberOfCell(cursor.par(), cursor.pos());
3092         }
3093     }
3094 #endif
3095 }
3096
3097
3098 /* -------> Skip initial whitespace at end of word and move cursor to *start*
3099             of prior word, not to end of next prior word. */
3100
3101 void LyXText::CursorLeftOneWord(BufferView * bview)  const
3102 {
3103         // treat HFills, floats and Insets as words
3104         LyXCursor tmpcursor = cursor;
3105         while (tmpcursor.pos() 
3106                && (tmpcursor.par()->IsSeparator(tmpcursor.pos() - 1) 
3107                    || tmpcursor.par()->IsKomma(tmpcursor.pos() - 1))
3108                && !(tmpcursor.par()->IsHfill(tmpcursor.pos() - 1)
3109                     || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
3110                     || tmpcursor.par()->IsInset(tmpcursor.pos() - 1)))
3111                 tmpcursor.pos(tmpcursor.pos() - 1);
3112
3113         if (tmpcursor.pos()
3114             && (tmpcursor.par()->IsInset(tmpcursor.pos() - 1)
3115                 || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
3116                 || tmpcursor.par()->IsHfill(tmpcursor.pos() - 1))) {
3117                 tmpcursor.pos(tmpcursor.pos() - 1);
3118         } else if (!tmpcursor.pos()) {
3119                 if (tmpcursor.par()->Previous()){
3120                         tmpcursor.par(tmpcursor.par()->Previous());
3121                         tmpcursor.pos(tmpcursor.par()->Last());
3122                 }
3123         } else {                // Here, tmpcursor != 0 
3124                 while (tmpcursor.pos() > 0 &&
3125                        tmpcursor.par()->IsWord(tmpcursor.pos()-1) )
3126                         tmpcursor.pos(tmpcursor.pos() - 1);
3127         }
3128         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3129 }
3130
3131 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
3132                         patched as well. */
3133
3134 void LyXText::SelectWord(BufferView * bview) 
3135 {
3136         // Move cursor to the beginning, when not already there.
3137         if ( cursor.pos()
3138              && !cursor.par()->IsSeparator(cursor.pos()-1)
3139              && !cursor.par()->IsKomma(cursor.pos()-1) )
3140                 CursorLeftOneWord(bview);
3141
3142         // set the sel cursor
3143         sel_cursor = cursor;
3144
3145         while ( cursor.pos() < cursor.par()->Last()
3146                         && !cursor.par()->IsSeparator(cursor.pos())
3147                         && !cursor.par()->IsKomma(cursor.pos()) )
3148                 cursor.pos(cursor.pos() + 1);
3149         SetCursor(bview, cursor.par(), cursor.pos() );
3150         
3151         // finally set the selection
3152         SetSelection();
3153 }
3154
3155
3156 /* -------> Select the word currently under the cursor when:
3157                         1: no selection is currently set,
3158                         2: the cursor is not at the borders of the word. */
3159
3160 bool LyXText::SelectWordWhenUnderCursor(BufferView * bview) 
3161 {
3162         if (!selection &&
3163             cursor.pos() > 0 && cursor.pos() < cursor.par()->Last()
3164             && !cursor.par()->IsSeparator(cursor.pos())
3165             && !cursor.par()->IsKomma(cursor.pos())
3166             && !cursor.par()->IsSeparator(cursor.pos() -1)
3167             && !cursor.par()->IsKomma(cursor.pos() -1) ) {
3168                 SelectWord(bview);
3169                 return true;
3170         }
3171         return false;
3172 }
3173
3174
3175 // This function is only used by the spellchecker for NextWord().
3176 // It doesn't handle LYX_ACCENTs and probably never will.
3177 char * LyXText::SelectNextWord(BufferView * bview, float & value)
3178 {
3179         LyXParagraph * tmppar = cursor.par();
3180         
3181         // If this is not the very first word, skip rest of
3182         // current word because we are probably in the middle
3183         // of a word if there is text here.
3184         if (cursor.pos() || cursor.par()->previous) {
3185                 while (cursor.pos() < cursor.par()->Last()
3186                        && cursor.par()->IsLetter(cursor.pos()))
3187                         cursor.pos(cursor.pos() + 1);
3188         }
3189         // Now, skip until we have real text (will jump paragraphs)
3190         while ((cursor.par()->Last() > cursor.pos()
3191                 && (!cursor.par()->IsLetter(cursor.pos())
3192                     || cursor.par()->getFont(bview->buffer()->params, cursor.pos())
3193                     .latex() == LyXFont::ON))
3194                || (cursor.par()->Last() == cursor.pos() 
3195                    && cursor.par()->Next())){
3196                 if (cursor.pos() == cursor.par()->Last()) {
3197                         cursor.par(cursor.par()->Next());
3198                         cursor.pos(0);
3199                 } else
3200                         cursor.pos(cursor.pos() + 1);
3201         }
3202   
3203         // Update the value if we changed paragraphs
3204         if (cursor.par() != tmppar){
3205                 SetCursor(bview, cursor.par(), cursor.pos());
3206                 value = float(cursor.y())/float(height);
3207         }
3208
3209         // Start the selection from here
3210         sel_cursor = cursor;
3211
3212 #ifdef HAVE_SSTREAM
3213         std::ostringstream latex;
3214 #else
3215         ostrstream latex;
3216 #endif
3217         // and find the end of the word 
3218         // (optional hyphens are part of a word)
3219         while (cursor.pos() < cursor.par()->Last()
3220                && (cursor.par()->IsLetter(cursor.pos())) 
3221                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
3222                        && cursor.par()->GetInset(cursor.pos()) != 0
3223                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
3224 #ifdef HAVE_SSTREAM
3225                        && latex.str() == "\\-"
3226 #else
3227                        && latex.str() // protect against null pointers         
3228                        && string(latex.str(), 3) == "\\-" // this is not nice at all
3229 #endif
3230                            ))
3231                 cursor.pos(cursor.pos() + 1);
3232
3233 #ifndef HAVE_SSTREAM
3234         delete [] latex.str();
3235 #endif
3236         // Finally, we copy the word to a string and return it
3237         char * str = 0;
3238
3239         if (sel_cursor.pos() < cursor.pos()) {
3240                 str = new char [cursor.pos() - sel_cursor.pos() + 2];
3241                 LyXParagraph::size_type i, j;
3242                 for (i = sel_cursor.pos(), j = 0; i < cursor.pos(); ++i) {
3243                         if (cursor.par()->GetChar(i) != LyXParagraph::META_INSET)
3244                                 str[j++] = cursor.par()->GetChar(i);
3245                 }
3246                 str[j] = '\0';
3247         }
3248         return str;
3249 }
3250
3251
3252 // This one is also only for the spellchecker
3253 void LyXText::SelectSelectedWord(BufferView * bview)
3254 {
3255         // move cursor to the beginning
3256         SetCursor(bview, sel_cursor.par(), sel_cursor.pos());
3257         
3258         // set the sel cursor
3259         sel_cursor = cursor;
3260
3261 #ifdef HAVE_SSTREAM
3262         std::ostringstream latex;
3263 #else
3264         ostrstream latex;
3265 #endif
3266         
3267         // now find the end of the word
3268         while (cursor.pos() < cursor.par()->Last()
3269                && (cursor.par()->IsLetter(cursor.pos())
3270                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
3271                        && cursor.par()->GetInset(cursor.pos()) != 0
3272                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
3273 #ifdef HAVE_SSTREAM
3274                        && latex.str() == "\\-"
3275 #else
3276                        && string(latex.str(), 3) == "\\-"
3277 #endif
3278                            )))
3279                 cursor.pos(cursor.pos() + 1);
3280         
3281 #ifndef HAVE_SSTREAM
3282         delete [] latex.str();
3283 #endif
3284         SetCursor(bview, cursor.par(), cursor.pos());
3285         
3286         // finally set the selection
3287         SetSelection();
3288 }
3289
3290
3291 /* -------> Delete from cursor up to the end of the current or next word. */
3292 void LyXText::DeleteWordForward(BufferView * bview)
3293 {
3294         if (!cursor.par()->Last())
3295                 CursorRight(bview);
3296         else {
3297                 LyXCursor tmpcursor = cursor;
3298                 tmpcursor.row(0); // ??
3299                 selection = true; // to avoid deletion 
3300                 CursorRightOneWord(bview);
3301                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3302                 sel_cursor = cursor;
3303                 cursor = tmpcursor;
3304                 SetSelection(); 
3305                 
3306                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
3307                 CutSelection(bview);
3308         }
3309 }
3310
3311
3312 /* -------> Delete from cursor to start of current or prior word. */
3313 void LyXText::DeleteWordBackward(BufferView * bview)
3314 {
3315        if (!cursor.par()->Last())
3316                CursorLeft(bview);
3317        else {
3318                LyXCursor tmpcursor = cursor;
3319                tmpcursor.row(0); // ??
3320                selection = true; // to avoid deletion 
3321                CursorLeftOneWord(bview);
3322                SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3323                sel_cursor = cursor;
3324                cursor = tmpcursor;
3325                SetSelection();
3326                CutSelection(bview);
3327        }
3328 }
3329
3330
3331 /* -------> Kill to end of line. */
3332 void LyXText::DeleteLineForward(BufferView * bview)
3333 {
3334         if (!cursor.par()->Last())
3335                 // Paragraph is empty, so we just go to the right
3336                 CursorRight(bview);
3337         else {
3338                 LyXCursor tmpcursor = cursor;
3339                 // We can't store the row over a regular SetCursor
3340                 // so we set it to 0 and reset it afterwards.
3341                 tmpcursor.row(0); // ??
3342                 selection = true; // to avoid deletion 
3343                 CursorEnd(bview);
3344                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3345                 sel_cursor = cursor;
3346                 cursor = tmpcursor;
3347                 SetSelection();
3348                 // What is this test for ??? (JMarc)
3349                 if (!selection) {
3350                         DeleteWordForward(bview);
3351                 } else {
3352                         CutSelection(bview);
3353                 }
3354         }
3355 }
3356
3357
3358 // Change the case of a word at cursor position. 
3359 // This function directly manipulates LyXParagraph::text because there
3360 // is no LyXParagraph::SetChar currently. I did what I could to ensure
3361 // that it is correct. I guess part of it should be moved to
3362 // LyXParagraph, but it will have to change for 1.1 anyway. At least
3363 // it does not access outside of the allocated array as the older
3364 // version did. (JMarc) 
3365 void LyXText::ChangeWordCase(BufferView * bview, LyXText::TextCase action) 
3366 {
3367         LyXParagraph * tmppar = cursor.par()->ParFromPos(cursor.pos());
3368
3369         SetUndo(bview->buffer(),Undo::FINISH, tmppar->previous, tmppar->next); 
3370
3371         LyXParagraph::size_type tmppos = 
3372                 cursor.par()->PositionInParFromPos(cursor.pos());
3373         while (tmppos < tmppar->size()) {
3374                 unsigned char c = tmppar->GetChar(tmppos);
3375                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
3376                         break;
3377                 if (c != LyXParagraph::META_INSET) {
3378                         switch (action) {
3379                         case text_lowercase:
3380                                 c = tolower(c);
3381                                 break;
3382                         case text_capitalization:
3383                                 c = toupper(c);
3384                                 action = text_lowercase;
3385                                 break;
3386                         case text_uppercase:
3387                                 c = toupper(c);
3388                                 break;
3389                         }
3390                 }
3391                 
3392                 //tmppar->text[tmppos] = c;
3393                 tmppar->SetChar(tmppos, c);
3394                 ++tmppos;
3395         }
3396         CheckParagraph(bview, tmppar, tmppos);
3397         CursorRightOneWord(bview);
3398 }
3399
3400
3401 void LyXText::Delete(BufferView * bview)
3402 {
3403         // this is a very easy implementation
3404
3405         LyXCursor old_cursor = cursor;
3406         int old_cur_par_id = old_cursor.par()->id();
3407         int old_cur_par_prev_id = old_cursor.par()->previous ?
3408                 old_cursor.par()->previous->id() : 0;
3409         
3410         // just move to the right
3411         CursorRightIntern(bview);
3412
3413         // CHECK Look at the comment here.
3414         // This check is not very good...
3415         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
3416         // and that can very well delete the par or par->previous in
3417         // old_cursor. Will a solution where we compare paragraph id's
3418         //work better?
3419         if ((cursor.par()->previous ? cursor.par()->previous->id() : 0)
3420             == old_cur_par_prev_id
3421             && cursor.par()->id() != old_cur_par_id)
3422                 return; // delete-empty-paragraph-mechanism has done it
3423
3424         // if you had success make a backspace
3425         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
3426                 LyXCursor tmpcursor = cursor;
3427                 cursor = old_cursor; // to make sure undo gets the right cursor position
3428                 SetUndo(bview->buffer(), Undo::DELETE, 
3429                         cursor.par()->ParFromPos(cursor.pos())->previous, 
3430                         cursor.par()->ParFromPos(cursor.pos())->next); 
3431                 cursor = tmpcursor;
3432                 Backspace(bview);
3433         }
3434 }
3435
3436
3437 void LyXText::Backspace(BufferView * bview)
3438 {
3439 #ifndef NEW_TABULAR
3440         /* table stuff -- begin */
3441         if (cursor.par()->table) {
3442                 BackspaceInTable(bview);
3443                 return;
3444         }
3445         /* table stuff -- end */
3446 #endif
3447         // LyXFont rawtmpfont = current_font;
3448         // LyXFont realtmpfont = real_current_font;
3449         //    We don't need the above variables as calling to SetCursor() with third
3450         //    argument eqaul to false, will not change current_font & real_current_font
3451         
3452         // Get the font that is used to calculate the baselineskip
3453         LyXParagraph::size_type lastpos = cursor.par()->Last();
3454         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
3455                                                          lastpos - 1);
3456
3457         if (cursor.pos() == 0) {
3458                 // The cursor is at the beginning of a paragraph, so the the backspace
3459                 // will collapse two paragraphs into one.
3460                 
3461                 // we may paste some paragraphs
3462       
3463                 // is it an empty paragraph?
3464       
3465                 if ((lastpos == 0
3466                      || (lastpos == 1 && cursor.par()->IsSeparator(0)))
3467                     && !(cursor.par()->Next() 
3468                          && cursor.par()->footnoteflag == LyXParagraph::NO_FOOTNOTE
3469                          && cursor.par()->Next()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)) {
3470                         // This is an empty paragraph and we delete it just by moving the cursor one step
3471                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
3472                         // of the paragraph.
3473                         
3474                         if (cursor.par()->previous) {
3475                                 LyXParagraph * tmppar = cursor.par()->previous->FirstPhysicalPar();
3476                                 if (cursor.par()->GetLayout() == tmppar->GetLayout()
3477                                     && cursor.par()->footnoteflag == tmppar->footnoteflag
3478                                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
3479                                         // Inherit botom DTD from the paragraph below.
3480                                         // (the one we are deleting)
3481                                         tmppar->line_bottom = cursor.par()->line_bottom;
3482                                         tmppar->added_space_bottom = cursor.par()->added_space_bottom;
3483                                         tmppar->pagebreak_bottom = cursor.par()->pagebreak_bottom;
3484                                 }
3485                                 
3486                                 CursorLeftIntern(bview);
3487                      
3488                                 // the layout things can change the height of a row !
3489                                 int tmpheight = cursor.row()->height();
3490                                 SetHeightOfRow(bview, cursor.row());
3491                                 if (cursor.row()->height() != tmpheight) {
3492                                         refresh_y = cursor.y() - cursor.row()->baseline();
3493                                         refresh_row = cursor.row();
3494                                         status = LyXText::NEED_MORE_REFRESH;
3495                                 }
3496                                 return;
3497                         }
3498                 }
3499                 
3500                 if (cursor.par()->ParFromPos(cursor.pos())->previous){
3501                         SetUndo(bview->buffer(), Undo::DELETE,
3502                                 cursor.par()->ParFromPos(cursor.pos())->previous->previous,
3503                                 cursor.par()->ParFromPos(cursor.pos())->next);
3504                 }
3505                 
3506                 LyXParagraph * tmppar = cursor.par();
3507                 Row * tmprow = cursor.row();
3508
3509                 // We used to do CursorLeftIntern() here, but it is
3510                 // not a good idea since it triggers the auto-delete
3511                 // mechanism. So we do a CursorLeftIntern()-lite,
3512                 // without the dreaded mechanism. (JMarc)
3513                 if (cursor.par()->Previous()) { 
3514                         // steps into the above paragraph.
3515                         SetCursorIntern(bview, cursor.par()->Previous(), 
3516                                         cursor.par()->Previous()->Last(), false);
3517                 }
3518
3519                 /* Pasting is not allowed, if the paragraphs have different
3520                    layout. I think it is a real bug of all other
3521                    word processors to allow it. It confuses the user.
3522                    Even so with a footnote paragraph and a non-footnote
3523                    paragraph. I will not allow pasting in this case, 
3524                    because the user would be confused if the footnote behaves 
3525                    different wether it is open or closed.
3526                   
3527                    Correction: Pasting is always allowed with standard-layout
3528                 */
3529                 if (cursor.par() != tmppar
3530                     && (cursor.par()->GetLayout() == tmppar->GetLayout()
3531                         || tmppar->GetLayout() == 0 /*standard*/)
3532                     && cursor.par()->footnoteflag == tmppar->footnoteflag
3533 #ifndef NEW_TABULAR
3534                     /* table stuff -- begin*/
3535                     && !cursor.par()->table /* no pasting of tables */ 
3536                     /* table stuff -- end*/
3537 #endif
3538                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
3539
3540                         RemoveParagraph(tmprow);
3541                         RemoveRow(tmprow);
3542                         cursor.par()->PasteParagraph(bview->buffer()->params);
3543                         
3544                         if (!cursor.pos() || !cursor.par()->IsSeparator(cursor.pos() - 1))
3545                                 ; //cursor.par()->InsertChar(cursor.pos(), ' ');
3546                         // strangely enough it seems that commenting out the line above removes
3547                         // most or all of the segfaults. I will however also try to move the
3548                         // two Remove... lines in front of the PasteParagraph too.
3549                         else
3550                                 if (cursor.pos())
3551                                         cursor.pos(cursor.pos() - 1);
3552                         
3553                         status = LyXText::NEED_MORE_REFRESH;
3554                         refresh_row = cursor.row();
3555                         refresh_y = cursor.y() - cursor.row()->baseline();
3556                         
3557                         // remove the lost paragraph
3558                         // This one is not safe, since the paragraph that the tmprow and the
3559                         // following rows belong to has been deleted by the PasteParagraph
3560                         // above. The question is... could this be moved in front of the
3561                         // PasteParagraph?
3562                         //RemoveParagraph(tmprow);
3563                         //RemoveRow(tmprow);  
3564                         
3565                         // This rebuilds the rows.
3566                         AppendParagraph(bview, cursor.row());
3567                         UpdateCounters(bview, cursor.row());
3568                         
3569                         // the row may have changed, block, hfills etc.
3570                         SetCursor(bview, cursor.par(), cursor.pos(), false);
3571                 }
3572         } else {
3573                 /* this is the code for a normal backspace, not pasting
3574                  * any paragraphs */ 
3575                 SetUndo(bview->buffer(), Undo::DELETE, 
3576                         cursor.par()->ParFromPos(cursor.pos())->previous, 
3577                         cursor.par()->ParFromPos(cursor.pos())->next); 
3578                 // We used to do CursorLeftIntern() here, but it is
3579                 // not a good idea since it triggers the auto-delete
3580                 // mechanism. So we do a CursorLeftIntern()-lite,
3581                 // without the dreaded mechanism. (JMarc)
3582                 SetCursorIntern(bview, cursor.par(), cursor.pos()- 1,
3583                                 false, cursor.boundary());
3584                 
3585                 // some insets are undeletable here
3586                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
3587                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
3588                                 return; 
3589                         // force complete redo when erasing display insets
3590                         // this is a cruel method but safe..... Matthias 
3591                         if (cursor.par()->GetInset(cursor.pos())->display()){
3592                                 cursor.par()->Erase(cursor.pos());
3593                                 RedoParagraph(bview);
3594                                 return;
3595                         }
3596                 }
3597                 
3598                 Row * row = cursor.row();
3599                 long y = cursor.y() - row->baseline();
3600                 LyXParagraph::size_type z;
3601                 /* remember that a space at the end of a row doesnt count
3602                  * when calculating the fill */ 
3603                 if (cursor.pos() < RowLast(row) ||
3604                     !cursor.par()->IsLineSeparator(cursor.pos())) {
3605                         row->fill(row->fill() + SingleWidth(bview,
3606                                                             cursor.par(),
3607                                                             cursor.pos()));
3608                 }
3609                 
3610                 /* some special code when deleting a newline. This is similar
3611                  * to the behavior when pasting paragraphs */ 
3612                 if (cursor.pos() && cursor.par()->IsNewline(cursor.pos())) {
3613                         cursor.par()->Erase(cursor.pos());
3614                         // refresh the positions
3615                         Row * tmprow = row;
3616                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
3617                                 tmprow = tmprow->next();
3618                                 tmprow->pos(tmprow->pos() - 1);
3619                         }
3620                         if (cursor.par()->IsLineSeparator(cursor.pos() - 1))
3621                                 cursor.pos(cursor.pos() - 1);
3622                         
3623                         if (cursor.pos() < cursor.par()->Last() && !cursor.par()->IsSeparator(cursor.pos())) {
3624                                 cursor.par()->InsertChar(cursor.pos(), ' ');
3625                                 // refresh the positions
3626                                 tmprow = row;
3627                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
3628                                         tmprow = tmprow->next();
3629                                         tmprow->pos(tmprow->pos() + 1);
3630                                 }
3631                         }
3632                 } else {
3633                         cursor.par()->Erase(cursor.pos());
3634                         
3635                         // refresh the positions
3636                         Row * tmprow = row;
3637                         while (tmprow->next()
3638                                && tmprow->next()->par() == row->par()) {
3639                                 tmprow = tmprow->next();
3640                                 tmprow->pos(tmprow->pos() - 1);
3641                         }
3642
3643                         // delete newlines at the beginning of paragraphs
3644                         while (cursor.par()->Last() &&
3645                                cursor.par()->IsNewline(cursor.pos()) &&
3646                                cursor.pos() == BeginningOfMainBody(bview->buffer(),
3647                                                                    cursor.par())) {
3648                                 cursor.par()->Erase(cursor.pos());
3649                                 // refresh the positions
3650                                 tmprow = row;
3651                                 while (tmprow->next() && 
3652                                        tmprow->next()->par() == row->par()) {
3653                                         tmprow = tmprow->next();
3654                                         tmprow->pos(tmprow->pos() - 1);
3655                                 }
3656                         }
3657                 }
3658                 
3659                 // is there a break one row above
3660                 if (row->previous() && row->previous()->par() == row->par()) {
3661                         z = NextBreakPoint(bview, row->previous(),
3662                                            workWidth(bview));
3663                         if ( z >= row->pos()) {
3664                                 row->pos(z + 1);
3665                                 
3666                                 Row * tmprow = row->previous();
3667                                 
3668                                 // maybe the current row is now empty
3669                                 if (row->pos() >= row->par()->Last()) {
3670                                         // remove it
3671                                         RemoveRow(row);
3672                                         need_break_row = 0;
3673                                 } else {
3674                                         BreakAgainOneRow(bview, row);
3675                                         if (row->next() && row->next()->par() == row->par())
3676                                                 need_break_row = row->next();
3677                                         else
3678                                                 need_break_row = 0;
3679                                 }
3680                                 
3681                                 // set the dimensions of the row above
3682                                 y -= tmprow->height();
3683                                 tmprow->fill(Fill(bview, tmprow,
3684                                                   workWidth(bview)));
3685                                 SetHeightOfRow(bview, tmprow);
3686                                 
3687                                 refresh_y = y;
3688                                 refresh_row = tmprow;
3689                                 status = LyXText::NEED_MORE_REFRESH;
3690                                 SetCursor(bview, cursor.par(), cursor.pos(),
3691                                           false, cursor.boundary());
3692                                 //current_font = rawtmpfont;
3693                                 //real_current_font = realtmpfont;
3694                                 // check, whether the last character's font has changed.
3695                                 if (rawparfont !=
3696                                     cursor.par()->GetFontSettings(bview->buffer()->params,
3697                                                                   cursor.par()->Last() - 1))
3698                                         RedoHeightOfParagraph(bview, cursor);
3699                                 return;
3700                         }
3701                 }
3702                 
3703                 // break the cursor row again
3704                 z = NextBreakPoint(bview, row, workWidth(bview));
3705                 
3706                 if (z != RowLast(row) || 
3707                     (row->next() && row->next()->par() == row->par() &&
3708                      RowLast(row) == row->par()->Last() - 1)){
3709                         
3710                         /* it can happen that a paragraph loses one row
3711                          * without a real breakup. This is when a word
3712                          * is to long to be broken. Well, I don t care this 
3713                          * hack ;-) */ 
3714                         if (row->next() && row->next()->par() == row->par() &&
3715                             RowLast(row) == row->par()->Last() - 1)
3716                                 RemoveRow(row->next());
3717                         
3718                         refresh_y = y;
3719                         refresh_row = row;
3720                         status = LyXText::NEED_MORE_REFRESH;
3721                         
3722                         BreakAgainOneRow(bview, row);
3723                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3724                         // cursor MUST be in row now
3725                         
3726                         if (row->next() && row->next()->par() == row->par())
3727                                 need_break_row = row->next();
3728                         else
3729                                 need_break_row = 0;
3730                 } else  {
3731                         // set the dimensions of the row
3732                         row->fill(Fill(bview, row, workWidth(bview)));
3733                         int tmpheight = row->height();
3734                         SetHeightOfRow(bview, row);
3735                         if (tmpheight == row->height())
3736                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
3737                         else
3738                                 status = LyXText::NEED_MORE_REFRESH;
3739                         refresh_y = y;
3740                         refresh_row = row;
3741                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3742                 }
3743         }
3744
3745         // current_font = rawtmpfont;
3746         // real_current_font = realtmpfont;
3747
3748         lastpos = cursor.par()->Last();
3749         if (cursor.pos() == lastpos) {
3750                 SetCurrentFont(bview);
3751                 if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos()) != cursor.boundary())
3752                         SetCursor(bview, cursor.par(), cursor.pos(), false, !cursor.boundary());
3753         }
3754         
3755         // check, wether the last characters font has changed.
3756         if (rawparfont != 
3757             cursor.par()->GetFontSettings(bview->buffer()->params, lastpos - 1)) {
3758                 RedoHeightOfParagraph(bview, cursor);
3759         } else {
3760                 // now the special right address boxes
3761                 if (textclasslist.Style(bview->buffer()->params.textclass,
3762                                         cursor.par()->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3763                         RedoDrawingOfParagraph(bview, cursor); 
3764                 }
3765         }
3766 }
3767
3768
3769 void LyXText::GetVisibleRow(BufferView * bview, int y_offset, int x_offset,
3770                             Row * row_ptr, long y)
3771 {
3772         /* returns a printed row */
3773         Painter & pain = bview->painter();
3774         
3775         bool is_rtl = row_ptr->par()->isRightToLeftPar(bview->buffer()->params);
3776         LyXParagraph::size_type last = RowLastPrintable(row_ptr);
3777
3778         LyXParagraph::size_type vpos, pos;
3779         float x, tmpx;
3780         int y_top, y_bottom;
3781         float fill_separator, fill_hfill, fill_label_hfill;
3782
3783         LyXFont font;
3784         int maxdesc;
3785         if (row_ptr->height() <= 0) {
3786                 lyxerr << "LYX_ERROR: row.height: "
3787                        << row_ptr->height() << endl;
3788                 return;
3789         }
3790         PrepareToPrint(bview, row_ptr, x, fill_separator,
3791                        fill_hfill, fill_label_hfill);
3792         
3793         x += x_offset;
3794         
3795         // clear the area where we want to paint/print
3796         int ww = workWidth(bview);
3797         if (ww < 0)
3798                 ww = bview->workWidth();
3799         if (bv_owner)
3800                 pain.fillRectangle(x_offset, y_offset, ww, row_ptr->height());
3801         
3802         if (selection) {
3803                 /* selection code */
3804                 if (bidi_same_direction) {
3805                         if (sel_start_cursor.row() == row_ptr &&
3806                             sel_end_cursor.row() == row_ptr) {
3807                                 if (sel_start_cursor.x() < sel_end_cursor.x())
3808                                         pain.fillRectangle(sel_start_cursor.x(), y_offset,
3809                                                            sel_end_cursor.x() - sel_start_cursor.x(),
3810                                                            row_ptr->height(),
3811                                                            LColor::selection);
3812                                 else
3813                                         pain.fillRectangle(sel_end_cursor.x(), y_offset,
3814                                                            sel_start_cursor.x() - sel_end_cursor.x(),
3815                                                            row_ptr->height(),
3816                                                            LColor::selection);
3817                         } else if (sel_start_cursor.row() == row_ptr) {
3818                                 if (is_rtl)
3819                                         pain.fillRectangle(x_offset, y_offset,
3820                                                            sel_start_cursor.x(),
3821                                                            row_ptr->height(),
3822                                                            LColor::selection);
3823                                 else
3824                                         pain.fillRectangle(sel_start_cursor.x(), y_offset,
3825                                                            ww - sel_start_cursor.x(),
3826                                                            row_ptr->height(),
3827                                                            LColor::selection);
3828                         } else if (sel_end_cursor.row() == row_ptr) {
3829                                 if (is_rtl)
3830                                         pain.fillRectangle(sel_end_cursor.x(), y_offset,
3831                                                            ww - sel_end_cursor.x(),
3832                                                            row_ptr->height(),
3833                                                            LColor::selection);
3834                                 else
3835                                         pain.fillRectangle(x_offset, y_offset,
3836                                                            sel_end_cursor.x(),
3837                                                            row_ptr->height(),
3838                                                            LColor::selection);
3839                         } else if (y > long(sel_start_cursor.y())
3840                                    && y < long(sel_end_cursor.y())) {
3841                                 pain.fillRectangle(x_offset, y_offset,
3842                                                    ww, row_ptr->height(),
3843                                                    LColor::selection);
3844                         }
3845                 } else if ( sel_start_cursor.row() != row_ptr &&
3846                             sel_end_cursor.row() != row_ptr &&
3847                             y > long(sel_start_cursor.y())
3848                             && y < long(sel_end_cursor.y())) {
3849                         pain.fillRectangle(x_offset, y_offset, ww, row_ptr->height(),
3850                                            LColor::selection);
3851                 } else if (sel_start_cursor.row() == row_ptr ||
3852                            sel_end_cursor.row() == row_ptr) {
3853                         float tmpx = x;
3854                         int cell = 0;
3855 #ifndef NEW_TABULAR
3856                         if (row_ptr->par()->table) {
3857                                 cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
3858                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3859                         }
3860 #endif
3861                         if ( (sel_start_cursor.row() != row_ptr && !is_rtl) ||
3862                              (sel_end_cursor.row() != row_ptr && is_rtl))
3863                                 pain.fillRectangle(x_offset, y_offset,
3864                                                    int(tmpx),
3865                                                    row_ptr->height(),
3866                                                    LColor::selection);
3867 #ifndef NEW_TABULAR
3868                         if (row_ptr->par()->table) {
3869                                 float x_old = x;
3870                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3871                                         pos = vis2log(vpos);
3872                                         float old_tmpx = tmpx;
3873                                         if (row_ptr->par()->IsNewline(pos)) {
3874                                                 tmpx = x_old + row_ptr->par()->table->WidthOfColumn(cell);
3875                                                 x_old = tmpx;
3876                                                 ++cell;
3877                                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3878                                         } else {
3879                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3880                                         }
3881                                         if ( (sel_start_cursor.row() != row_ptr ||
3882                                               sel_start_cursor.pos() <= pos) &&
3883                                              (sel_end_cursor.row() != row_ptr ||
3884                                               pos < sel_end_cursor.pos()) )
3885                                                 pain.fillRectangle(int(old_tmpx), y_offset,
3886                                                                    int(tmpx - old_tmpx + 1),
3887                                                                    row_ptr->height(),
3888                                                                    LColor::selection);
3889                                 }
3890                         } else {
3891 #endif
3892                                 LyXParagraph::size_type main_body =
3893                                         BeginningOfMainBody(bview->buffer(),
3894                                                             row_ptr->par());
3895
3896                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3897                                         pos = vis2log(vpos);
3898                                         float old_tmpx = tmpx;
3899                                         if (main_body > 0 && pos == main_body-1) {
3900                                                 tmpx += fill_label_hfill +
3901                                                         lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
3902                                                                                            row_ptr->par()->GetLayout()).labelsep,
3903                                                                        GetFont(bview->buffer(),row_ptr->par(), -2));
3904                                                 if (row_ptr->par()->IsLineSeparator(main_body-1))
3905                                                         tmpx -= SingleWidth(bview, row_ptr->par(), main_body-1);
3906                                         }
3907                                         if (HfillExpansion(bview->buffer(), row_ptr, pos)) {
3908                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3909                                                 if (pos >= main_body)
3910                                                         tmpx += fill_hfill;
3911                                                 else 
3912                                                         tmpx += fill_label_hfill;
3913                                         }
3914                                         else if (row_ptr->par()->IsSeparator(pos)) {
3915                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3916                                                 if (pos >= main_body)
3917                                                         tmpx += fill_separator;
3918                                         } else
3919                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3920
3921                                         if ( (sel_start_cursor.row() != row_ptr ||
3922                                               sel_start_cursor.pos() <= pos) &&
3923                                              (sel_end_cursor.row() != row_ptr ||
3924                                               pos < sel_end_cursor.pos()) )
3925                                                 pain.fillRectangle(int(old_tmpx), y_offset,
3926                                                                    int(tmpx - old_tmpx + 1),
3927                                                                    row_ptr->height(),
3928                                                            LColor::selection);
3929                                 }
3930 #ifndef NEW_TABULAR
3931                         }
3932 #endif
3933                         if ( (sel_start_cursor.row() != row_ptr && is_rtl) ||
3934                              (sel_end_cursor.row() != row_ptr && !is_rtl) )
3935                                 pain.fillRectangle(int(tmpx), y_offset,
3936                                                    int(ww - tmpx),
3937                                                    row_ptr->height(),
3938                                                    LColor::selection);
3939                 }
3940         }
3941
3942         int box_x = 0;
3943         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
3944                 LyXFont font(LyXFont::ALL_SANE);
3945                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3946                 font.setColor(LColor::footnote);
3947                 
3948                 box_x = LYX_PAPER_MARGIN + lyxfont::width(" wide-tab ", font);
3949                 if (row_ptr->previous() &&
3950                     row_ptr->previous()->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
3951                         string fs;
3952                         switch (row_ptr->par()->footnotekind) {
3953                         case LyXParagraph::MARGIN:
3954                                 fs = " margin";
3955                                 break;
3956                         case LyXParagraph::FIG:
3957                                 fs = " fig";
3958                                 break;
3959                         case LyXParagraph::TAB:
3960                                 fs = " tab";
3961                                 break;
3962                         case LyXParagraph::WIDE_FIG:
3963                                 fs = " wide-fig";
3964                                 break;
3965                         case LyXParagraph::WIDE_TAB:
3966                                 fs = " wide-tab";
3967                                 break;
3968                         case LyXParagraph::ALGORITHM:
3969                                 fs = " alg";
3970                                 break;
3971                         case LyXParagraph::FOOTNOTE:
3972                                 fs = " foot";
3973                                 break;
3974                         }
3975                         
3976                         pain.fillRectangle(LYX_PAPER_MARGIN,
3977                                            y_offset + 1,
3978                                            box_x - LYX_PAPER_MARGIN,
3979                                            int(lyxfont::maxAscent(font)
3980                                                + lyxfont::maxDescent(font)),
3981                                            LColor::footnotebg);
3982                         
3983                         pain.line(LYX_PAPER_MARGIN, y_offset,
3984                                   workWidth(bview) - LYX_PAPER_MARGIN, y_offset,
3985                                   LColor::footnoteframe);
3986                         
3987                         pain.text(LYX_PAPER_MARGIN,
3988                                   y_offset + int(lyxfont::maxAscent(font)) + 1,
3989                                   fs, font);
3990                         
3991                         pain.line(LYX_PAPER_MARGIN, y_offset,
3992                                   LYX_PAPER_MARGIN,
3993                                   y_offset + int(lyxfont::maxAscent(font)
3994                                                + lyxfont::maxDescent(font)),
3995                                   LColor::footnoteframe);
3996                         
3997                         pain.line(LYX_PAPER_MARGIN,
3998                                   y_offset + int(lyxfont::maxAscent(font)
3999                                                + lyxfont::maxDescent(font)) + 1,
4000                                   box_x,
4001                                   y_offset + int(lyxfont::maxAscent(font)
4002                                                + lyxfont::maxDescent(font)) + 1,
4003                                   LColor::footnoteframe);
4004                         
4005                 }
4006                 
4007                 /* draw the open floats in a red box */
4008                 pain.line(box_x, y_offset,
4009                           box_x, y_offset + row_ptr->height(),
4010                           LColor::footnoteframe);
4011                 
4012                 pain.line(workWidth(bview) - LYX_PAPER_MARGIN,
4013                           y_offset,
4014                           workWidth(bview) - LYX_PAPER_MARGIN,
4015                           y_offset + row_ptr->height(),
4016                           LColor::footnoteframe);
4017
4018
4019                 // Draw appendix lines
4020                 LyXParagraph * p = row_ptr->par()->PreviousBeforeFootnote()->FirstPhysicalPar();
4021                 if (p->appendix){
4022                         pain.line(1, y_offset,
4023                                   1, y_offset + row_ptr->height(),
4024                                   LColor::appendixline);
4025                         pain.line(workWidth(bview) - 2, y_offset,
4026                                   workWidth(bview) - 2,
4027                                   y_offset + row_ptr->height(),
4028                                   LColor::appendixline);
4029                 }
4030
4031                 // Draw minipage line
4032                 bool minipage = p->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4033                 if (minipage)
4034                         pain.line(LYX_PAPER_MARGIN/5, y_offset,
4035                                   LYX_PAPER_MARGIN/5, 
4036                                   y_offset + row_ptr->height() - 1,
4037                                   LColor::minipageline);
4038
4039                 // Draw depth lines
4040                 int depth = p->GetDepth();
4041                 for (int i = 1; i <= depth; ++i) {
4042                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage);
4043                         pain.line(line_x, y_offset, line_x,
4044                                   y_offset + row_ptr->height() - 1,
4045                                   LColor::depthbar);
4046                 }
4047         } else if (row_ptr->previous() &&
4048                    row_ptr->previous()->par()->footnoteflag
4049                    == LyXParagraph::OPEN_FOOTNOTE) {
4050                 LyXFont font(LyXFont::ALL_SANE);
4051                 font.setSize(LyXFont::SIZE_FOOTNOTE);
4052                 
4053                 int box_x = LYX_PAPER_MARGIN;
4054                 box_x += lyxfont::width(" wide-tab ", font);
4055                 
4056                 pain.line(box_x, y_offset,
4057                           workWidth(bview) - LYX_PAPER_MARGIN,
4058                           y_offset, LColor::footnote);
4059         }
4060
4061         // Draw appendix lines
4062         LyXParagraph * firstpar = row_ptr->par()->FirstPhysicalPar();
4063         if (firstpar->appendix){
4064                 pain.line(1, y_offset,
4065                           1, y_offset + row_ptr->height(),
4066                           LColor::appendixline);
4067                 pain.line(ww - 2, y_offset,
4068                           ww - 2, y_offset + row_ptr->height(),
4069                           LColor::appendixline);
4070         }
4071
4072         // Draw minipage line
4073         bool minipage = firstpar->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4074         if (minipage)
4075                 pain.line(LYX_PAPER_MARGIN/5 + box_x, y_offset,
4076                           LYX_PAPER_MARGIN/5 + box_x, 
4077                           y_offset + row_ptr->height() - 1,
4078                           LColor::minipageline);
4079
4080         // Draw depth lines
4081         int depth = firstpar->GetDepth();
4082         if (depth > 0) {
4083                 int next_depth = 0;
4084                 int prev_depth = 0;
4085                 if (row_ptr->next())
4086                         if (row_ptr->par()->footnoteflag ==
4087                             row_ptr->next()->par()->footnoteflag)
4088                                 next_depth = row_ptr->next()->par()->GetDepth();
4089                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4090                                 next_depth = depth;
4091
4092                 if (row_ptr->previous())
4093                         if (row_ptr->par()->footnoteflag ==
4094                             row_ptr->previous()->par()->footnoteflag)
4095                                 prev_depth = row_ptr->previous()->par()->GetDepth();
4096                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4097                                 prev_depth = depth;
4098
4099                 for (int i = 1; i <= depth; ++i) {
4100                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage) + box_x;
4101                         pain.line(line_x, y_offset, line_x,
4102                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
4103                                   LColor::depthbar);
4104                 
4105                         if (i > prev_depth)
4106                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
4107                                                    LColor::depthbar);
4108                         if (i > next_depth)
4109                                 pain.fillRectangle(line_x,
4110                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
4111                                                    LYX_PAPER_MARGIN / 5, 2,
4112                                                    LColor::depthbar);
4113                 }
4114         }
4115
4116         
4117         LyXLayout const & layout =
4118                 textclasslist.Style(bview->buffer()->params.textclass,
4119                                     row_ptr->par()->GetLayout());
4120
4121         y_top = 0;
4122         y_bottom = row_ptr->height();
4123         
4124         /* is it a first row? */ 
4125         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
4126                 
4127                 /* start of appendix? */
4128                 if (row_ptr->par()->start_of_appendix){
4129                         pain.line(1, y_offset,
4130                                   ww - 2, y_offset,
4131                                   LColor::appendixline);
4132                 }
4133                 
4134                 /* think about the margins */ 
4135                 if (!row_ptr->previous() && bv_owner)
4136                         y_top += LYX_PAPER_MARGIN;
4137                 
4138                 if (row_ptr->par()->pagebreak_top){ /* draw a top pagebreak  */
4139                         LyXFont pb_font;
4140                         pb_font.setColor(LColor::pagebreak).decSize();
4141                         int w = 0, a = 0, d = 0;
4142                         pain.line(0, y_offset + y_top + 2*DefaultHeight(),
4143                                   ww, 
4144                                   y_offset + y_top + 2 * DefaultHeight(),
4145                                   LColor::pagebreak, 
4146                                   Painter::line_onoffdash)
4147                                 .rectText(0,
4148                                           0,
4149                                           _("Page Break (top)"),
4150                                           pb_font,
4151                                           LColor::background,
4152                                           LColor::background, false, w, a, d);
4153                         pain.rectText((ww - w)/2,
4154                                       y_offset + y_top + 2 * DefaultHeight() + d,
4155                                       _("Page Break (top)"),
4156                                       pb_font,
4157                                       LColor::background,
4158                                       LColor::background);
4159                         y_top += 3 * DefaultHeight();
4160                 }
4161                 
4162                 if (row_ptr->par()->added_space_top.kind() == VSpace::VFILL) {
4163                         /* draw a vfill top  */
4164                         pain.line(0, y_offset + 2 + y_top,
4165                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
4166                                   LColor::vfillline);
4167                         
4168                         pain.line(0, y_offset + y_top + 3 * DefaultHeight(),
4169                                   LYX_PAPER_MARGIN,
4170                                   y_offset + y_top + 3 * DefaultHeight(),
4171                                   LColor::vfillline);
4172                         
4173                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
4174                                   LYX_PAPER_MARGIN / 2,
4175                                   y_offset + y_top + 3 * DefaultHeight(),
4176                                   LColor::vfillline);
4177                         
4178                         y_top += 3 * DefaultHeight();
4179                 }
4180                 
4181                 /* think about user added space */ 
4182                 y_top += int(row_ptr->par()->added_space_top.inPixels(bview));
4183                 
4184                 /* think about the parskip */ 
4185                 /* some parskips VERY EASY IMPLEMENTATION */ 
4186                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
4187                         if (layout.latextype == LATEX_PARAGRAPH
4188                             && firstpar->GetDepth() == 0
4189                             && firstpar->Previous())
4190                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4191                         else if (firstpar->Previous()
4192                                  && textclasslist.Style(bview->buffer()->params.textclass,
4193                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
4194                                  && firstpar->Previous()->GetDepth() == 0)
4195                                 // is it right to use defskip here, too? (AS) 
4196                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4197                 }
4198                 
4199                 if (row_ptr->par()->line_top) {      /* draw a top line  */
4200                         y_top +=  lyxfont::ascent('x',
4201                                                   GetFont(bview->buffer(),
4202                                                           row_ptr->par(), 0));
4203                         
4204                         pain.line(0, y_offset + y_top,
4205                                   ww, y_offset + y_top,
4206                                   LColor::topline,
4207                                   Painter::line_solid,
4208                                   Painter::line_thick);
4209                         
4210                         y_top +=  lyxfont::ascent('x',GetFont(bview->buffer(),
4211                                                               row_ptr->par(), 0));
4212                 }
4213                 
4214                 /* should we print a label? */ 
4215                 if (layout.labeltype >= LABEL_STATIC
4216                     && (layout.labeltype != LABEL_STATIC
4217                         || layout.latextype != LATEX_ENVIRONMENT
4218                         || row_ptr->par()->IsFirstInSequence())) {
4219                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4220                         if (!row_ptr->par()->GetLabelstring().empty()) {
4221                                 tmpx = x;
4222                                 string tmpstring = row_ptr->par()->GetLabelstring();
4223                                 
4224                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
4225                                         if (bview->buffer()->params.secnumdepth >= 0) {
4226                                                 /* this is special code for the chapter layout. This is printed in
4227                                                  * an extra row and has a pagebreak at the top. */
4228                                                 float spacing_val = 1.0;
4229                                                 if (!row_ptr->par()->spacing.isDefault()) {
4230                                                         spacing_val = row_ptr->par()->spacing.getValue();
4231                                                 } else {
4232                                                         spacing_val = bview->buffer()->params.spacing.getValue();
4233                                                 }
4234    
4235                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
4236                                                         + int(layout.parsep) * DefaultHeight();
4237                                                 if (is_rtl)
4238                                                         tmpx = ww - LeftMargin(bview, row_ptr) - 
4239                                                                 lyxfont::width(tmpstring, font);
4240                                                 pain.text(int(tmpx),
4241                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
4242                                                           tmpstring, font);
4243                                         }
4244                                 } else {
4245                                         if (is_rtl) {
4246                                                 tmpx = ww - LeftMargin(bview, row_ptr)
4247                                                         + lyxfont::width(layout.labelsep, font);
4248                                                 if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
4249                                                         LyXFont font(LyXFont::ALL_SANE);
4250                                                         font.setSize(LyXFont::SIZE_SMALL);
4251                                                         tmpx += lyxfont::width("Mwide-fixM", font);
4252                                                 }
4253                                         } else
4254                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4255                                                         - lyxfont::width(tmpstring, font);
4256
4257                                         /* draw it! */
4258                                         pain.text(int(tmpx),
4259                                                   y_offset + row_ptr->baseline(),
4260                                                   tmpstring, font);
4261                                 }
4262                         }
4263                         /* the labels at the top of an environment. More or less for bibliography */ 
4264                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
4265                            layout.labeltype == LABEL_BIBLIO ||
4266                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
4267                         if (row_ptr->par()->IsFirstInSequence()) {
4268                                 font = GetFont(bview->buffer(),
4269                                                row_ptr->par(), -2);
4270                                 if (!row_ptr->par()->GetLabelstring().empty()) {
4271                                         string tmpstring = row_ptr->par()->GetLabelstring();
4272                                         float spacing_val = 1.0;
4273                                         if (!row_ptr->par()->spacing.isDefault()) {
4274                                                 spacing_val = row_ptr->par()->spacing.getValue();
4275                                         } else {
4276                                                 spacing_val = bview->buffer()->params.spacing.getValue();
4277                                         }
4278    
4279                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
4280                                                       + (layout.labelbottomsep * DefaultHeight()));
4281                                         
4282                                         tmpx = x;
4283                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
4284                                                 tmpx = ( (is_rtl ? LeftMargin(bview, row_ptr) : x)
4285                                                          + ww - RightMargin(bview->buffer(), row_ptr) ) / 2; 
4286                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
4287                                         } else if (is_rtl)
4288                                                 tmpx = ww - LeftMargin(bview, row_ptr) - 
4289                                                         lyxfont::width(tmpstring, font);
4290                                         pain.text(int(tmpx),
4291                                                   y_offset + row_ptr->baseline()
4292                                                   - row_ptr->ascent_of_text()
4293                                                   - maxdesc,
4294                                                   tmpstring, font);
4295                                 }
4296                         }
4297                 }
4298                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
4299                         font = GetFont(bview->buffer(), row_ptr->par(), -1);
4300                         if (is_rtl)
4301                                 tmpx = ww - LeftMargin(bview, row_ptr)
4302                                         + lyxfont::width(layout.labelsep, font);
4303                         else
4304                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4305                                         - row_ptr->par()->bibkey->width(bview->painter(), font);
4306                         row_ptr->par()->bibkey->draw(pain,
4307                                                    font,
4308                                                    y_offset + row_ptr->baseline(), 
4309                                                    tmpx);
4310                 }
4311         }
4312         
4313         /* is it a last row? */
4314         LyXParagraph * par = row_ptr->par()->LastPhysicalPar();
4315         if ((row_ptr->par()->ParFromPos(last + 1) == par) &&
4316             (!row_ptr->next() || (row_ptr->next()->par() != row_ptr->par())))
4317         {
4318                 /* think about the margins */ 
4319                 if (!row_ptr->next() && bv_owner)
4320                         y_bottom -= LYX_PAPER_MARGIN;
4321                 
4322                 /* draw a bottom pagebreak */ 
4323                 if (firstpar->pagebreak_bottom) {
4324                         LyXFont pb_font;
4325                         pb_font.setColor(LColor::pagebreak).decSize();
4326                         int w = 0, a = 0, d = 0;
4327                         pain.line(0,
4328                                   y_offset + y_bottom - 2 * DefaultHeight(), 
4329                                   ww, 
4330                                   y_offset + y_bottom - 2 * DefaultHeight(),
4331                                   LColor::pagebreak,
4332                                   Painter::line_onoffdash)
4333                                 .rectText(0,
4334                                           0,
4335                                           _("Page Break (bottom)"),
4336                                           pb_font,
4337                                           LColor::background,
4338                                           LColor::background, false, w, a, d);
4339                         pain.rectText((ww - w) / 2,
4340                                       y_offset + y_top + 2 * DefaultHeight() + d,
4341                                       _("Page Break (bottom)"),
4342                                       pb_font,
4343                                       LColor::background,
4344                                       LColor::background);
4345                         y_bottom -= 3 * DefaultHeight();
4346                 }
4347                 
4348                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
4349                         /* draw a vfill bottom  */
4350                         pain.line(0, y_offset + y_bottom - 3 * DefaultHeight(),
4351                                   LYX_PAPER_MARGIN,
4352                                   y_offset + y_bottom - 3 * DefaultHeight(),
4353                                   LColor::vfillline);
4354                         pain.line(0, y_offset + y_bottom - 2,
4355                                   LYX_PAPER_MARGIN,
4356                                   y_offset + y_bottom - 2,
4357                                   LColor::vfillline);
4358                         pain.line(LYX_PAPER_MARGIN / 2,
4359                                   y_offset + y_bottom - 3 * DefaultHeight(),
4360                                   LYX_PAPER_MARGIN / 2,
4361                                   y_offset + y_bottom - 2,
4362                                   LColor::vfillline);
4363                         y_bottom -= 3 * DefaultHeight();
4364                 }
4365                 
4366                 /* think about user added space */ 
4367                 y_bottom -= int(firstpar->added_space_bottom.inPixels(bview));
4368                 
4369                 if (firstpar->line_bottom) {
4370                         /* draw a bottom line */
4371                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4372                                                                  par, par->Last() - 1));
4373                         pain.line(0, y_offset + y_bottom,
4374                                   ww, y_offset + y_bottom,
4375                                   LColor::topline, Painter::line_solid,
4376                                   Painter::line_thick);
4377                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4378                                                                  par, par->Last() - 1));
4379                 }
4380
4381                 // draw an endlabel
4382                 int endlabel = row_ptr->par()->GetEndLabel(bview->buffer()->params);
4383                 switch (endlabel) {
4384                 case END_LABEL_BOX:
4385                 case END_LABEL_FILLED_BOX:
4386                 {
4387                         LyXFont font = GetFont(bview->buffer(),
4388                                                row_ptr->par(), last);
4389                         int size = int(0.75 * lyxfont::maxAscent(font));
4390                         int y = (y_offset + row_ptr->baseline()) - size;
4391                         int x = is_rtl ? LYX_PAPER_MARGIN 
4392                                 : ww - LYX_PAPER_MARGIN - size;
4393                         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
4394                                 if (is_rtl) {
4395                                         LyXFont font(LyXFont::ALL_SANE);
4396                                         font.setSize(LyXFont::SIZE_SMALL);
4397                                         x += lyxfont::width("Mwide-figM", font);
4398                                 } else
4399                                         x -= LYX_PAPER_MARGIN/2;
4400                         if (row_ptr->fill() <= size)
4401                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
4402                         if (endlabel == END_LABEL_BOX) {
4403                                 pain.line(x, y, x, y + size,
4404                                           LColor::eolmarker);
4405                                 pain.line(x + size, y, x + size , y + size,
4406                                           LColor::eolmarker);
4407                                 pain.line(x, y, x + size, y,
4408                                           LColor::eolmarker);
4409                                 pain.line(x, y + size, x + size, y + size,
4410                                           LColor::eolmarker);
4411                         } else
4412                                 pain.fillRectangle(x, y, size, size,
4413                                                    LColor::eolmarker);
4414                         break;
4415                 }
4416                 case END_LABEL_STATIC:
4417                 {
4418                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->GetLayout();
4419                         string tmpstring = textclasslist.Style(bview->buffer()->params.textclass,
4420                                                          layout).endlabelstring();
4421                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4422                         int tmpx = is_rtl ? int(x) - lyxfont::width(tmpstring, font)
4423                                 : ww - RightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
4424                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
4425                         break;
4426                 }
4427                 case END_LABEL_NO_LABEL:
4428                         break;
4429                 }
4430         }
4431         
4432         /* draw the text in the pixmap */  
4433         
4434         vpos = row_ptr->pos();
4435 #ifndef NEW_TABULAR
4436         /* table stuff -- begin*/
4437         if (row_ptr->par()->table) {
4438                 bool on_off;
4439                 int cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
4440                 float x_old = x;
4441                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4442                 
4443                 while (vpos <= last)  {
4444                         pos = vis2log(vpos);
4445                         if (row_ptr->par()->IsNewline(pos)) {
4446                                 
4447                                 x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4448                                 /* draw the table lines, still very simple */
4449                                 on_off = !row_ptr->par()->table->TopLine(cell);
4450                                 if ((!on_off ||
4451                                      !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4452                                     !row_ptr->par()->table->IsContRow(cell))
4453                                         pain.line(int(x_old),
4454                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4455                                                   int(x),
4456                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4457                                                   LColor::tableline,
4458                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4459                                 
4460                                 on_off = !row_ptr->par()->table->BottomLine(cell);
4461                                 if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4462                                     row_ptr->par()->table->VeryLastRow(cell))
4463                                         
4464                                         pain.line(int(x_old),
4465                                                   y_offset + y_bottom - 1,
4466                                                   int(x),
4467                                                   y_offset + y_bottom - 1,
4468                                                   LColor::tableline,
4469                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4470                                 
4471                                 on_off = !row_ptr->par()->table->LeftLine(cell);
4472                                 
4473                                 pain.line(int(x_old),
4474                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4475                                           int(x_old),
4476                                           y_offset + y_bottom - 1,
4477                                           LColor::tableline,
4478                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4479                                 
4480                                 on_off = !row_ptr->par()->table->RightLine(cell);
4481                                 
4482                                 pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4483                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4484                                           int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4485                                           y_offset + y_bottom - 1,
4486                                           LColor::tableline,
4487                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4488                                 
4489                                 x_old = x;
4490                                 /* take care about the alignment and other spaces */
4491                                 ++cell;
4492                                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4493                                 if (row_ptr->par()->table->IsFirstCell(cell))
4494                                         --cell; // little hack, sorry
4495                                 ++vpos;
4496                         } else if (row_ptr->par()->IsHfill(pos)) {
4497                                 x += 1;
4498                                 
4499                                 pain.line(int(x),
4500                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4501                                           int(x),
4502                                           y_offset + row_ptr->baseline(),
4503                                           LColor::vfillline);
4504                                 
4505                                 x += 2;
4506                                 ++vpos;
4507                         } else if (row_ptr->par()->IsSeparator(pos)) {
4508                                 tmpx = x;
4509                                 x+= SingleWidth(bview, 
4510                                                 row_ptr->par(), pos);
4511                                 ++vpos;
4512                         } else
4513                                 draw(bview, row_ptr, vpos, y_offset, x);
4514                 }
4515                 
4516                 /* do not forget the very last cell. This has no NEWLINE so 
4517                  * ignored by the code above*/ 
4518                 if (cell == row_ptr->par()->table->GetNumberOfCells() - 1) {
4519                         x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4520                         on_off = !row_ptr->par()->table->TopLine(cell);
4521                         if ((!on_off ||
4522                              !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4523                             !row_ptr->par()->table->IsContRow(cell))
4524                                 
4525                                 pain.line(int(x_old),
4526                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4527                                           int(x),
4528                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4529                                           LColor::tableline,
4530                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4531                         on_off = !row_ptr->par()->table->BottomLine(cell);
4532                         if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4533                             row_ptr->par()->table->VeryLastRow(cell))
4534                                 
4535                                 pain.line(int(x_old),
4536                                           y_offset + y_bottom - 1,
4537                                           int(x),
4538                                           y_offset + y_bottom - 1,
4539                                           LColor::tableline,
4540                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4541                         
4542                         on_off = !row_ptr->par()->table->LeftLine(cell);
4543                         
4544                         pain.line(int(x_old),
4545                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4546                                   int(x_old),
4547                                   y_offset + y_bottom - 1,
4548                                   LColor::tableline,
4549                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4550                         
4551                         on_off = !row_ptr->par()->table->RightLine(cell);
4552                         
4553                         pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4554                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4555                                   int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4556                                   y_offset + y_bottom - 1,
4557                                   LColor::tableline,
4558                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4559                 }
4560         } else {
4561                 /* table stuff -- end*/
4562 #endif
4563                 LyXParagraph::size_type main_body = 
4564                         BeginningOfMainBody(bview->buffer(), row_ptr->par());
4565                 if (main_body > 0 &&
4566                     (main_body-1 > last || 
4567                      !row_ptr->par()->IsLineSeparator(main_body - 1)))
4568                         main_body = 0;
4569                 
4570                 while (vpos <= last)  {
4571                         pos = vis2log(vpos);
4572                         if (main_body > 0 && pos == main_body - 1) {
4573                                 x += fill_label_hfill
4574                                         + lyxfont::width(layout.labelsep,
4575                                                          GetFont(bview->buffer(),
4576                                                                  row_ptr->par(), -2))
4577                                         - SingleWidth(bview,
4578                                                       row_ptr->par(),
4579                                                       main_body - 1);
4580                         }
4581                         
4582                         if (row_ptr->par() ->IsHfill(pos)) {
4583                                 x += 1;
4584                                 pain.line(int(x),
4585                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4586                                           int(x),
4587                                           y_offset + row_ptr->baseline(),
4588                                           LColor::vfillline);
4589                                 
4590                                 if (HfillExpansion(bview->buffer(),
4591                                                    row_ptr, pos)) {
4592                                         if (pos >= main_body) {
4593                                                 pain.line(int(x),
4594                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4595                                                           int(x + fill_hfill),
4596                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4597                                                           LColor::vfillline,
4598                                                           Painter::line_onoffdash);
4599                                                 x += fill_hfill;
4600                                         } else {
4601                                                 pain.line(int(x),
4602                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4603                                                           int(x + fill_label_hfill),
4604                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4605                                                           LColor::vfillline,
4606                                                           Painter::line_onoffdash);
4607                                                 
4608                                                 x += fill_label_hfill;
4609                                         }
4610                                         pain.line(int(x),
4611                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4612                                                   int(x),
4613                                                   y_offset + row_ptr->baseline(),
4614                                                   LColor::vfillline);
4615                                 }
4616                                 x += 2;
4617                                 ++vpos;
4618                         } else if (row_ptr->par()->IsSeparator(pos)) {
4619                                 x += SingleWidth(bview,
4620                                                  row_ptr->par(), pos);
4621                                 if (pos >= main_body)
4622                                         x += fill_separator;
4623                                 ++vpos;
4624                         } else
4625                                 draw(bview, row_ptr, vpos, y_offset, x);
4626                 }
4627 #ifndef NEW_TABULAR
4628         }
4629 #endif
4630 }
4631
4632
4633 int LyXText::DefaultHeight() const
4634 {
4635         LyXFont font(LyXFont::ALL_SANE);
4636         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
4637 }
4638
4639    
4640 /* returns the column near the specified x-coordinate of the row 
4641 * x is set to the real beginning of this column  */ 
4642 int LyXText::GetColumnNearX(BufferView * bview, Row * row, int & x,
4643                             bool & boundary) const
4644 {
4645         float tmpx = 0.0;
4646         float fill_separator, fill_hfill, fill_label_hfill;
4647    
4648         PrepareToPrint(bview, row, tmpx, fill_separator,
4649                        fill_hfill, fill_label_hfill);
4650
4651         LyXParagraph::size_type vc = row->pos();
4652         LyXParagraph::size_type last = RowLastPrintable(row);
4653         LyXParagraph::size_type c = 0;
4654         LyXLayout const & layout =
4655                 textclasslist.Style(bview->buffer()->params.textclass,
4656                                     row->par()->GetLayout());
4657         bool left_side = false;
4658
4659 #ifndef NEW_TABULAR
4660         /* table stuff -- begin */
4661         if (row->par()->table) {
4662                 //the last row doesn't need a newline at the end
4663                 if (row->next() && row->next()->par() == row->par()
4664                     && row->par()->IsNewline(last))
4665                         --last;
4666                 int cell = NumberOfCell(row->par(), row->pos());
4667                 float cell_x = tmpx + row->par()->table->WidthOfColumn(cell);
4668                 tmpx += row->par()->table->GetBeginningOfTextInCell(cell);
4669                 float last_tmpx = tmpx;
4670                 while (vc <= last && tmpx <= x) {
4671                        c = vis2log(vc);
4672                        last_tmpx = tmpx;
4673                        if (row->par()->IsNewline(c)) {
4674                                if (cell_x <= x){
4675                                        ++cell;
4676                                        tmpx = cell_x + row->par()->table->GetBeginningOfTextInCell(cell);
4677                                        cell_x += row->par()->table->WidthOfColumn(cell);
4678                                        ++vc;
4679                                } else
4680                                        break;
4681                        } else {
4682                                tmpx += SingleWidth(bview, row->par(), c);
4683                                ++vc;
4684                        }
4685                 }
4686                 if (vc > row->pos() && !row->par()->IsNewline(c) &&
4687                     (tmpx + last_tmpx) / 2 > x) {
4688                         tmpx = last_tmpx;
4689                         left_side = true;
4690                 }
4691         } else {
4692                 /* table stuff -- end*/
4693 #endif
4694                 LyXParagraph::size_type
4695                         main_body = BeginningOfMainBody(bview->buffer(), row->par());
4696                 float last_tmpx = tmpx;
4697
4698                 if (main_body > 0 &&
4699                     (main_body-1 > last || 
4700                      !row->par()->IsLineSeparator(main_body - 1)))
4701                         main_body = 0;
4702
4703                 while (vc <= last && tmpx <= x) {
4704                         c = vis2log(vc);
4705                         last_tmpx = tmpx;
4706                         if (main_body > 0 && c == main_body-1) {
4707                                 tmpx += fill_label_hfill +
4708                                         lyxfont::width(layout.labelsep,
4709                                                GetFont(bview->buffer(), row->par(), -2));
4710                                 if (row->par()->IsLineSeparator(main_body - 1))
4711                                         tmpx -= SingleWidth(bview, row->par(), main_body-1);
4712                         }
4713              
4714                         if (HfillExpansion(bview->buffer(), row, c)) {
4715                                 x += SingleWidth(bview, row->par(), c);
4716                                 if (c >= main_body)
4717                                         tmpx += fill_hfill;
4718                                 else
4719                                         tmpx += fill_label_hfill;
4720                         }
4721                         else if (row->par()->IsSeparator(c)) {
4722                                 tmpx += SingleWidth(bview, row->par(), c);
4723                                 if (c >= main_body)
4724                                         tmpx+= fill_separator;
4725                         } else
4726                                 tmpx += SingleWidth(bview, row->par(), c);
4727                         ++vc;
4728                 }
4729
4730                 if (vc > row->pos() && (tmpx + last_tmpx) / 2 > x) {
4731                         tmpx = last_tmpx;
4732                         left_side = true;
4733                 }
4734 #ifndef NEW_TABULAR
4735         }
4736 #endif
4737
4738
4739         if (vc > last + 1)  // This shouldn't happen.
4740                 vc = last + 1;
4741
4742         boundary = false;
4743
4744         if (row->pos() > last)  // Row is empty?
4745                 c = row->pos();
4746         else if (vc == row->pos() ||
4747                  (row->par()->table
4748                   && vc <= last && row->par()->IsNewline(vc-1)) ) {
4749                 c = vis2log(vc);
4750                 if (bidi_level(c) % 2 == 1)
4751                         ++c;
4752         } else {
4753                 c = vis2log(vc - 1);
4754                 bool rtl = (bidi_level(c) % 2 == 1);
4755                 if (left_side == rtl) {
4756                         ++c;
4757                         boundary = IsBoundary(bview->buffer(), row->par(), c);
4758                 }
4759         }
4760
4761         if (!row->par()->table && row->pos() <= last && c > last
4762             && row->par()->IsNewline(last)) {
4763                 if (bidi_level(last) % 2 == 0)
4764                         tmpx -= SingleWidth(bview, row->par(), last);
4765                 else
4766                         tmpx += SingleWidth(bview, row->par(), last);
4767                 c = last;
4768         }
4769
4770         c -= row->pos();
4771         x = int(tmpx);
4772         return c;
4773 }
4774
4775    
4776 /* turn the selection into a new environment. If there is no selection,
4777 * create an empty environment */ 
4778 void LyXText::InsertFootnoteEnvironment(BufferView * bview, 
4779                                         LyXParagraph::footnote_kind kind)
4780 {
4781    /* no footnoteenvironment in a footnoteenvironment */ 
4782    if (cursor.par()->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4783       WriteAlert(_("Impossible operation"), 
4784                  _("You can't insert a float in a float!"), 
4785                  _("Sorry."));
4786      return;
4787    }
4788    /* no marginpars in minipages */
4789    if (kind == LyXParagraph::MARGIN 
4790       && cursor.par()->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
4791       WriteAlert(_("Impossible operation"), 
4792                  _("You can't insert a marginpar in a minipage!"), 
4793                  _("Sorry."));
4794       return;
4795    }
4796    
4797    /* this doesnt make sense, if there is no selection */ 
4798    bool dummy_selection = false;
4799    if (!selection) {
4800       sel_start_cursor = cursor;       /* dummy selection  */
4801       sel_end_cursor = cursor;
4802       dummy_selection = true;
4803    }
4804    
4805    LyXParagraph * tmppar;
4806
4807 #ifndef NEW_TABULAR
4808    if (sel_start_cursor.par()->table || sel_end_cursor.par()->table){
4809       WriteAlert(_("Impossible operation"), _("Cannot cut table."), _("Sorry."));
4810       return;
4811    }
4812 #endif
4813    /* a test to make sure there is not already a footnote
4814     * in the selection. */
4815    
4816    tmppar = sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos());
4817    
4818    while (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos()) && 
4819           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
4820      tmppar = tmppar->next;
4821    
4822    if (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())
4823        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4824       WriteAlert(_("Impossible operation"), 
4825                  _("Float would include float!"), 
4826                  _("Sorry."));
4827       return;
4828    }
4829    
4830    /* ok we have a selection. This is always between sel_start_cursor
4831     * and sel_end cursor */
4832
4833    SetUndo(bview->buffer(), Undo::FINISH, 
4834            sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos())->previous, 
4835            sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())->next); 
4836    
4837    if (sel_end_cursor.pos() > 0 
4838        && sel_end_cursor.par()->IsLineSeparator(sel_end_cursor.pos() - 1))
4839            sel_end_cursor.pos(sel_end_cursor.pos() - 1);
4840    /* please break before a space at the end */
4841    if (sel_start_cursor.par() == sel_end_cursor.par()
4842        && sel_start_cursor.pos() > sel_end_cursor.pos())
4843            sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4844
4845    sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, sel_end_cursor.pos());
4846    
4847    sel_end_cursor.par(sel_end_cursor.par()->Next());
4848    sel_end_cursor.pos(0);
4849    
4850    // don't forget to insert a dummy layout paragraph if necessary
4851    if (sel_start_cursor.par()->GetLayout() != sel_end_cursor.par()->layout){
4852      sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, 0);
4853      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4854      sel_end_cursor.par(sel_end_cursor.par()->next);
4855    }
4856    else
4857      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4858
4859    cursor = sel_end_cursor;
4860
4861    /* please break behind a space, if there is one. The space should
4862     * be erased too */ 
4863    if (sel_start_cursor.pos() > 0 
4864        && sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos() - 1))
4865      sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4866    if (sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos())) {
4867       sel_start_cursor.par()->Erase(sel_start_cursor.pos());
4868    }
4869    
4870    sel_start_cursor.par()->BreakParagraphConservative(bview->buffer()->params,
4871                                                     sel_start_cursor.pos());
4872    tmppar = sel_start_cursor.par()->Next();
4873    
4874    if (dummy_selection) {
4875            tmppar->Clear();
4876            if (kind == LyXParagraph::TAB
4877                || kind == LyXParagraph::FIG 
4878                || kind == LyXParagraph::WIDE_TAB
4879                || kind == LyXParagraph::WIDE_FIG 
4880                || kind == LyXParagraph::ALGORITHM) {
4881                    pair<bool, LyXTextClass::size_type> lres =
4882                            textclasslist.NumberOfLayout(bview->buffer()->params.textclass,
4883                                                         "Caption");
4884                    LyXTextClass::size_type lay;
4885                    if (lres.first) {
4886                            // layout fount
4887                            lay = lres.second;
4888                    } else {
4889                            // layout not found
4890                            lay = 0; // use default layout "Standard" (0)
4891                    }
4892                    tmppar->SetLayout(bview->buffer()->params, lay);
4893            }
4894    } else {
4895      if (sel_start_cursor.pos() > 0) {
4896        /* the footnote-environment should begin with a standard layout.
4897         * Imagine you insert a footnote within an enumeration, you 
4898         * certainly do not want an enumerated footnote! */ 
4899        tmppar->Clear();
4900      } else {
4901        /* this is a exception the user would sometimes expect, I hope */
4902        sel_start_cursor.par()->Clear();
4903      }
4904    }
4905    
4906    while (tmppar != sel_end_cursor.par()) {
4907       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
4908       tmppar->footnotekind = kind;
4909       tmppar = tmppar->Next();
4910    }
4911
4912    RedoParagraphs(bview, sel_start_cursor, sel_end_cursor.par()->Next());
4913    
4914    SetCursor(bview, sel_start_cursor.par()->Next(), 0);
4915
4916    ClearSelection();
4917 }
4918    
4919
4920 // returns pointer to a specified row
4921 Row * LyXText::GetRow(LyXParagraph * par,
4922                       LyXParagraph::size_type pos, long & y) const
4923 {
4924         Row * tmprow = firstrow;
4925         y = 0;
4926         
4927         // find the first row of the specified paragraph
4928         while (tmprow->next() && tmprow->par() != par) {
4929                 y += tmprow->height();
4930                 tmprow = tmprow->next();
4931         }
4932         
4933         // now find the wanted row
4934         while (tmprow->pos() < pos
4935                && tmprow->next()
4936                && tmprow->next()->par() == par
4937                && tmprow->next()->pos() <= pos) {
4938                 y += tmprow->height();
4939                 tmprow = tmprow->next();
4940         }
4941         
4942         return tmprow;
4943 }