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