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