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