]> git.lyx.org Git - lyx.git/blob - src/text.C
Various fixes in insettext/tabular to make update work selective.
[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 "insets/insettext.h"
26 #include "lyx_gui_misc.h"
27 #include "gettext.h"
28 #include "bufferparams.h"
29 #include "buffer.h"
30 #include "minibuffer.h"
31 #include "debug.h"
32 #include "lyxrc.h"
33 #include "LyXView.h"
34 #include "lyxrow.h"
35 #include "Painter.h"
36 #include "tracer.h"
37 #include "font.h"
38
39 using std::max;
40 using std::min;
41 using std::endl;
42 using std::pair;
43
44 static const int LYX_PAPER_MARGIN = 20;
45 extern int bibitemMaxWidth(Painter &, LyXFont const &);
46
47 static int iso885968x[] = {
48         0xbc,   // 0xa8 = fathatan
49         0xbd,   // 0xa9 = dammatan
50         0xbe,   // 0xaa = kasratan
51         0xdb,   // 0xab = fatha
52         0xdc,   // 0xac = damma
53         0xdd,   // 0xad = kasra
54         0xde,   // 0xae = shadda
55         0xdf,   // 0xaf = sukun
56
57         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xb0-0xbf
58
59         0,      // 0xc0 
60         0xc1,   // 0xc1 = hamza
61         0xc2,   // 0xc2 = ligature madda
62         0xc3,   // 0xc3 = ligature hamza on alef
63         0xc4,   // 0xc4 = ligature hamza on waw
64         0xc5,   // 0xc5 = ligature hamza under alef
65         0xc0,   // 0xc6 = ligature hamza on ya 
66         0xc7,   // 0xc7 = alef
67         0xeb,   // 0xc8 = baa 
68         0xc9,   // 0xc9 = taa marbuta
69         0xec,   // 0xca = taa
70         0xed,   // 0xcb = thaa
71         0xee,   // 0xcc = jeem
72         0xef,   // 0xcd = haa
73         0xf0,   // 0xce = khaa
74         0xcf,   // 0xcf = dal
75
76         0xd0,   // 0xd0 = thal
77         0xd1,   // 0xd1 = ra
78         0xd2,   // 0xd2 = zain
79         0xf1,   // 0xd3 = seen
80         0xf2,   // 0xd4 = sheen
81         0xf3,   // 0xd5 = sad
82         0xf4,   // 0xd6 = dad
83         0xd7,   // 0xd7 = tah
84         0xd8,   // 0xd8 = zah
85         0xf5,   // 0xd9 = ain
86         0xf6,   // 0xda = ghain
87         0,0,0,0,0, // 0xdb- 0xdf
88
89         0,      // 0xe0
90         0xf7,   // 0xe1 = fa
91         0xf8,   // 0xe2 = qaf
92         0xf9,   // 0xe3 = kaf
93         0xfa,   // 0xe4 = lam
94         0xfb,   // 0xe5 = meem
95         0xfc,   // 0xe6 = noon
96         0xfd,   // 0xe7 = ha
97         0xe8,   // 0xe8 = waw
98         0xe9,   // 0xe9 = alef maksura
99         0xfe    // 0xea = ya
100 };
101
102
103 inline
104 bool is_arabic(unsigned char c)
105 {
106         return 0xa8 <= c && c <= 0xea && iso885968x[c-0xa8];
107 }
108
109
110 inline
111 bool is_nikud(unsigned char c)
112 {
113         return 192 <= c && c <= 210;
114 }
115
116
117 int LyXText::workWidth(BufferView * bview) const
118 {
119         if (inset_owner) {
120 #if 1
121                 return inset_owner->getMaxWidth(bview->painter(), inset_owner);
122 #else
123                 LyXFont font(LyXFont::ALL_SANE);
124                 return inset_owner->width(bview->painter(), font);
125 #endif
126         }
127         return bview->workWidth();
128 }
129
130 unsigned char LyXText::TransformChar(unsigned char c, Letter_Form form) const
131 {
132         if (is_arabic(c) && 
133             (form == FORM_INITIAL || form == FORM_MEDIAL) )
134                 return iso885968x[c-0xa8];
135         else
136                 return c;
137 }
138
139
140 unsigned char LyXText::TransformChar(unsigned char c, LyXParagraph * par,
141                         LyXParagraph::size_type pos) const
142 {
143         if (!is_arabic(c))
144                 if (isdigit(c))
145                         return c + (0xb0 - '0');
146                 else
147                         return c;
148
149         bool not_first = (pos > 0 && is_arabic(par->GetChar(pos-1)));
150         if (pos < par->Last()-1 && is_arabic(par->GetChar(pos+1)))
151                 if (not_first)
152                         return TransformChar(c,FORM_MEDIAL);
153                 else
154                         return TransformChar(c,FORM_INITIAL);
155         else
156                 if (not_first)
157                         return TransformChar(c,FORM_FINAL);
158                 else
159                         return TransformChar(c,FORM_ISOLATED);
160 }
161
162 // This is the comments that some of the warnings below refers to.
163 // There are some issues in this file and I don't think they are
164 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
165 // this is a problem that has been here almost from day one and that a
166 // larger userbase with differenct access patters triggers the bad
167 // behaviour. (segfaults.) What I think happen is: In several places
168 // we store the paragraph in the current cursor and then moves the
169 // cursor. This movement of the cursor will delete paragraph at the
170 // old position if it is now empty. This will make the temporary
171 // pointer to the old cursor paragraph invalid and dangerous to use.
172 // And is some cases this will trigger a segfault. I have marked some
173 // of the cases where this happens with a warning, but I am sure there
174 // are others in this file and in text2.C. There is also a note in
175 // Delete() that you should read. In Delete I store the paragraph->id
176 // instead of a pointer to the paragraph. I am pretty sure this faulty
177 // use of temporary pointers to paragraphs that might have gotten
178 // invalidated (through a cursor movement) before they are used, are
179 // the cause of the strange crashes we get reported often.
180 //
181 // It is very tiresom to change this code, especially when it is as
182 // hard to read as it is. Help to fix all the cases where this is done
183 // would be greately appreciated.
184 //
185 // Lgb
186
187 int LyXText::SingleWidth(BufferView * bview, LyXParagraph * par,
188                          LyXParagraph::size_type pos) const
189 {
190         char c = par->GetChar(pos);
191         return SingleWidth(bview, par, pos, c);
192 }
193
194
195 int LyXText::SingleWidth(BufferView * bview, LyXParagraph * par,
196                          LyXParagraph::size_type pos, char c) const
197 {
198         LyXFont font = GetFont(bview->buffer(), par, pos);
199
200         // The most common case is handled first (Asger)
201         if (IsPrintable(c)) {
202                 if (font.language()->RightToLeft()) {
203                         if (font.language()->lang() == "arabic" &&
204                             lyxrc.font_norm == "iso8859-6.8x")
205                                 c = TransformChar(c, par, pos);
206                         else if (font.language()->lang() == "hebrew" &&
207                                  is_nikud(c))
208                                 return 0;
209                 }
210                 return lyxfont::width(c, font);
211
212         } else if (IsHfillChar(c)) {
213                 return 3;       /* Because of the representation
214                                  * as vertical lines */
215         } else if (c == LyXParagraph::META_FOOTNOTE ||
216                    c == LyXParagraph::META_MARGIN ||
217                    c == LyXParagraph::META_FIG ||
218                    c == LyXParagraph::META_TAB ||
219                    c == LyXParagraph::META_WIDE_FIG ||
220                    c == LyXParagraph::META_WIDE_TAB ||
221                    c == LyXParagraph::META_ALGORITHM) {
222                 string fs;
223                 switch (c) {
224                 case LyXParagraph::META_MARGIN:
225                         fs = "margin";
226                         break;
227                 case LyXParagraph::META_FIG:
228                         fs = "fig";
229                         break;
230                 case LyXParagraph::META_TAB:
231                         fs = "tab";
232                         break;
233                 case LyXParagraph::META_ALGORITHM:
234                         fs = "alg";
235                         break;
236                 case LyXParagraph::META_WIDE_FIG:
237                         fs = "wide-fig";
238                         break;
239                 case LyXParagraph::META_WIDE_TAB:
240                         fs = "wide-tab";
241                         break;
242                 case LyXParagraph::META_FOOTNOTE:
243                         fs = "foot";
244                         break;
245                 }
246                 font.decSize();
247                 font.decSize();
248                 return lyxfont::width(fs, font);
249         } else if (c == LyXParagraph::META_INSET) {
250                 Inset * tmpinset = par->GetInset(pos);
251                 if (tmpinset) {
252                         tmpinset->update(bview, font);
253                         return tmpinset->width(bview->painter(), font);
254                 } else
255                         return 0;
256
257         } else if (IsSeparatorChar(c))
258                 c = ' ';
259         else if (IsNewlineChar(c))
260                 c = 'n';
261         return lyxfont::width(c, font);
262 }
263
264
265 // Returns the paragraph position of the last character in the specified row
266 LyXParagraph::size_type LyXText::RowLast(Row const * row) const
267 {
268         if (row->next() == 0)
269                 return row->par()->Last() - 1;
270         else if (row->next()->par() != row->par()) 
271                 return row->par()->Last() - 1;
272         else 
273                 return row->next()->pos() - 1;
274 }
275
276
277 LyXParagraph::size_type LyXText::RowLastPrintable(Row const * row) const
278 {
279         LyXParagraph::size_type last = RowLast(row);
280         if (last >= row->pos()
281             && row->next()
282             && row->next()->par() == row->par()
283             && row->par()->IsSeparator(last))
284                 return last - 1;
285         else
286                 return last;
287 }
288
289
290 void LyXText::ComputeBidiTables(Buffer const * buf, Row * row) const
291 {
292         bidi_same_direction = true;
293         if (!lyxrc.rtl_support) {
294                 bidi_start = -1;
295                 return;
296         }
297
298         bidi_start = row->pos();
299         bidi_end = RowLastPrintable(row);
300
301         if (bidi_start > bidi_end) {
302                 bidi_start = -1;
303                 return;
304         }
305
306         if (bidi_end + 2 - bidi_start >
307             static_cast<LyXParagraph::size_type>(log2vis_list.size())) {
308                 LyXParagraph::size_type new_size = 
309                         (bidi_end + 2 - bidi_start < 500) ?
310                         500 : 2 * (bidi_end + 2 - bidi_start);
311                 log2vis_list.resize(new_size);
312                 vis2log_list.resize(new_size);
313                 bidi_levels.resize(new_size);
314         }
315
316         vis2log_list[bidi_end + 1 - bidi_start] = -1;
317         log2vis_list[bidi_end + 1 - bidi_start] = -1;
318
319         LyXParagraph::size_type stack[2];
320         bool rtl_par = row->par()->getParLanguage(buf->params)->RightToLeft();
321         int level = 0;
322         bool rtl = false;
323         bool rtl0 = false;
324         LyXParagraph::size_type main_body = BeginningOfMainBody(buf, row->par());
325
326         for (LyXParagraph::size_type lpos = bidi_start;
327              lpos <= bidi_end; ++lpos) {
328                 bool is_space = row->par()->IsLineSeparator(lpos);
329                 LyXParagraph::size_type pos =
330                         (is_space && lpos + 1 <= bidi_end &&
331                          !row->par()->IsLineSeparator(lpos + 1) &&
332                          (!row->par()->table
333                           || !row->par()->IsNewline(lpos + 1)) )
334                         ? lpos + 1 : lpos;
335                 LyXFont font = row->par()->GetFontSettings(buf->params, pos);
336                 bool new_rtl = font.isVisibleRightToLeft();
337                 bool new_rtl0 = font.isRightToLeft();
338                 int new_level;
339
340 #ifndef NEW_TABULAR
341                 if (row->par()->table && row->par()->IsNewline(lpos)) {
342                         new_level = 0;
343                         new_rtl = new_rtl0 = false;
344                 } else
345 #endif
346                         if (lpos == main_body - 1
347                            && row->pos() < main_body - 1
348                            && row->par()->IsLineSeparator(lpos)) {
349                         new_level = (rtl_par) ? 1 : 0;
350                         new_rtl = new_rtl0 = rtl_par;
351                 } else if (new_rtl0)
352                         new_level = (new_rtl) ? 1 : 2;
353                 else
354                         new_level = (rtl_par) ? 2 : 0;
355
356                 if (is_space && new_level >= level) {
357                         new_level = level;
358                         new_rtl = rtl;
359                         new_rtl0 = rtl0;
360                 }
361
362                 int new_level2 = new_level;
363
364                 if (level == new_level && rtl0 != new_rtl0) {
365                         --new_level2;
366                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
367                 } else if (level < new_level) {
368                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
369                         if (new_level > rtl_par)
370                                 bidi_same_direction = false;
371                 } else
372                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
373                 rtl = new_rtl;
374                 rtl0 = new_rtl0;
375                 bidi_levels[lpos - bidi_start] = new_level;
376
377                 while (level > new_level2) {
378                         LyXParagraph::size_type old_lpos =
379                                 stack[--level];
380                         int delta = lpos - old_lpos - 1;
381                         if (level % 2)
382                                 delta = -delta;
383                         log2vis_list[lpos - bidi_start] += delta;
384                         log2vis_list[old_lpos - bidi_start] += delta;
385                 }
386                 while (level < new_level)
387                         stack[level++] = lpos;
388         }
389
390         while (level > 0) {
391                 LyXParagraph::size_type old_lpos = stack[--level];
392                 int delta = bidi_end - old_lpos;
393                 if (level % 2)
394                         delta = -delta;
395                 log2vis_list[old_lpos - bidi_start] += delta;
396         }
397
398         LyXParagraph::size_type vpos = bidi_start - 1;
399         for (LyXParagraph::size_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
400                 vpos += log2vis_list[lpos - bidi_start];
401                 vis2log_list[vpos - bidi_start] = lpos;
402                 log2vis_list[lpos - bidi_start] = vpos;
403         }
404 }
405
406
407 // This method requires a previous call to ComputeBidiTables()
408 bool LyXText::IsBoundary(Buffer const * buf, LyXParagraph * par,
409                          LyXParagraph::size_type pos) const
410 {
411         if (!lyxrc.rtl_support)
412                 return false;    // This is just for speedup
413
414         if (!bidi_InRange(pos - 1) ||
415             (par->table && par->IsNewline(pos-1)) )
416                 return false;
417
418         bool rtl = bidi_level(pos - 1) % 2;
419         bool rtl2 = rtl;
420         if (pos == par->Last() ||
421             (par->table && par->IsNewline(pos)))
422                 rtl2 = par->isRightToLeftPar(buf->params);
423         else if (bidi_InRange(pos))
424                 rtl2 = bidi_level(pos) % 2;
425         return rtl != rtl2;
426 }
427
428 bool LyXText::IsBoundary(Buffer const * buf, LyXParagraph * par,
429                          LyXParagraph::size_type pos,
430                          LyXFont const & font) const
431 {
432         if (!lyxrc.rtl_support)
433                 return false;    // This is just for speedup
434
435         bool rtl = font.isVisibleRightToLeft();
436         bool rtl2 = rtl;
437         if (pos == par->Last() ||
438             (par->table && par->IsNewline(pos)))
439                 rtl2 = par->isRightToLeftPar(buf->params);
440         else if (bidi_InRange(pos))
441                 rtl2 =  bidi_level(pos) % 2;
442         return rtl != rtl2;
443 }
444
445
446 void LyXText::draw(BufferView * bview, Row const * row,
447                    LyXParagraph::size_type & vpos,
448                    int offset, float & x)
449 {
450         Painter & pain = bview->painter();
451         
452         LyXParagraph::size_type pos = vis2log(vpos);
453         char c = row->par()->GetChar(pos);
454         float tmpx = x;
455
456         if (IsNewlineChar(c)) {
457                 ++vpos;
458                 // Draw end-of-line marker
459                 LyXFont font = GetFont(bview->buffer(), row->par(), pos);
460                 int wid = lyxfont::width('n', font);
461                 int asc = lyxfont::maxAscent(font);
462                 int y = offset + row->baseline();
463                 int xp[3], yp[3];
464                 
465                 if (bidi_level(pos) % 2 == 0) {
466                         xp[0] = int(x + wid * 0.375);
467                         yp[0] = int(y - 0.875 * asc * 0.75);
468                         
469                         xp[1] = int(x);
470                         yp[1] = int(y - 0.500 * asc * 0.75);
471                         
472                         xp[2] = int(x + wid * 0.375);
473                         yp[2] = int(y - 0.125 * asc * 0.75);
474                         
475                         pain.lines(xp, yp, 3, LColor::eolmarker);
476                         
477                         xp[0] = int(x);
478                         yp[0] = int(y - 0.500 * asc * 0.75);
479                         
480                         xp[1] = int(x + wid);
481                         yp[1] = int(y - 0.500 * asc * 0.75);
482                         
483                         xp[2] = int(x + wid);
484                         yp[2] = int(y - asc * 0.75);
485                         
486                         pain.lines(xp, yp, 3, LColor::eolmarker);
487                 } else {
488                         xp[0] = int(x + wid * 0.625);
489                         yp[0] = int(y - 0.875 * asc * 0.75);
490                         
491                         xp[1] = int(x + wid);
492                         yp[1] = int(y - 0.500 * asc * 0.75);
493                         
494                         xp[2] = int(x + wid * 0.625);
495                         yp[2] = int(y - 0.125 * asc * 0.75);
496                         
497                         pain.lines(xp, yp, 3, LColor::eolmarker);
498                         
499                         xp[0] = int(x + wid);
500                         yp[0] = int(y - 0.500 * asc * 0.75);
501                         
502                         xp[1] = int(x);
503                         yp[1] = int(y - 0.500 * asc * 0.75);
504                         
505                         xp[2] = int(x);
506                         yp[2] = int(y - asc * 0.75);
507                         
508                         pain.lines(xp, yp, 3, LColor::eolmarker);
509                 }
510                 x += wid;
511                 return;
512         }
513
514         LyXFont font = GetFont(bview->buffer(), row->par(), pos);
515         LyXFont font2 = font;
516
517         if (c == LyXParagraph::META_FOOTNOTE
518             || c == LyXParagraph::META_MARGIN
519             || c == LyXParagraph::META_FIG
520             || c == LyXParagraph::META_TAB
521             || c == LyXParagraph::META_WIDE_FIG
522             || c == LyXParagraph::META_WIDE_TAB
523             || c == LyXParagraph::META_ALGORITHM) {
524                 string fs;
525                 switch (c) {
526                 case LyXParagraph::META_MARGIN:
527                         fs = "margin";
528                         break;
529                 case LyXParagraph::META_FIG:
530                         fs = "fig";
531                         break;
532                 case LyXParagraph::META_TAB:
533                         fs = "tab";
534                         break;
535                 case LyXParagraph::META_ALGORITHM:
536                         fs = "alg";
537                         break;
538                 case LyXParagraph::META_WIDE_FIG:
539                         fs = "wide-fig";
540                         break;
541                 case LyXParagraph::META_WIDE_TAB:
542                         fs = "wide-tab";
543                         break;
544                 case LyXParagraph::META_FOOTNOTE:
545                         fs = "foot";
546                         break;
547                 }
548                 font.decSize();
549                 font.decSize();
550           
551                 // calculate the position of the footnotemark
552                 int y = (row->baseline() - lyxfont::maxAscent(font2) 
553                          + lyxfont::maxAscent(font));
554           
555                 font.setColor(LColor::footnote);
556
557                 // draw it and set new x position
558                 
559                 pain.text(int(x), offset + y, fs, font);
560                 x += lyxfont::width(fs, font);
561                 pain.line(int(tmpx), offset + row->baseline(),
562                           int(x), offset + row->baseline(),
563                           LColor::footnote);
564
565                 ++vpos;
566                 return;
567         } else if (c == LyXParagraph::META_INSET) {
568                 Inset const * tmpinset = row->par()->GetInset(pos);
569                 if (tmpinset) {
570                         tmpinset->draw(bview, font, 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(LyXFont::ALL_SANE);
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;
3797         if (inset_owner)
3798                 ww = inset_owner->width(bview->painter(), font) - 1;
3799         else
3800                 ww = bview->workWidth();
3801
3802         bool clear_area = true;
3803
3804         if ((last == row_ptr->pos()) &&
3805             row_ptr->par()->GetInset(row_ptr->pos())) {
3806                 clear_area = row_ptr->par()->GetInset(row_ptr->pos())->doClearArea();
3807         }
3808         if (bv_owner && clear_area)
3809                 pain.fillRectangle(x_offset, y_offset, ww, row_ptr->height());
3810         
3811         if (selection) {
3812                 /* selection code */
3813                 if (bidi_same_direction) {
3814                         if (sel_start_cursor.row() == row_ptr &&
3815                             sel_end_cursor.row() == row_ptr) {
3816                                 if (sel_start_cursor.x() < sel_end_cursor.x())
3817                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3818                                                            y_offset,
3819                                                            sel_end_cursor.x() - sel_start_cursor.x(),
3820                                                            row_ptr->height(),
3821                                                            LColor::selection);
3822                                 else
3823                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3824                                                            y_offset,
3825                                                            sel_start_cursor.x() - sel_end_cursor.x(),
3826                                                            row_ptr->height(),
3827                                                            LColor::selection);
3828                         } else if (sel_start_cursor.row() == row_ptr) {
3829                                 if (is_rtl)
3830                                         pain.fillRectangle(x_offset, y_offset,
3831                                                            sel_start_cursor.x(),
3832                                                            row_ptr->height(),
3833                                                            LColor::selection);
3834                                 else
3835                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3836                                                            y_offset,
3837                                                            ww - sel_start_cursor.x(),
3838                                                            row_ptr->height(),
3839                                                            LColor::selection);
3840                         } else if (sel_end_cursor.row() == row_ptr) {
3841                                 if (is_rtl)
3842                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3843                                                            y_offset,
3844                                                            ww - sel_end_cursor.x(),
3845                                                            row_ptr->height(),
3846                                                            LColor::selection);
3847                                 else
3848                                         pain.fillRectangle(x_offset, y_offset,
3849                                                            sel_end_cursor.x(),
3850                                                            row_ptr->height(),
3851                                                            LColor::selection);
3852                         } else if (y > long(sel_start_cursor.y())
3853                                    && y < long(sel_end_cursor.y())) {
3854                                 pain.fillRectangle(x_offset, y_offset, ww,
3855                                                    row_ptr->height(),
3856                                                    LColor::selection);
3857                         }
3858                 } else if ( sel_start_cursor.row() != row_ptr &&
3859                             sel_end_cursor.row() != row_ptr &&
3860                             y > long(sel_start_cursor.y())
3861                             && y < long(sel_end_cursor.y())) {
3862                         pain.fillRectangle(x_offset, y_offset, ww,
3863                                            row_ptr->height(),
3864                                            LColor::selection);
3865                 } else if (sel_start_cursor.row() == row_ptr ||
3866                            sel_end_cursor.row() == row_ptr) {
3867                         float tmpx = x;
3868                         int cell = 0;
3869 #ifndef NEW_TABULAR
3870                         if (row_ptr->par()->table) {
3871                                 cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
3872                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3873                         }
3874 #endif
3875                         if ( (sel_start_cursor.row() != row_ptr && !is_rtl) ||
3876                              (sel_end_cursor.row() != row_ptr && is_rtl))
3877                                 pain.fillRectangle(x_offset, y_offset,
3878                                                    int(tmpx),
3879                                                    row_ptr->height(),
3880                                                    LColor::selection);
3881 #ifndef NEW_TABULAR
3882                         if (row_ptr->par()->table) {
3883                                 float x_old = x;
3884                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3885                                         pos = vis2log(vpos);
3886                                         float old_tmpx = tmpx;
3887                                         if (row_ptr->par()->IsNewline(pos)) {
3888                                                 tmpx = x_old + row_ptr->par()->table->WidthOfColumn(cell);
3889                                                 x_old = tmpx;
3890                                                 ++cell;
3891                                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3892                                         } else {
3893                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3894                                         }
3895                                         if ( (sel_start_cursor.row() != row_ptr ||
3896                                               sel_start_cursor.pos() <= pos) &&
3897                                              (sel_end_cursor.row() != row_ptr ||
3898                                               pos < sel_end_cursor.pos()) )
3899                                                 pain.fillRectangle(x_offset + int(old_tmpx),
3900                                                                    y_offset,
3901                                                                    int(tmpx - old_tmpx + 1),
3902                                                                    row_ptr->height(),
3903                                                                    LColor::selection);
3904                                 }
3905                         } else {
3906 #endif
3907                                 LyXParagraph::size_type main_body =
3908                                         BeginningOfMainBody(bview->buffer(),
3909                                                             row_ptr->par());
3910
3911                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3912                                         pos = vis2log(vpos);
3913                                         float old_tmpx = tmpx;
3914                                         if (main_body > 0 && pos == main_body-1) {
3915                                                 tmpx += fill_label_hfill +
3916                                                         lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
3917                                                                                            row_ptr->par()->GetLayout()).labelsep,
3918                                                                        GetFont(bview->buffer(),row_ptr->par(), -2));
3919                                                 if (row_ptr->par()->IsLineSeparator(main_body-1))
3920                                                         tmpx -= SingleWidth(bview, row_ptr->par(), main_body-1);
3921                                         }
3922                                         if (HfillExpansion(bview->buffer(), row_ptr, pos)) {
3923                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3924                                                 if (pos >= main_body)
3925                                                         tmpx += fill_hfill;
3926                                                 else 
3927                                                         tmpx += fill_label_hfill;
3928                                         }
3929                                         else if (row_ptr->par()->IsSeparator(pos)) {
3930                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3931                                                 if (pos >= main_body)
3932                                                         tmpx += fill_separator;
3933                                         } else
3934                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3935
3936                                         if ( (sel_start_cursor.row() != row_ptr ||
3937                                               sel_start_cursor.pos() <= pos) &&
3938                                              (sel_end_cursor.row() != row_ptr ||
3939                                               pos < sel_end_cursor.pos()) )
3940                                                 pain.fillRectangle(x_offset + int(old_tmpx),
3941                                                                    y_offset,
3942                                                                    int(tmpx - old_tmpx + 1),
3943                                                                    row_ptr->height(),
3944                                                                    LColor::selection);
3945                                 }
3946 #ifndef NEW_TABULAR
3947                         }
3948 #endif
3949                         if ( (sel_start_cursor.row() != row_ptr && is_rtl) ||
3950                              (sel_end_cursor.row() != row_ptr && !is_rtl) )
3951                                 pain.fillRectangle(x_offset + int(tmpx),
3952                                                    y_offset,
3953                                                    int(ww - tmpx),
3954                                                    row_ptr->height(),
3955                                                    LColor::selection);
3956                 }
3957         }
3958
3959         int box_x = 0;
3960         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
3961                 LyXFont font(LyXFont::ALL_SANE);
3962                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3963                 font.setColor(LColor::footnote);
3964                 
3965                 box_x = LYX_PAPER_MARGIN + lyxfont::width(" wide-tab ", font);
3966                 if (row_ptr->previous() &&
3967                     row_ptr->previous()->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
3968                         string fs;
3969                         switch (row_ptr->par()->footnotekind) {
3970                         case LyXParagraph::MARGIN:
3971                                 fs = " margin";
3972                                 break;
3973                         case LyXParagraph::FIG:
3974                                 fs = " fig";
3975                                 break;
3976                         case LyXParagraph::TAB:
3977                                 fs = " tab";
3978                                 break;
3979                         case LyXParagraph::WIDE_FIG:
3980                                 fs = " wide-fig";
3981                                 break;
3982                         case LyXParagraph::WIDE_TAB:
3983                                 fs = " wide-tab";
3984                                 break;
3985                         case LyXParagraph::ALGORITHM:
3986                                 fs = " alg";
3987                                 break;
3988                         case LyXParagraph::FOOTNOTE:
3989                                 fs = " foot";
3990                                 break;
3991                         }
3992                         
3993                         pain.fillRectangle(LYX_PAPER_MARGIN,
3994                                            y_offset + 1,
3995                                            box_x - LYX_PAPER_MARGIN,
3996                                            int(lyxfont::maxAscent(font)
3997                                                + lyxfont::maxDescent(font)),
3998                                            LColor::footnotebg);
3999                         
4000                         pain.line(LYX_PAPER_MARGIN, y_offset,
4001                                   workWidth(bview) - LYX_PAPER_MARGIN, y_offset,
4002                                   LColor::footnoteframe);
4003                         
4004                         pain.text(LYX_PAPER_MARGIN,
4005                                   y_offset + int(lyxfont::maxAscent(font)) + 1,
4006                                   fs, font);
4007                         
4008                         pain.line(LYX_PAPER_MARGIN, y_offset,
4009                                   LYX_PAPER_MARGIN,
4010                                   y_offset + int(lyxfont::maxAscent(font)
4011                                                + lyxfont::maxDescent(font)),
4012                                   LColor::footnoteframe);
4013                         
4014                         pain.line(LYX_PAPER_MARGIN,
4015                                   y_offset + int(lyxfont::maxAscent(font)
4016                                                + lyxfont::maxDescent(font)) + 1,
4017                                   box_x,
4018                                   y_offset + int(lyxfont::maxAscent(font)
4019                                                + lyxfont::maxDescent(font)) + 1,
4020                                   LColor::footnoteframe);
4021                         
4022                 }
4023                 
4024                 /* draw the open floats in a red box */
4025                 pain.line(box_x, y_offset,
4026                           box_x, y_offset + row_ptr->height(),
4027                           LColor::footnoteframe);
4028                 
4029                 pain.line(workWidth(bview) - LYX_PAPER_MARGIN,
4030                           y_offset,
4031                           workWidth(bview) - LYX_PAPER_MARGIN,
4032                           y_offset + row_ptr->height(),
4033                           LColor::footnoteframe);
4034
4035
4036                 // Draw appendix lines
4037                 LyXParagraph * p = row_ptr->par()->PreviousBeforeFootnote()->FirstPhysicalPar();
4038                 if (p->appendix){
4039                         pain.line(1, y_offset,
4040                                   1, y_offset + row_ptr->height(),
4041                                   LColor::appendixline);
4042                         pain.line(workWidth(bview) - 2, y_offset,
4043                                   workWidth(bview) - 2,
4044                                   y_offset + row_ptr->height(),
4045                                   LColor::appendixline);
4046                 }
4047
4048                 // Draw minipage line
4049                 bool minipage = p->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4050                 if (minipage)
4051                         pain.line(LYX_PAPER_MARGIN/5, y_offset,
4052                                   LYX_PAPER_MARGIN/5, 
4053                                   y_offset + row_ptr->height() - 1,
4054                                   LColor::minipageline);
4055
4056                 // Draw depth lines
4057                 int depth = p->GetDepth();
4058                 for (int i = 1; i <= depth; ++i) {
4059                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage);
4060                         pain.line(line_x, y_offset, line_x,
4061                                   y_offset + row_ptr->height() - 1,
4062                                   LColor::depthbar);
4063                 }
4064         } else if (row_ptr->previous() &&
4065                    row_ptr->previous()->par()->footnoteflag
4066                    == LyXParagraph::OPEN_FOOTNOTE) {
4067                 LyXFont font(LyXFont::ALL_SANE);
4068                 font.setSize(LyXFont::SIZE_FOOTNOTE);
4069                 
4070                 int box_x = LYX_PAPER_MARGIN;
4071                 box_x += lyxfont::width(" wide-tab ", font);
4072                 
4073                 pain.line(box_x, y_offset,
4074                           workWidth(bview) - LYX_PAPER_MARGIN,
4075                           y_offset, LColor::footnote);
4076         }
4077
4078         // Draw appendix lines
4079         LyXParagraph * firstpar = row_ptr->par()->FirstPhysicalPar();
4080         if (firstpar->appendix){
4081                 pain.line(1, y_offset,
4082                           1, y_offset + row_ptr->height(),
4083                           LColor::appendixline);
4084                 pain.line(ww - 2, y_offset,
4085                           ww - 2, y_offset + row_ptr->height(),
4086                           LColor::appendixline);
4087         }
4088
4089         // Draw minipage line
4090         bool minipage = firstpar->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4091         if (minipage)
4092                 pain.line(LYX_PAPER_MARGIN/5 + box_x, y_offset,
4093                           LYX_PAPER_MARGIN/5 + box_x, 
4094                           y_offset + row_ptr->height() - 1,
4095                           LColor::minipageline);
4096
4097         // Draw depth lines
4098         int depth = firstpar->GetDepth();
4099         if (depth > 0) {
4100                 int next_depth = 0;
4101                 int prev_depth = 0;
4102                 if (row_ptr->next())
4103                         if (row_ptr->par()->footnoteflag ==
4104                             row_ptr->next()->par()->footnoteflag)
4105                                 next_depth = row_ptr->next()->par()->GetDepth();
4106                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4107                                 next_depth = depth;
4108
4109                 if (row_ptr->previous())
4110                         if (row_ptr->par()->footnoteflag ==
4111                             row_ptr->previous()->par()->footnoteflag)
4112                                 prev_depth = row_ptr->previous()->par()->GetDepth();
4113                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4114                                 prev_depth = depth;
4115
4116                 for (int i = 1; i <= depth; ++i) {
4117                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage) + box_x;
4118                         pain.line(line_x, y_offset, line_x,
4119                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
4120                                   LColor::depthbar);
4121                 
4122                         if (i > prev_depth)
4123                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
4124                                                    LColor::depthbar);
4125                         if (i > next_depth)
4126                                 pain.fillRectangle(line_x,
4127                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
4128                                                    LYX_PAPER_MARGIN / 5, 2,
4129                                                    LColor::depthbar);
4130                 }
4131         }
4132
4133         
4134         LyXLayout const & layout =
4135                 textclasslist.Style(bview->buffer()->params.textclass,
4136                                     row_ptr->par()->GetLayout());
4137
4138         y_top = 0;
4139         y_bottom = row_ptr->height();
4140         
4141         /* is it a first row? */ 
4142         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
4143                 
4144                 /* start of appendix? */
4145                 if (row_ptr->par()->start_of_appendix){
4146                         pain.line(1, y_offset,
4147                                   ww - 2, y_offset,
4148                                   LColor::appendixline);
4149                 }
4150                 
4151                 /* think about the margins */ 
4152                 if (!row_ptr->previous() && bv_owner)
4153                         y_top += LYX_PAPER_MARGIN;
4154                 
4155                 if (row_ptr->par()->pagebreak_top){ /* draw a top pagebreak  */
4156                         LyXFont pb_font;
4157                         pb_font.setColor(LColor::pagebreak).decSize();
4158                         int w = 0, a = 0, d = 0;
4159                         pain.line(0, y_offset + y_top + 2*DefaultHeight(),
4160                                   ww, 
4161                                   y_offset + y_top + 2 * DefaultHeight(),
4162                                   LColor::pagebreak, 
4163                                   Painter::line_onoffdash)
4164                                 .rectText(0,
4165                                           0,
4166                                           _("Page Break (top)"),
4167                                           pb_font,
4168                                           LColor::background,
4169                                           LColor::background, false, w, a, d);
4170                         pain.rectText((ww - w)/2,
4171                                       y_offset + y_top + 2 * DefaultHeight() + d,
4172                                       _("Page Break (top)"),
4173                                       pb_font,
4174                                       LColor::background,
4175                                       LColor::background);
4176                         y_top += 3 * DefaultHeight();
4177                 }
4178                 
4179                 if (row_ptr->par()->added_space_top.kind() == VSpace::VFILL) {
4180                         /* draw a vfill top  */
4181                         pain.line(0, y_offset + 2 + y_top,
4182                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
4183                                   LColor::vfillline);
4184                         
4185                         pain.line(0, y_offset + y_top + 3 * DefaultHeight(),
4186                                   LYX_PAPER_MARGIN,
4187                                   y_offset + y_top + 3 * DefaultHeight(),
4188                                   LColor::vfillline);
4189                         
4190                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
4191                                   LYX_PAPER_MARGIN / 2,
4192                                   y_offset + y_top + 3 * DefaultHeight(),
4193                                   LColor::vfillline);
4194                         
4195                         y_top += 3 * DefaultHeight();
4196                 }
4197                 
4198                 /* think about user added space */ 
4199                 y_top += int(row_ptr->par()->added_space_top.inPixels(bview));
4200                 
4201                 /* think about the parskip */ 
4202                 /* some parskips VERY EASY IMPLEMENTATION */ 
4203                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
4204                         if (layout.latextype == LATEX_PARAGRAPH
4205                             && firstpar->GetDepth() == 0
4206                             && firstpar->Previous())
4207                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4208                         else if (firstpar->Previous()
4209                                  && textclasslist.Style(bview->buffer()->params.textclass,
4210                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
4211                                  && firstpar->Previous()->GetDepth() == 0)
4212                                 // is it right to use defskip here, too? (AS) 
4213                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4214                 }
4215                 
4216                 if (row_ptr->par()->line_top) {      /* draw a top line  */
4217                         y_top +=  lyxfont::ascent('x',
4218                                                   GetFont(bview->buffer(),
4219                                                           row_ptr->par(), 0));
4220                         
4221                         pain.line(0, y_offset + y_top,
4222                                   ww, y_offset + y_top,
4223                                   LColor::topline,
4224                                   Painter::line_solid,
4225                                   Painter::line_thick);
4226                         
4227                         y_top +=  lyxfont::ascent('x',GetFont(bview->buffer(),
4228                                                               row_ptr->par(), 0));
4229                 }
4230                 
4231                 /* should we print a label? */ 
4232                 if (layout.labeltype >= LABEL_STATIC
4233                     && (layout.labeltype != LABEL_STATIC
4234                         || layout.latextype != LATEX_ENVIRONMENT
4235                         || row_ptr->par()->IsFirstInSequence())) {
4236                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4237                         if (!row_ptr->par()->GetLabelstring().empty()) {
4238                                 tmpx = x;
4239                                 string tmpstring = row_ptr->par()->GetLabelstring();
4240                                 
4241                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
4242                                         if (bview->buffer()->params.secnumdepth >= 0) {
4243                                                 /* this is special code for the chapter layout. This is printed in
4244                                                  * an extra row and has a pagebreak at the top. */
4245                                                 float spacing_val = 1.0;
4246                                                 if (!row_ptr->par()->spacing.isDefault()) {
4247                                                         spacing_val = row_ptr->par()->spacing.getValue();
4248                                                 } else {
4249                                                         spacing_val = bview->buffer()->params.spacing.getValue();
4250                                                 }
4251    
4252                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
4253                                                         + int(layout.parsep) * DefaultHeight();
4254                                                 if (is_rtl)
4255                                                         tmpx = ww - LeftMargin(bview, row_ptr) - 
4256                                                                 lyxfont::width(tmpstring, font);
4257                                                 pain.text(int(tmpx),
4258                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
4259                                                           tmpstring, font);
4260                                         }
4261                                 } else {
4262                                         if (is_rtl) {
4263                                                 tmpx = ww - LeftMargin(bview, row_ptr)
4264                                                         + lyxfont::width(layout.labelsep, font);
4265                                                 if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
4266                                                         LyXFont font(LyXFont::ALL_SANE);
4267                                                         font.setSize(LyXFont::SIZE_SMALL);
4268                                                         tmpx += lyxfont::width("Mwide-fixM", font);
4269                                                 }
4270                                         } else
4271                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4272                                                         - lyxfont::width(tmpstring, font);
4273
4274                                         /* draw it! */
4275                                         pain.text(int(tmpx),
4276                                                   y_offset + row_ptr->baseline(),
4277                                                   tmpstring, font);
4278                                 }
4279                         }
4280                         /* the labels at the top of an environment. More or less for bibliography */ 
4281                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
4282                            layout.labeltype == LABEL_BIBLIO ||
4283                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
4284                         if (row_ptr->par()->IsFirstInSequence()) {
4285                                 font = GetFont(bview->buffer(),
4286                                                row_ptr->par(), -2);
4287                                 if (!row_ptr->par()->GetLabelstring().empty()) {
4288                                         string tmpstring = row_ptr->par()->GetLabelstring();
4289                                         float spacing_val = 1.0;
4290                                         if (!row_ptr->par()->spacing.isDefault()) {
4291                                                 spacing_val = row_ptr->par()->spacing.getValue();
4292                                         } else {
4293                                                 spacing_val = bview->buffer()->params.spacing.getValue();
4294                                         }
4295    
4296                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
4297                                                       + (layout.labelbottomsep * DefaultHeight()));
4298                                         
4299                                         tmpx = x;
4300                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
4301                                                 tmpx = ( (is_rtl ? LeftMargin(bview, row_ptr) : x)
4302                                                          + ww - RightMargin(bview->buffer(), row_ptr) ) / 2; 
4303                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
4304                                         } else if (is_rtl)
4305                                                 tmpx = ww - LeftMargin(bview, row_ptr) - 
4306                                                         lyxfont::width(tmpstring, font);
4307                                         pain.text(int(tmpx),
4308                                                   y_offset + row_ptr->baseline()
4309                                                   - row_ptr->ascent_of_text()
4310                                                   - maxdesc,
4311                                                   tmpstring, font);
4312                                 }
4313                         }
4314                 }
4315                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
4316                         font = GetFont(bview->buffer(), row_ptr->par(), -1);
4317                         if (is_rtl)
4318                                 tmpx = ww - LeftMargin(bview, row_ptr)
4319                                         + lyxfont::width(layout.labelsep, font);
4320                         else
4321                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4322                                         - row_ptr->par()->bibkey->width(bview->painter(), font);
4323                         row_ptr->par()->bibkey->draw(bview, font,
4324                                                    y_offset + row_ptr->baseline(), 
4325                                                    tmpx);
4326                 }
4327         }
4328         
4329         /* is it a last row? */
4330         LyXParagraph * par = row_ptr->par()->LastPhysicalPar();
4331         if ((row_ptr->par()->ParFromPos(last + 1) == par) &&
4332             (!row_ptr->next() || (row_ptr->next()->par() != row_ptr->par())))
4333         {
4334                 /* think about the margins */ 
4335                 if (!row_ptr->next() && bv_owner)
4336                         y_bottom -= LYX_PAPER_MARGIN;
4337                 
4338                 /* draw a bottom pagebreak */ 
4339                 if (firstpar->pagebreak_bottom) {
4340                         LyXFont pb_font;
4341                         pb_font.setColor(LColor::pagebreak).decSize();
4342                         int w = 0, a = 0, d = 0;
4343                         pain.line(0,
4344                                   y_offset + y_bottom - 2 * DefaultHeight(), 
4345                                   ww, 
4346                                   y_offset + y_bottom - 2 * DefaultHeight(),
4347                                   LColor::pagebreak,
4348                                   Painter::line_onoffdash)
4349                                 .rectText(0,
4350                                           0,
4351                                           _("Page Break (bottom)"),
4352                                           pb_font,
4353                                           LColor::background,
4354                                           LColor::background, false, w, a, d);
4355                         pain.rectText((ww - w) / 2,
4356                                       y_offset + y_top + 2 * DefaultHeight() + d,
4357                                       _("Page Break (bottom)"),
4358                                       pb_font,
4359                                       LColor::background,
4360                                       LColor::background);
4361                         y_bottom -= 3 * DefaultHeight();
4362                 }
4363                 
4364                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
4365                         /* draw a vfill bottom  */
4366                         pain.line(0, y_offset + y_bottom - 3 * DefaultHeight(),
4367                                   LYX_PAPER_MARGIN,
4368                                   y_offset + y_bottom - 3 * DefaultHeight(),
4369                                   LColor::vfillline);
4370                         pain.line(0, y_offset + y_bottom - 2,
4371                                   LYX_PAPER_MARGIN,
4372                                   y_offset + y_bottom - 2,
4373                                   LColor::vfillline);
4374                         pain.line(LYX_PAPER_MARGIN / 2,
4375                                   y_offset + y_bottom - 3 * DefaultHeight(),
4376                                   LYX_PAPER_MARGIN / 2,
4377                                   y_offset + y_bottom - 2,
4378                                   LColor::vfillline);
4379                         y_bottom -= 3 * DefaultHeight();
4380                 }
4381                 
4382                 /* think about user added space */ 
4383                 y_bottom -= int(firstpar->added_space_bottom.inPixels(bview));
4384                 
4385                 if (firstpar->line_bottom) {
4386                         /* draw a bottom line */
4387                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4388                                                                  par, par->Last() - 1));
4389                         pain.line(0, y_offset + y_bottom,
4390                                   ww, y_offset + y_bottom,
4391                                   LColor::topline, Painter::line_solid,
4392                                   Painter::line_thick);
4393                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4394                                                                  par, par->Last() - 1));
4395                 }
4396
4397                 // draw an endlabel
4398                 int endlabel = row_ptr->par()->GetEndLabel(bview->buffer()->params);
4399                 switch (endlabel) {
4400                 case END_LABEL_BOX:
4401                 case END_LABEL_FILLED_BOX:
4402                 {
4403                         LyXFont font = GetFont(bview->buffer(),
4404                                                row_ptr->par(), last);
4405                         int size = int(0.75 * lyxfont::maxAscent(font));
4406                         int y = (y_offset + row_ptr->baseline()) - size;
4407                         int x = is_rtl ? LYX_PAPER_MARGIN 
4408                                 : ww - LYX_PAPER_MARGIN - size;
4409                         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
4410                                 if (is_rtl) {
4411                                         LyXFont font(LyXFont::ALL_SANE);
4412                                         font.setSize(LyXFont::SIZE_SMALL);
4413                                         x += lyxfont::width("Mwide-figM", font);
4414                                 } else
4415                                         x -= LYX_PAPER_MARGIN/2;
4416                         if (row_ptr->fill() <= size)
4417                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
4418                         if (endlabel == END_LABEL_BOX) {
4419                                 pain.line(x, y, x, y + size,
4420                                           LColor::eolmarker);
4421                                 pain.line(x + size, y, x + size , y + size,
4422                                           LColor::eolmarker);
4423                                 pain.line(x, y, x + size, y,
4424                                           LColor::eolmarker);
4425                                 pain.line(x, y + size, x + size, y + size,
4426                                           LColor::eolmarker);
4427                         } else
4428                                 pain.fillRectangle(x, y, size, size,
4429                                                    LColor::eolmarker);
4430                         break;
4431                 }
4432                 case END_LABEL_STATIC:
4433                 {
4434                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->GetLayout();
4435                         string tmpstring = textclasslist.Style(bview->buffer()->params.textclass,
4436                                                          layout).endlabelstring();
4437                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4438                         int tmpx = is_rtl ? int(x) - lyxfont::width(tmpstring, font)
4439                                 : ww - RightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
4440                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
4441                         break;
4442                 }
4443                 case END_LABEL_NO_LABEL:
4444                         break;
4445                 }
4446         }
4447         
4448         /* draw the text in the pixmap */  
4449         
4450         vpos = row_ptr->pos();
4451 #ifndef NEW_TABULAR
4452         /* table stuff -- begin*/
4453         if (row_ptr->par()->table) {
4454                 bool on_off;
4455                 int cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
4456                 float x_old = x;
4457                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4458                 
4459                 while (vpos <= last)  {
4460                         pos = vis2log(vpos);
4461                         if (row_ptr->par()->IsNewline(pos)) {
4462                                 
4463                                 x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4464                                 /* draw the table lines, still very simple */
4465                                 on_off = !row_ptr->par()->table->TopLine(cell);
4466                                 if ((!on_off ||
4467                                      !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4468                                     !row_ptr->par()->table->IsContRow(cell))
4469                                         pain.line(int(x_old),
4470                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4471                                                   int(x),
4472                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4473                                                   LColor::tableline,
4474                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4475                                 
4476                                 on_off = !row_ptr->par()->table->BottomLine(cell);
4477                                 if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4478                                     row_ptr->par()->table->VeryLastRow(cell))
4479                                         
4480                                         pain.line(int(x_old),
4481                                                   y_offset + y_bottom - 1,
4482                                                   int(x),
4483                                                   y_offset + y_bottom - 1,
4484                                                   LColor::tableline,
4485                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4486                                 
4487                                 on_off = !row_ptr->par()->table->LeftLine(cell);
4488                                 
4489                                 pain.line(int(x_old),
4490                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4491                                           int(x_old),
4492                                           y_offset + y_bottom - 1,
4493                                           LColor::tableline,
4494                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4495                                 
4496                                 on_off = !row_ptr->par()->table->RightLine(cell);
4497                                 
4498                                 pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4499                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4500                                           int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4501                                           y_offset + y_bottom - 1,
4502                                           LColor::tableline,
4503                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4504                                 
4505                                 x_old = x;
4506                                 /* take care about the alignment and other spaces */
4507                                 ++cell;
4508                                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4509                                 if (row_ptr->par()->table->IsFirstCell(cell))
4510                                         --cell; // little hack, sorry
4511                                 ++vpos;
4512                         } else if (row_ptr->par()->IsHfill(pos)) {
4513                                 x += 1;
4514                                 
4515                                 pain.line(int(x),
4516                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4517                                           int(x),
4518                                           y_offset + row_ptr->baseline(),
4519                                           LColor::vfillline);
4520                                 
4521                                 x += 2;
4522                                 ++vpos;
4523                         } else if (row_ptr->par()->IsSeparator(pos)) {
4524                                 tmpx = x;
4525                                 x+= SingleWidth(bview, 
4526                                                 row_ptr->par(), pos);
4527                                 ++vpos;
4528                         } else
4529                                 draw(bview, row_ptr, vpos, y_offset, x);
4530                 }
4531                 
4532                 /* do not forget the very last cell. This has no NEWLINE so 
4533                  * ignored by the code above*/ 
4534                 if (cell == row_ptr->par()->table->GetNumberOfCells() - 1) {
4535                         x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4536                         on_off = !row_ptr->par()->table->TopLine(cell);
4537                         if ((!on_off ||
4538                              !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4539                             !row_ptr->par()->table->IsContRow(cell))
4540                                 
4541                                 pain.line(int(x_old),
4542                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4543                                           int(x),
4544                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4545                                           LColor::tableline,
4546                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4547                         on_off = !row_ptr->par()->table->BottomLine(cell);
4548                         if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4549                             row_ptr->par()->table->VeryLastRow(cell))
4550                                 
4551                                 pain.line(int(x_old),
4552                                           y_offset + y_bottom - 1,
4553                                           int(x),
4554                                           y_offset + y_bottom - 1,
4555                                           LColor::tableline,
4556                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4557                         
4558                         on_off = !row_ptr->par()->table->LeftLine(cell);
4559                         
4560                         pain.line(int(x_old),
4561                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4562                                   int(x_old),
4563                                   y_offset + y_bottom - 1,
4564                                   LColor::tableline,
4565                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4566                         
4567                         on_off = !row_ptr->par()->table->RightLine(cell);
4568                         
4569                         pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4570                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4571                                   int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4572                                   y_offset + y_bottom - 1,
4573                                   LColor::tableline,
4574                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4575                 }
4576         } else {
4577                 /* table stuff -- end*/
4578 #endif
4579                 LyXParagraph::size_type main_body = 
4580                         BeginningOfMainBody(bview->buffer(), row_ptr->par());
4581                 if (main_body > 0 &&
4582                     (main_body-1 > last || 
4583                      !row_ptr->par()->IsLineSeparator(main_body - 1)))
4584                         main_body = 0;
4585                 
4586                 while (vpos <= last)  {
4587                         pos = vis2log(vpos);
4588                         if (main_body > 0 && pos == main_body - 1) {
4589                                 x += fill_label_hfill
4590                                         + lyxfont::width(layout.labelsep,
4591                                                          GetFont(bview->buffer(),
4592                                                                  row_ptr->par(), -2))
4593                                         - SingleWidth(bview,
4594                                                       row_ptr->par(),
4595                                                       main_body - 1);
4596                         }
4597                         
4598                         if (row_ptr->par() ->IsHfill(pos)) {
4599                                 x += 1;
4600                                 pain.line(int(x),
4601                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4602                                           int(x),
4603                                           y_offset + row_ptr->baseline(),
4604                                           LColor::vfillline);
4605                                 
4606                                 if (HfillExpansion(bview->buffer(),
4607                                                    row_ptr, pos)) {
4608                                         if (pos >= main_body) {
4609                                                 pain.line(int(x),
4610                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4611                                                           int(x + fill_hfill),
4612                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4613                                                           LColor::vfillline,
4614                                                           Painter::line_onoffdash);
4615                                                 x += fill_hfill;
4616                                         } else {
4617                                                 pain.line(int(x),
4618                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4619                                                           int(x + fill_label_hfill),
4620                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4621                                                           LColor::vfillline,
4622                                                           Painter::line_onoffdash);
4623                                                 
4624                                                 x += fill_label_hfill;
4625                                         }
4626                                         pain.line(int(x),
4627                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4628                                                   int(x),
4629                                                   y_offset + row_ptr->baseline(),
4630                                                   LColor::vfillline);
4631                                 }
4632                                 x += 2;
4633                                 ++vpos;
4634                         } else if (row_ptr->par()->IsSeparator(pos)) {
4635                                 x += SingleWidth(bview,
4636                                                  row_ptr->par(), pos);
4637                                 if (pos >= main_body)
4638                                         x += fill_separator;
4639                                 ++vpos;
4640                         } else
4641                                 draw(bview, row_ptr, vpos, y_offset, x);
4642                 }
4643 #ifndef NEW_TABULAR
4644         }
4645 #endif
4646 }
4647
4648
4649 int LyXText::DefaultHeight() const
4650 {
4651         LyXFont font(LyXFont::ALL_SANE);
4652         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
4653 }
4654
4655    
4656 /* returns the column near the specified x-coordinate of the row 
4657 * x is set to the real beginning of this column  */ 
4658 int LyXText::GetColumnNearX(BufferView * bview, Row * row, int & x,
4659                             bool & boundary) const
4660 {
4661         float tmpx = 0.0;
4662         float fill_separator, fill_hfill, fill_label_hfill;
4663    
4664         PrepareToPrint(bview, row, tmpx, fill_separator,
4665                        fill_hfill, fill_label_hfill);
4666
4667         LyXParagraph::size_type vc = row->pos();
4668         LyXParagraph::size_type last = RowLastPrintable(row);
4669         LyXParagraph::size_type c = 0;
4670         LyXLayout const & layout =
4671                 textclasslist.Style(bview->buffer()->params.textclass,
4672                                     row->par()->GetLayout());
4673         bool left_side = false;
4674
4675 #ifndef NEW_TABULAR
4676         /* table stuff -- begin */
4677         if (row->par()->table) {
4678                 //the last row doesn't need a newline at the end
4679                 if (row->next() && row->next()->par() == row->par()
4680                     && row->par()->IsNewline(last))
4681                         --last;
4682                 int cell = NumberOfCell(row->par(), row->pos());
4683                 float cell_x = tmpx + row->par()->table->WidthOfColumn(cell);
4684                 tmpx += row->par()->table->GetBeginningOfTextInCell(cell);
4685                 float last_tmpx = tmpx;
4686                 while (vc <= last && tmpx <= x) {
4687                        c = vis2log(vc);
4688                        last_tmpx = tmpx;
4689                        if (row->par()->IsNewline(c)) {
4690                                if (cell_x <= x){
4691                                        ++cell;
4692                                        tmpx = cell_x + row->par()->table->GetBeginningOfTextInCell(cell);
4693                                        cell_x += row->par()->table->WidthOfColumn(cell);
4694                                        ++vc;
4695                                } else
4696                                        break;
4697                        } else {
4698                                tmpx += SingleWidth(bview, row->par(), c);
4699                                ++vc;
4700                        }
4701                 }
4702                 if (vc > row->pos() && !row->par()->IsNewline(c) &&
4703                     (tmpx + last_tmpx) / 2 > x) {
4704                         tmpx = last_tmpx;
4705                         left_side = true;
4706                 }
4707         } else {
4708                 /* table stuff -- end*/
4709 #endif
4710                 LyXParagraph::size_type
4711                         main_body = BeginningOfMainBody(bview->buffer(), row->par());
4712                 float last_tmpx = tmpx;
4713
4714                 if (main_body > 0 &&
4715                     (main_body-1 > last || 
4716                      !row->par()->IsLineSeparator(main_body - 1)))
4717                         main_body = 0;
4718
4719                 while (vc <= last && tmpx <= x) {
4720                         c = vis2log(vc);
4721                         last_tmpx = tmpx;
4722                         if (main_body > 0 && c == main_body-1) {
4723                                 tmpx += fill_label_hfill +
4724                                         lyxfont::width(layout.labelsep,
4725                                                GetFont(bview->buffer(), row->par(), -2));
4726                                 if (row->par()->IsLineSeparator(main_body - 1))
4727                                         tmpx -= SingleWidth(bview, row->par(), main_body-1);
4728                         }
4729              
4730                         if (HfillExpansion(bview->buffer(), row, c)) {
4731                                 x += SingleWidth(bview, row->par(), c);
4732                                 if (c >= main_body)
4733                                         tmpx += fill_hfill;
4734                                 else
4735                                         tmpx += fill_label_hfill;
4736                         }
4737                         else if (row->par()->IsSeparator(c)) {
4738                                 tmpx += SingleWidth(bview, row->par(), c);
4739                                 if (c >= main_body)
4740                                         tmpx+= fill_separator;
4741                         } else
4742                                 tmpx += SingleWidth(bview, row->par(), c);
4743                         ++vc;
4744                 }
4745
4746                 if (vc > row->pos() && (tmpx + last_tmpx) / 2 > x) {
4747                         tmpx = last_tmpx;
4748                         left_side = true;
4749                 }
4750 #ifndef NEW_TABULAR
4751         }
4752 #endif
4753
4754
4755         if (vc > last + 1)  // This shouldn't happen.
4756                 vc = last + 1;
4757
4758         boundary = false;
4759
4760         if (row->pos() > last)  // Row is empty?
4761                 c = row->pos();
4762         else if (vc == row->pos() ||
4763                  (row->par()->table
4764                   && vc <= last && row->par()->IsNewline(vc-1)) ) {
4765                 c = vis2log(vc);
4766                 if (bidi_level(c) % 2 == 1)
4767                         ++c;
4768         } else {
4769                 c = vis2log(vc - 1);
4770                 bool rtl = (bidi_level(c) % 2 == 1);
4771                 if (left_side == rtl) {
4772                         ++c;
4773                         boundary = IsBoundary(bview->buffer(), row->par(), c);
4774                 }
4775         }
4776
4777         if (!row->par()->table && row->pos() <= last && c > last
4778             && row->par()->IsNewline(last)) {
4779                 if (bidi_level(last) % 2 == 0)
4780                         tmpx -= SingleWidth(bview, row->par(), last);
4781                 else
4782                         tmpx += SingleWidth(bview, row->par(), last);
4783                 c = last;
4784         }
4785
4786         c -= row->pos();
4787         x = int(tmpx);
4788         return c;
4789 }
4790
4791    
4792 /* turn the selection into a new environment. If there is no selection,
4793 * create an empty environment */ 
4794 void LyXText::InsertFootnoteEnvironment(BufferView * bview, 
4795                                         LyXParagraph::footnote_kind kind)
4796 {
4797    /* no footnoteenvironment in a footnoteenvironment */ 
4798    if (cursor.par()->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4799       WriteAlert(_("Impossible operation"), 
4800                  _("You can't insert a float in a float!"), 
4801                  _("Sorry."));
4802      return;
4803    }
4804    /* no marginpars in minipages */
4805    if (kind == LyXParagraph::MARGIN 
4806       && cursor.par()->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
4807       WriteAlert(_("Impossible operation"), 
4808                  _("You can't insert a marginpar in a minipage!"), 
4809                  _("Sorry."));
4810       return;
4811    }
4812    
4813    /* this doesnt make sense, if there is no selection */ 
4814    bool dummy_selection = false;
4815    if (!selection) {
4816       sel_start_cursor = cursor;       /* dummy selection  */
4817       sel_end_cursor = cursor;
4818       dummy_selection = true;
4819    }
4820    
4821    LyXParagraph * tmppar;
4822
4823 #ifndef NEW_TABULAR
4824    if (sel_start_cursor.par()->table || sel_end_cursor.par()->table){
4825       WriteAlert(_("Impossible operation"), _("Cannot cut table."), _("Sorry."));
4826       return;
4827    }
4828 #endif
4829    /* a test to make sure there is not already a footnote
4830     * in the selection. */
4831    
4832    tmppar = sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos());
4833    
4834    while (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos()) && 
4835           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
4836      tmppar = tmppar->next;
4837    
4838    if (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())
4839        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4840       WriteAlert(_("Impossible operation"), 
4841                  _("Float would include float!"), 
4842                  _("Sorry."));
4843       return;
4844    }
4845    
4846    /* ok we have a selection. This is always between sel_start_cursor
4847     * and sel_end cursor */
4848
4849    SetUndo(bview->buffer(), Undo::FINISH, 
4850            sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos())->previous, 
4851            sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())->next); 
4852    
4853    if (sel_end_cursor.pos() > 0 
4854        && sel_end_cursor.par()->IsLineSeparator(sel_end_cursor.pos() - 1))
4855            sel_end_cursor.pos(sel_end_cursor.pos() - 1);
4856    /* please break before a space at the end */
4857    if (sel_start_cursor.par() == sel_end_cursor.par()
4858        && sel_start_cursor.pos() > sel_end_cursor.pos())
4859            sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4860
4861    sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, sel_end_cursor.pos());
4862    
4863    sel_end_cursor.par(sel_end_cursor.par()->Next());
4864    sel_end_cursor.pos(0);
4865    
4866    // don't forget to insert a dummy layout paragraph if necessary
4867    if (sel_start_cursor.par()->GetLayout() != sel_end_cursor.par()->layout){
4868      sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, 0);
4869      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4870      sel_end_cursor.par(sel_end_cursor.par()->next);
4871    }
4872    else
4873      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4874
4875    cursor = sel_end_cursor;
4876
4877    /* please break behind a space, if there is one. The space should
4878     * be erased too */ 
4879    if (sel_start_cursor.pos() > 0 
4880        && sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos() - 1))
4881      sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4882    if (sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos())) {
4883       sel_start_cursor.par()->Erase(sel_start_cursor.pos());
4884    }
4885    
4886    sel_start_cursor.par()->BreakParagraphConservative(bview->buffer()->params,
4887                                                     sel_start_cursor.pos());
4888    tmppar = sel_start_cursor.par()->Next();
4889    
4890    if (dummy_selection) {
4891            tmppar->Clear();
4892            if (kind == LyXParagraph::TAB
4893                || kind == LyXParagraph::FIG 
4894                || kind == LyXParagraph::WIDE_TAB
4895                || kind == LyXParagraph::WIDE_FIG 
4896                || kind == LyXParagraph::ALGORITHM) {
4897                    pair<bool, LyXTextClass::size_type> lres =
4898                            textclasslist.NumberOfLayout(bview->buffer()->params.textclass,
4899                                                         "Caption");
4900                    LyXTextClass::size_type lay;
4901                    if (lres.first) {
4902                            // layout fount
4903                            lay = lres.second;
4904                    } else {
4905                            // layout not found
4906                            lay = 0; // use default layout "Standard" (0)
4907                    }
4908                    tmppar->SetLayout(bview->buffer()->params, lay);
4909            }
4910    } else {
4911      if (sel_start_cursor.pos() > 0) {
4912        /* the footnote-environment should begin with a standard layout.
4913         * Imagine you insert a footnote within an enumeration, you 
4914         * certainly do not want an enumerated footnote! */ 
4915        tmppar->Clear();
4916      } else {
4917        /* this is a exception the user would sometimes expect, I hope */
4918        sel_start_cursor.par()->Clear();
4919      }
4920    }
4921    
4922    while (tmppar != sel_end_cursor.par()) {
4923       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
4924       tmppar->footnotekind = kind;
4925       tmppar = tmppar->Next();
4926    }
4927
4928    RedoParagraphs(bview, sel_start_cursor, sel_end_cursor.par()->Next());
4929    
4930    SetCursor(bview, sel_start_cursor.par()->Next(), 0);
4931
4932    ClearSelection();
4933 }
4934    
4935
4936 // returns pointer to a specified row
4937 Row * LyXText::GetRow(LyXParagraph * par,
4938                       LyXParagraph::size_type pos, long & y) const
4939 {
4940         Row * tmprow = firstrow;
4941         y = 0;
4942         
4943         // find the first row of the specified paragraph
4944         while (tmprow->next() && tmprow->par() != par) {
4945                 y += tmprow->height();
4946                 tmprow = tmprow->next();
4947         }
4948         
4949         // now find the wanted row
4950         while (tmprow->pos() < pos
4951                && tmprow->next()
4952                && tmprow->next()->par() == par
4953                && tmprow->next()->pos() <= pos) {
4954                 y += tmprow->height();
4955                 tmprow = tmprow->next();
4956         }
4957         
4958         return tmprow;
4959 }