]> git.lyx.org Git - lyx.git/blob - src/text.C
several changes and some new insets, read the Changelog
[lyx.git] / src / text.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12 #include <cstdlib>
13 #include <cctype>
14 #include <algorithm>
15
16 #ifdef __GNUG__
17 #pragma implementation "table.h"
18 #endif
19
20 #include "layout.h"
21 #include "lyxparagraph.h"
22 #include "lyxtext.h"
23 #include "support/textutils.h"
24 #include "insets/insetbib.h"
25 #include "insets/insettext.h"
26 #include "lyx_gui_misc.h"
27 #include "gettext.h"
28 #include "bufferparams.h"
29 #include "buffer.h"
30 #include "minibuffer.h"
31 #include "debug.h"
32 #include "lyxrc.h"
33 #include "LyXView.h"
34 #include "lyxrow.h"
35 #include "Painter.h"
36 #include "tracer.h"
37 #include "font.h"
38
39 using std::max;
40 using std::min;
41 using std::endl;
42 using std::pair;
43
44 static const int LYX_PAPER_MARGIN = 20;
45 extern int bibitemMaxWidth(Painter &, LyXFont const &);
46
47 static int iso885968x[] = {
48         0xbc,   // 0xa8 = fathatan
49         0xbd,   // 0xa9 = dammatan
50         0xbe,   // 0xaa = kasratan
51         0xdb,   // 0xab = fatha
52         0xdc,   // 0xac = damma
53         0xdd,   // 0xad = kasra
54         0xde,   // 0xae = shadda
55         0xdf,   // 0xaf = sukun
56
57         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xb0-0xbf
58
59         0,      // 0xc0 
60         0xc1,   // 0xc1 = hamza
61         0xc2,   // 0xc2 = ligature madda
62         0xc3,   // 0xc3 = ligature hamza on alef
63         0xc4,   // 0xc4 = ligature hamza on waw
64         0xc5,   // 0xc5 = ligature hamza under alef
65         0xc0,   // 0xc6 = ligature hamza on ya 
66         0xc7,   // 0xc7 = alef
67         0xeb,   // 0xc8 = baa 
68         0xc9,   // 0xc9 = taa marbuta
69         0xec,   // 0xca = taa
70         0xed,   // 0xcb = thaa
71         0xee,   // 0xcc = jeem
72         0xef,   // 0xcd = haa
73         0xf0,   // 0xce = khaa
74         0xcf,   // 0xcf = dal
75
76         0xd0,   // 0xd0 = thal
77         0xd1,   // 0xd1 = ra
78         0xd2,   // 0xd2 = zain
79         0xf1,   // 0xd3 = seen
80         0xf2,   // 0xd4 = sheen
81         0xf3,   // 0xd5 = sad
82         0xf4,   // 0xd6 = dad
83         0xd7,   // 0xd7 = tah
84         0xd8,   // 0xd8 = zah
85         0xf5,   // 0xd9 = ain
86         0xf6,   // 0xda = ghain
87         0,0,0,0,0, // 0xdb- 0xdf
88
89         0,      // 0xe0
90         0xf7,   // 0xe1 = fa
91         0xf8,   // 0xe2 = qaf
92         0xf9,   // 0xe3 = kaf
93         0xfa,   // 0xe4 = lam
94         0xfb,   // 0xe5 = meem
95         0xfc,   // 0xe6 = noon
96         0xfd,   // 0xe7 = ha
97         0xe8,   // 0xe8 = waw
98         0xe9,   // 0xe9 = alef maksura
99         0xfe    // 0xea = ya
100 };
101
102
103 inline
104 bool is_arabic(unsigned char c)
105 {
106         return 0xa8 <= c && c <= 0xea && iso885968x[c-0xa8];
107 }
108
109
110 inline
111 bool is_nikud(unsigned char c)
112 {
113         return 192 <= c && c <= 210;
114 }
115
116
117 int LyXText::workWidth(BufferView * bview) const
118 {
119         if (inset_owner) {
120                 return inset_owner->textWidth(bview->painter());
121         }
122         return bview->workWidth();
123 }
124
125 unsigned char LyXText::TransformChar(unsigned char c, Letter_Form form) const
126 {
127         if (is_arabic(c) && 
128             (form == FORM_INITIAL || form == FORM_MEDIAL) )
129                 return iso885968x[c-0xa8];
130         else
131                 return c;
132 }
133
134
135 unsigned char LyXText::TransformChar(unsigned char c, LyXParagraph * par,
136                         LyXParagraph::size_type pos) const
137 {
138         if (!is_arabic(c))
139                 if (isdigit(c))
140                         return c + (0xb0 - '0');
141                 else
142                         return c;
143
144         bool not_first = (pos > 0 && is_arabic(par->GetChar(pos-1)));
145         if (pos < par->Last()-1 && is_arabic(par->GetChar(pos+1)))
146                 if (not_first)
147                         return TransformChar(c,FORM_MEDIAL);
148                 else
149                         return TransformChar(c,FORM_INITIAL);
150         else
151                 if (not_first)
152                         return TransformChar(c,FORM_FINAL);
153                 else
154                         return TransformChar(c,FORM_ISOLATED);
155 }
156
157 // This is the comments that some of the warnings below refers to.
158 // There are some issues in this file and I don't think they are
159 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
160 // this is a problem that has been here almost from day one and that a
161 // larger userbase with differenct access patters triggers the bad
162 // behaviour. (segfaults.) What I think happen is: In several places
163 // we store the paragraph in the current cursor and then moves the
164 // cursor. This movement of the cursor will delete paragraph at the
165 // old position if it is now empty. This will make the temporary
166 // pointer to the old cursor paragraph invalid and dangerous to use.
167 // And is some cases this will trigger a segfault. I have marked some
168 // of the cases where this happens with a warning, but I am sure there
169 // are others in this file and in text2.C. There is also a note in
170 // Delete() that you should read. In Delete I store the paragraph->id
171 // instead of a pointer to the paragraph. I am pretty sure this faulty
172 // use of temporary pointers to paragraphs that might have gotten
173 // invalidated (through a cursor movement) before they are used, are
174 // the cause of the strange crashes we get reported often.
175 //
176 // It is very tiresom to change this code, especially when it is as
177 // hard to read as it is. Help to fix all the cases where this is done
178 // would be greately appreciated.
179 //
180 // Lgb
181
182 int LyXText::SingleWidth(BufferView * bview, LyXParagraph * par,
183                          LyXParagraph::size_type pos) const
184 {
185         char c = par->GetChar(pos);
186         return SingleWidth(bview, par, pos, c);
187 }
188
189
190 int LyXText::SingleWidth(BufferView * bview, LyXParagraph * par,
191                          LyXParagraph::size_type pos, char c) const
192 {
193         LyXFont font = GetFont(bview->buffer(), par, pos);
194
195         // The most common case is handled first (Asger)
196         if (IsPrintable(c)) {
197                 if (font.language()->RightToLeft()) {
198                         if (font.language()->lang() == "arabic" &&
199                             lyxrc.font_norm == "iso8859-6.8x")
200                                 c = TransformChar(c, par, pos);
201                         else if (font.language()->lang() == "hebrew" &&
202                                  is_nikud(c))
203                                 return 0;
204                 }
205                 return lyxfont::width(c, font);
206
207         } else if (IsHfillChar(c)) {
208                 return 3;       /* Because of the representation
209                                  * as vertical lines */
210 #ifndef NEW_INSETS
211         } else if (c == LyXParagraph::META_FOOTNOTE ||
212                    c == LyXParagraph::META_MARGIN ||
213                    c == LyXParagraph::META_FIG ||
214                    c == LyXParagraph::META_TAB ||
215                    c == LyXParagraph::META_WIDE_FIG ||
216                    c == LyXParagraph::META_WIDE_TAB ||
217                    c == LyXParagraph::META_ALGORITHM) {
218                 string fs;
219                 switch (c) {
220                 case LyXParagraph::META_MARGIN:
221                         fs = "margin";
222                         break;
223                 case LyXParagraph::META_FIG:
224                         fs = "fig";
225                         break;
226                 case LyXParagraph::META_TAB:
227                         fs = "tab";
228                         break;
229                 case LyXParagraph::META_ALGORITHM:
230                         fs = "alg";
231                         break;
232                 case LyXParagraph::META_WIDE_FIG:
233                         fs = "wide-fig";
234                         break;
235                 case LyXParagraph::META_WIDE_TAB:
236                         fs = "wide-tab";
237                         break;
238                 case LyXParagraph::META_FOOTNOTE:
239                         fs = "foot";
240                         break;
241                 }
242                 font.decSize();
243                 font.decSize();
244                 return lyxfont::width(fs, font);
245 #endif
246         } else if (c == LyXParagraph::META_INSET) {
247                 Inset * tmpinset = par->GetInset(pos);
248                 if (tmpinset) {
249                         tmpinset->update(bview, font);
250                         return tmpinset->width(bview->painter(), font);
251                 } else
252                         return 0;
253
254         } else if (IsSeparatorChar(c))
255                 c = ' ';
256         else if (IsNewlineChar(c))
257                 c = 'n';
258         return lyxfont::width(c, font);
259 }
260
261
262 // Returns the paragraph position of the last character in the specified row
263 LyXParagraph::size_type LyXText::RowLast(Row const * row) const
264 {
265         if (row->next() == 0)
266                 return row->par()->Last() - 1;
267         else if (row->next()->par() != row->par()) 
268                 return row->par()->Last() - 1;
269         else 
270                 return row->next()->pos() - 1;
271 }
272
273
274 LyXParagraph::size_type LyXText::RowLastPrintable(Row const * row) const
275 {
276         LyXParagraph::size_type last = RowLast(row);
277         if (last >= row->pos()
278             && row->next()
279             && row->next()->par() == row->par()
280             && row->par()->IsSeparator(last))
281                 return last - 1;
282         else
283                 return last;
284 }
285
286
287 void LyXText::ComputeBidiTables(Buffer const * buf, Row * row) const
288 {
289         bidi_same_direction = true;
290         if (!lyxrc.rtl_support) {
291                 bidi_start = -1;
292                 return;
293         }
294
295         bidi_start = row->pos();
296         bidi_end = RowLastPrintable(row);
297
298         if (bidi_start > bidi_end) {
299                 bidi_start = -1;
300                 return;
301         }
302
303         if (bidi_end + 2 - bidi_start >
304             static_cast<LyXParagraph::size_type>(log2vis_list.size())) {
305                 LyXParagraph::size_type new_size = 
306                         (bidi_end + 2 - bidi_start < 500) ?
307                         500 : 2 * (bidi_end + 2 - bidi_start);
308                 log2vis_list.resize(new_size);
309                 vis2log_list.resize(new_size);
310                 bidi_levels.resize(new_size);
311         }
312
313         vis2log_list[bidi_end + 1 - bidi_start] = -1;
314         log2vis_list[bidi_end + 1 - bidi_start] = -1;
315
316         LyXParagraph::size_type stack[2];
317         bool rtl_par = row->par()->getParLanguage(buf->params)->RightToLeft();
318         int level = 0;
319         bool rtl = false;
320         bool rtl0 = false;
321         LyXParagraph::size_type main_body = BeginningOfMainBody(buf, row->par());
322
323         for (LyXParagraph::size_type lpos = bidi_start;
324              lpos <= bidi_end; ++lpos) {
325                 bool is_space = row->par()->IsLineSeparator(lpos);
326                 LyXParagraph::size_type pos =
327                         (is_space && lpos + 1 <= bidi_end &&
328                          !row->par()->IsLineSeparator(lpos + 1) &&
329                          (!row->par()->table
330                           || !row->par()->IsNewline(lpos + 1)) )
331                         ? lpos + 1 : lpos;
332                 LyXFont font = row->par()->GetFontSettings(buf->params, pos);
333                 bool new_rtl = font.isVisibleRightToLeft();
334                 bool new_rtl0 = font.isRightToLeft();
335                 int new_level;
336
337 #ifndef NEW_TABULAR
338                 if (row->par()->table && row->par()->IsNewline(lpos)) {
339                         new_level = 0;
340                         new_rtl = new_rtl0 = false;
341                 } else
342 #endif
343                         if (lpos == main_body - 1
344                            && row->pos() < main_body - 1
345                            && row->par()->IsLineSeparator(lpos)) {
346                         new_level = (rtl_par) ? 1 : 0;
347                         new_rtl = new_rtl0 = rtl_par;
348                 } else if (new_rtl0)
349                         new_level = (new_rtl) ? 1 : 2;
350                 else
351                         new_level = (rtl_par) ? 2 : 0;
352
353                 if (is_space && new_level >= level) {
354                         new_level = level;
355                         new_rtl = rtl;
356                         new_rtl0 = rtl0;
357                 }
358
359                 int new_level2 = new_level;
360
361                 if (level == new_level && rtl0 != new_rtl0) {
362                         --new_level2;
363                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
364                 } else if (level < new_level) {
365                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
366                         if (new_level > rtl_par)
367                                 bidi_same_direction = false;
368                 } else
369                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
370                 rtl = new_rtl;
371                 rtl0 = new_rtl0;
372                 bidi_levels[lpos - bidi_start] = new_level;
373
374                 while (level > new_level2) {
375                         LyXParagraph::size_type old_lpos =
376                                 stack[--level];
377                         int delta = lpos - old_lpos - 1;
378                         if (level % 2)
379                                 delta = -delta;
380                         log2vis_list[lpos - bidi_start] += delta;
381                         log2vis_list[old_lpos - bidi_start] += delta;
382                 }
383                 while (level < new_level)
384                         stack[level++] = lpos;
385         }
386
387         while (level > 0) {
388                 LyXParagraph::size_type old_lpos = stack[--level];
389                 int delta = bidi_end - old_lpos;
390                 if (level % 2)
391                         delta = -delta;
392                 log2vis_list[old_lpos - bidi_start] += delta;
393         }
394
395         LyXParagraph::size_type vpos = bidi_start - 1;
396         for (LyXParagraph::size_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
397                 vpos += log2vis_list[lpos - bidi_start];
398                 vis2log_list[vpos - bidi_start] = lpos;
399                 log2vis_list[lpos - bidi_start] = vpos;
400         }
401 }
402
403
404 // This method requires a previous call to ComputeBidiTables()
405 bool LyXText::IsBoundary(Buffer const * buf, LyXParagraph * par,
406                          LyXParagraph::size_type pos) const
407 {
408         if (!lyxrc.rtl_support)
409                 return false;    // This is just for speedup
410
411         if (!bidi_InRange(pos - 1) ||
412             (par->table && par->IsNewline(pos-1)) )
413                 return false;
414
415         bool rtl = bidi_level(pos - 1) % 2;
416         bool rtl2 = rtl;
417         if (pos == par->Last() ||
418             (par->table && par->IsNewline(pos)))
419                 rtl2 = par->isRightToLeftPar(buf->params);
420         else if (bidi_InRange(pos))
421                 rtl2 = bidi_level(pos) % 2;
422         return rtl != rtl2;
423 }
424
425
426 bool LyXText::IsBoundary(Buffer const * buf, LyXParagraph * par,
427                          LyXParagraph::size_type pos,
428                          LyXFont const & font) const
429 {
430         if (!lyxrc.rtl_support)
431                 return false;    // This is just for speedup
432
433         bool rtl = font.isVisibleRightToLeft();
434         bool rtl2 = rtl;
435         if (pos == par->Last() ||
436             (par->table && par->IsNewline(pos)))
437                 rtl2 = par->isRightToLeftPar(buf->params);
438         else if (bidi_InRange(pos))
439                 rtl2 =  bidi_level(pos) % 2;
440         return rtl != rtl2;
441 }
442
443
444 void LyXText::draw(BufferView * bview, Row const * row,
445                    LyXParagraph::size_type & vpos,
446                    int offset, float & x, bool cleared)
447 {
448         Painter & pain = bview->painter();
449         
450         LyXParagraph::size_type pos = vis2log(vpos);
451         char c = row->par()->GetChar(pos);
452         float tmpx = x;
453
454         if (IsNewlineChar(c)) {
455                 ++vpos;
456                 // Draw end-of-line marker
457                 LyXFont font = GetFont(bview->buffer(), row->par(), pos);
458                 int wid = lyxfont::width('n', font);
459                 int asc = lyxfont::maxAscent(font);
460                 int y = offset + row->baseline();
461                 int xp[3], yp[3];
462                 
463                 if (bidi_level(pos) % 2 == 0) {
464                         xp[0] = int(x + wid * 0.375);
465                         yp[0] = int(y - 0.875 * asc * 0.75);
466                         
467                         xp[1] = int(x);
468                         yp[1] = int(y - 0.500 * asc * 0.75);
469                         
470                         xp[2] = int(x + wid * 0.375);
471                         yp[2] = int(y - 0.125 * asc * 0.75);
472                         
473                         pain.lines(xp, yp, 3, LColor::eolmarker);
474                         
475                         xp[0] = int(x);
476                         yp[0] = int(y - 0.500 * asc * 0.75);
477                         
478                         xp[1] = int(x + wid);
479                         yp[1] = int(y - 0.500 * asc * 0.75);
480                         
481                         xp[2] = int(x + wid);
482                         yp[2] = int(y - asc * 0.75);
483                         
484                         pain.lines(xp, yp, 3, LColor::eolmarker);
485                 } else {
486                         xp[0] = int(x + wid * 0.625);
487                         yp[0] = int(y - 0.875 * asc * 0.75);
488                         
489                         xp[1] = int(x + wid);
490                         yp[1] = int(y - 0.500 * asc * 0.75);
491                         
492                         xp[2] = int(x + wid * 0.625);
493                         yp[2] = int(y - 0.125 * asc * 0.75);
494                         
495                         pain.lines(xp, yp, 3, LColor::eolmarker);
496                         
497                         xp[0] = int(x + wid);
498                         yp[0] = int(y - 0.500 * asc * 0.75);
499                         
500                         xp[1] = int(x);
501                         yp[1] = int(y - 0.500 * asc * 0.75);
502                         
503                         xp[2] = int(x);
504                         yp[2] = int(y - asc * 0.75);
505                         
506                         pain.lines(xp, yp, 3, LColor::eolmarker);
507                 }
508                 x += wid;
509                 return;
510         }
511
512         LyXFont font = GetFont(bview->buffer(), row->par(), pos);
513         LyXFont font2 = font;
514 #ifndef NEW_INSETS
515         if (c == LyXParagraph::META_FOOTNOTE
516             || c == LyXParagraph::META_MARGIN
517             || c == LyXParagraph::META_FIG
518             || c == LyXParagraph::META_TAB
519             || c == LyXParagraph::META_WIDE_FIG
520             || c == LyXParagraph::META_WIDE_TAB
521             || c == LyXParagraph::META_ALGORITHM) {
522                 string fs;
523                 switch (c) {
524                 case LyXParagraph::META_MARGIN:
525                         fs = "margin";
526                         break;
527                 case LyXParagraph::META_FIG:
528                         fs = "fig";
529                         break;
530                 case LyXParagraph::META_TAB:
531                         fs = "tab";
532                         break;
533                 case LyXParagraph::META_ALGORITHM:
534                         fs = "alg";
535                         break;
536                 case LyXParagraph::META_WIDE_FIG:
537                         fs = "wide-fig";
538                         break;
539                 case LyXParagraph::META_WIDE_TAB:
540                         fs = "wide-tab";
541                         break;
542                 case LyXParagraph::META_FOOTNOTE:
543                         fs = "foot";
544                         break;
545                 }
546                 font.decSize();
547                 font.decSize();
548           
549                 // calculate the position of the footnotemark
550                 int y = (row->baseline() - lyxfont::maxAscent(font2) 
551                          + lyxfont::maxAscent(font));
552           
553                 font.setColor(LColor::footnote);
554
555                 // draw it and set new x position
556                 
557                 pain.text(int(x), offset + y, fs, font);
558                 x += lyxfont::width(fs, font);
559                 pain.line(int(tmpx), offset + row->baseline(),
560                           int(x), offset + row->baseline(),
561                           LColor::footnote);
562
563                 ++vpos;
564                 return;
565         } else
566 #endif
567                 if (c == LyXParagraph::META_INSET) {
568                 Inset 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 #ifdef NEW_WAY
2099               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
2100 #else
2101               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2102               cursor.par()->SetFont(pos, font);
2103 #endif
2104           }
2105                 
2106           /* append the row into the table */
2107           cursor.par()->table->AppendRow(cell_org);
2108           RedoParagraph(bview);
2109           return;
2110       }
2111       case LyXTable::APPEND_CONT_ROW: {
2112               LyXParagraph::size_type pos = cursor.pos();
2113           /* move to the next row */
2114           int cell_org = actCell;
2115           int cell = cell_org;
2116
2117           // if there is already a controw but not for this cell
2118           // the AppendContRow sets only the right values but does
2119           // not actually add a row
2120           if (cursor.par()->table->RowHasContRow(cell_org) &&
2121               (cursor.par()->table->CellHasContRow(cell_org)<0)) {
2122               cursor.par()->table->AppendContRow(cell_org);
2123               RedoParagraph(bview);
2124               return;
2125           }
2126           while (pos < cursor.par()->Last() && 
2127                  (cell == cell_org
2128                   || !cursor.par()->table->IsFirstCell(cell))){
2129               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2130                   ++pos;
2131               if (pos < cursor.par()->Last())
2132                   ++pos;
2133               ++cell;
2134           }
2135                 
2136           /* insert the new cells */ 
2137           int number = cursor.par()->table->NumberOfCellsInRow(cell_org);
2138           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2139           LyXFont font(LyXFont::ALL_INHERIT,lang);
2140           for (int i = 0; i < number; ++i) {
2141 #ifdef NEW_WAY
2142               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
2143 #else
2144               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2145               cursor.par()->SetFont(pos, font);
2146 #endif
2147           }
2148
2149           /* append the row into the table */
2150           cursor.par()->table->AppendContRow(cell_org);
2151           RedoParagraph(bview);
2152           return;
2153       }
2154       case LyXTable::APPEND_COLUMN: {
2155               LyXParagraph::size_type pos = 0;
2156           int cell_org = actCell;
2157           int cell = 0;
2158           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2159           LyXFont font(LyXFont::ALL_INHERIT,lang);
2160           do{
2161               if (pos && (cursor.par()->IsNewline(pos-1))){
2162                   if (cursor.par()->table->AppendCellAfterCell(cell_org, cell)) {
2163 #ifdef NEW_WAY
2164                       cursor.par()->InsertChar(pos,
2165                                                LyXParagraph::META_NEWLINE,
2166                                                font);
2167 #else
2168                       cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2169                       cursor.par()->SetFont(pos, font);
2170 #endif
2171                       if (pos <= cursor.pos())
2172                           cursor.pos(cursor.pos() + 1);
2173                       ++pos;
2174                   }
2175                   ++cell;
2176               }
2177               ++pos;
2178           } while (pos <= cursor.par()->Last());
2179           /* remember that the very last cell doesn't end with a newline.
2180              This saves one byte memory per table ;-) */
2181           if (cursor.par()->table->AppendCellAfterCell(cell_org, cell)) {
2182                   LyXParagraph::size_type last = cursor.par()->Last();
2183 #ifdef NEW_WAY
2184                   cursor.par()->InsertChar(last,
2185                                            LyXParagraph::META_NEWLINE, font);
2186 #else
2187                   cursor.par()->InsertChar(last, LyXParagraph::META_NEWLINE);
2188                   cursor.par()->SetFont(last, font);
2189 #endif
2190           }
2191                 
2192           /* append the column into the table */ 
2193           cursor.par()->table->AppendColumn(cell_org);
2194                 
2195           RedoParagraph(bview);
2196           return;
2197       }
2198       case LyXTable::DELETE_ROW:
2199           if (bview->the_locking_inset)
2200               bview->unlockInset(bview->the_locking_inset);
2201           RemoveTableRow(cursor);
2202           RedoParagraph(bview);
2203           return;
2204         
2205       case LyXTable::DELETE_COLUMN: {
2206               LyXParagraph::size_type pos = 0;
2207           int cell_org = actCell;
2208           int cell = 0;
2209           if (bview->the_locking_inset)
2210               bview->unlockInset(bview->the_locking_inset);
2211           do {
2212               if (!pos || (cursor.par()->IsNewline(pos-1))){
2213                   if (cursor.par()->table->DeleteCellIfColumnIsDeleted(cell, cell_org)){
2214                       // delete one cell
2215                       while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2216                           cursor.par()->Erase(pos);
2217                       if (pos < cursor.par()->Last())
2218                           cursor.par()->Erase(pos);
2219                       else 
2220                           cursor.par()->Erase(pos - 1); // the missing newline at the end of a table
2221                       --pos; // because of pos++ below
2222                   }   
2223                   ++cell;
2224               }
2225               ++pos;
2226           } while (pos <= cursor.par()->Last());
2227                 
2228           /* delete the column from the table */ 
2229           cursor.par()->table->DeleteColumn(cell_org);
2230                 
2231           /* set the cursor to the beginning of the table, where else? */ 
2232           cursor.pos(0);
2233           RedoParagraph(bview);
2234           return;
2235       }
2236       case LyXTable::TOGGLE_LINE_TOP:
2237           lineSet = !cursor.par()->table->TopLine(actCell);
2238           if (!selection){
2239               cursor.par()->table->SetTopLine(actCell, lineSet);
2240           } else {
2241                   LyXParagraph::size_type i;
2242                   int n = -1, m = -2;
2243               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2244                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2245                       cursor.par()->table->SetTopLine(n, lineSet);
2246                       m = n;
2247                   }
2248               }
2249           }
2250           RedoParagraph(bview);
2251           return;
2252     
2253       case LyXTable::TOGGLE_LINE_BOTTOM:
2254           lineSet = !cursor.par()->table->BottomLine(actCell);
2255           if (!selection){
2256               cursor.par()->table->SetBottomLine(actCell, lineSet);
2257           } else {
2258                   LyXParagraph::size_type i;
2259                   int n = -1, m = -2;
2260               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2261                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2262                       cursor.par()->table->SetBottomLine(n, lineSet);
2263                       m = n;
2264                   }
2265               }
2266           }
2267           RedoParagraph(bview);
2268           return;
2269                 
2270       case LyXTable::TOGGLE_LINE_LEFT:
2271           lineSet = !cursor.par()->table->LeftLine(actCell);
2272           if (!selection){
2273               cursor.par()->table->SetLeftLine(actCell, lineSet);
2274           } else {
2275                   LyXParagraph::size_type i;
2276                   int n = -1, m = -2;
2277               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2278                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2279                       cursor.par()->table->SetLeftLine(n, lineSet);
2280                       m = n;
2281                   }
2282               }
2283           }
2284           RedoParagraph(bview);
2285           return;
2286
2287       case LyXTable::TOGGLE_LINE_RIGHT:
2288           lineSet = !cursor.par()->table->RightLine(actCell);
2289           if (!selection){
2290               cursor.par()->table->SetRightLine(actCell, lineSet);
2291           } else {
2292                   int n = -1, m = -2;
2293                   LyXParagraph::size_type i = sel_start_cursor.pos();
2294               for (; i <= sel_end_cursor.pos(); ++i) {
2295                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2296                       cursor.par()->table->SetRightLine(n, lineSet);
2297                       m = n;
2298                   }
2299               }
2300           }
2301           RedoParagraph(bview);
2302           return;
2303     
2304       case LyXTable::ALIGN_LEFT:
2305       case LyXTable::ALIGN_RIGHT:
2306       case LyXTable::ALIGN_CENTER:
2307           if (!selection){
2308               cursor.par()->table->SetAlignment(actCell, setAlign);
2309           } else {
2310               int n = -1, m = -2;
2311               LyXParagraph::size_type i = sel_start_cursor.pos();
2312               for (; i <= sel_end_cursor.pos(); ++i) {
2313                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2314                       cursor.par()->table->SetAlignment(n, setAlign);
2315                       m = n;
2316                   }
2317               }
2318           }
2319           RedoParagraph(bview);
2320           return;
2321                 
2322       case LyXTable::DELETE_TABLE:
2323           SetCursorIntern(bview, cursor.par(), 0);
2324           delete cursor.par()->table;
2325           cursor.par()->table = 0;
2326           // temporary: Should put table in simple_cut_buffer (with before and after
2327           // dummy-paragraph !! 
2328           // not necessar anymore with UNDO :)
2329           for (LyXParagraph::size_type i = 
2330                        cursor.par()->size() - 1; i >= 0; --i)
2331               cursor.par()->Erase(i);
2332           RedoParagraph(bview);
2333           return;
2334                 
2335       case LyXTable::MULTICOLUMN: {
2336           int number = 0;
2337           // check wether we are completly in a multicol
2338           int multicol = cursor.par()->table->IsMultiColumn(actCell);
2339           if (multicol && selection && sel_start_cursor.row() == sel_end_cursor.row()) {
2340               multicol = NumberOfCell(sel_start_cursor.par(), sel_start_cursor.pos())
2341                   == NumberOfCell(sel_end_cursor.par(), sel_end_cursor.pos());
2342           }
2343
2344           if (multicol){
2345               int newlines = cursor.par()->table->UnsetMultiColumn(actCell);
2346               LyXParagraph::size_type pos = cursor.pos();
2347               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2348                   ++pos;
2349               for (; newlines; --newlines)
2350                   cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2351               RedoParagraph(bview);
2352               return;
2353           }
2354           else {
2355               // selection must be in one row (or no selection)
2356               if (!selection){
2357                   cursor.par()->table->SetMultiColumn(NumberOfCell(cursor.par(),
2358                                                                  cursor.pos()),
2359                                                     1);
2360                   RedoParagraph(bview);
2361                   return;
2362               }
2363               else {
2364                   if (sel_start_cursor.row() == sel_end_cursor.row()){
2365                       LyXParagraph::size_type i;
2366                       number = 1;
2367                       for (i = sel_start_cursor.pos();
2368                            i < sel_end_cursor.pos(); ++i){
2369                           if (sel_start_cursor.par()->IsNewline(i)){
2370                               sel_start_cursor.par()->Erase(i);
2371                               // check for double-blanks
2372                               if ((i && !sel_start_cursor.par()->IsLineSeparator(i-1))
2373                                   &&
2374                                   (i < sel_start_cursor.par()->Last() 
2375                                    && !sel_start_cursor.par()->IsLineSeparator(i)))
2376                                   sel_start_cursor.par()->InsertChar(i, ' ');
2377                               else {
2378                                   sel_end_cursor.pos(sel_end_cursor.pos() - 1);
2379                                   --i;
2380                               }
2381                               ++number;
2382                           }
2383                       }
2384                       cursor.par()->table->
2385                           SetMultiColumn(NumberOfCell(sel_start_cursor.par(),
2386                                                       sel_start_cursor.pos()),
2387                                          number);
2388                       cursor.pos(sel_start_cursor.pos());
2389                       RedoParagraph(bview);
2390                       return;
2391                   }
2392                   else {
2393                       WriteAlert(_("Impossible Operation!"), 
2394                                  _("Multicolumns can only be horizontally."), 
2395                                  _("Sorry."));
2396                   }
2397               }
2398           }
2399           break;
2400       }
2401       case LyXTable::SET_ALL_LINES:
2402           setLines = 1;
2403       case LyXTable::UNSET_ALL_LINES:
2404           if (!selection){
2405               cursor.par()->table->SetAllLines(NumberOfCell(cursor.par(),
2406                                                           cursor.pos()),
2407                                              setLines);
2408           } else {
2409                   LyXParagraph::size_type i;
2410                   int n = -1, m = -2;
2411               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2412                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2413                       cursor.par()->table->SetAllLines(n, setLines);
2414                       m = n;
2415                   }
2416               }
2417           }
2418           RedoParagraph(bview);
2419           return;
2420       case LyXTable::SET_LONGTABLE:
2421           cursor.par()->table->SetLongTable(true);
2422           return;
2423       case LyXTable::UNSET_LONGTABLE:
2424           cursor.par()->table->SetLongTable(false);
2425           return;
2426       case LyXTable::SET_ROTATE_TABLE:
2427           cursor.par()->table->SetRotateTable(true);
2428           return;
2429       case LyXTable::UNSET_ROTATE_TABLE:
2430           cursor.par()->table->SetRotateTable(false);
2431           return;
2432       case LyXTable::SET_ROTATE_CELL:
2433           if (!selection){
2434               cursor.par()->table->SetRotateCell(actCell, true);
2435           } else {
2436                   LyXParagraph::size_type i;
2437                   int n = -1, m = -2;
2438               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2439                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2440                       cursor.par()->table->SetRotateCell(n, true);
2441                       m = n;
2442                   }
2443               }
2444           }
2445           return;
2446       case LyXTable::UNSET_ROTATE_CELL:
2447           if (!selection){
2448               cursor.par()->table->SetRotateCell(actCell, false);
2449           } else {
2450                   int n = -1, m = -2;
2451                   LyXParagraph::size_type i = sel_start_cursor.pos();
2452               for (; i <= sel_end_cursor.pos(); ++i) {
2453                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2454                       cursor.par()->table->SetRotateCell(n, false);
2455                       m = n;
2456                   }
2457               }
2458           }
2459           return;
2460       case LyXTable::SET_LINEBREAKS:
2461           what = !cursor.par()->table->Linebreaks(cursor.par()->table->FirstVirtualCell(actCell));
2462           if (!selection){
2463               cursor.par()->table->SetLinebreaks(actCell, what);
2464           } else {
2465                   LyXParagraph::size_type i;
2466                   int n = -1, m = -2;
2467               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2468                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2469                       cursor.par()->table->SetLinebreaks(n, what);
2470                       m = n;
2471                   }
2472               }
2473           }
2474           return;
2475       case LyXTable::SET_LTFIRSTHEAD:
2476           cursor.par()->table->SetLTHead(actCell, true);
2477           return;
2478       case LyXTable::SET_LTHEAD:
2479           cursor.par()->table->SetLTHead(actCell, false);
2480           return;
2481       case LyXTable::SET_LTFOOT:
2482           cursor.par()->table->SetLTFoot(actCell, false);
2483           return;
2484       case LyXTable::SET_LTLASTFOOT:
2485           cursor.par()->table->SetLTFoot(actCell, true);
2486           return;
2487       case LyXTable::SET_LTNEWPAGE:
2488           what = !cursor.par()->table->LTNewPage(actCell);
2489           cursor.par()->table->SetLTNewPage(actCell, what);
2490           return;
2491     }
2492 }
2493         
2494
2495 void LyXText::InsertCharInTable(BufferView * bview, char c)
2496 {
2497         Row * row = 0;
2498         Row * tmprow = 0;
2499         long y;
2500         bool jumped_over_space;
2501         
2502         /* first check, if there will be two blanks together or a blank at 
2503          * the beginning of a paragraph. 
2504          * I decided to handle blanks like normal characters, the main 
2505          * difference are the special checks when calculating the row.fill
2506          * (blank does not count at the end of a row) and the check here */ 
2507         
2508         LyXFont realtmpfont = real_current_font;
2509         LyXFont rawtmpfont = current_font; /* store the current font.
2510                                             * This is because of the use
2511                                             * of cursor movements. The moving
2512                                             * cursor would refresh the 
2513                                             * current font */
2514
2515         // Get the font that is used to calculate the baselineskip
2516         LyXParagraph::size_type const lastpos = 
2517                 cursor.par()->Last();
2518         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2519                                                            lastpos - 1);
2520
2521         jumped_over_space = false;
2522         if (IsLineSeparatorChar(c)) {
2523                 if ((cursor.pos() > 0 && 
2524                      cursor.par()->IsLineSeparator(cursor.pos() - 1))
2525                     || (cursor.pos() > 0 && cursor.par()->IsNewline(cursor.pos() - 1))
2526                     || (cursor.pos() == 0 &&
2527                         !(cursor.par()->Previous()
2528                           && cursor.par()->Previous()->footnoteflag
2529                           == LyXParagraph::OPEN_FOOTNOTE)))
2530                         return;
2531         } else if (IsNewlineChar(c)) {
2532             if (!IsEmptyTableCell()) {
2533                 TableFeatures(bview, LyXTable::APPEND_CONT_ROW);
2534                 CursorDown(bview);
2535             }
2536           return;
2537         }
2538    
2539         row = cursor.row();
2540         y = cursor.y() - row->baseline();
2541         if (c != LyXParagraph::META_INSET)      /* in this case LyXText::InsertInset 
2542                                          * already inserted the character */
2543                 cursor.par()->InsertChar(cursor.pos(), c);
2544         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
2545
2546         if (!jumped_over_space) {
2547                 /* refresh the positions */
2548                 tmprow = row;
2549                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2550                         tmprow = tmprow->next();
2551                         tmprow->pos(tmprow->pos() + 1);
2552                 }
2553         }
2554
2555         cursor.pos(cursor.pos() + 1);
2556
2557         CheckParagraphInTable(bview, cursor.par(), cursor.pos());
2558         
2559         current_font = rawtmpfont;
2560         real_current_font = realtmpfont;
2561         
2562         /* check, whether the last character's font has changed. */
2563         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2564             && rawparfont != rawtmpfont)
2565                 RedoHeightOfParagraph(bview, cursor);
2566 }
2567
2568
2569 void LyXText::CheckParagraphInTable(BufferView * bview, LyXParagraph * par,
2570                                     LyXParagraph::size_type pos)
2571 {
2572         
2573         if (par->GetChar(pos) == LyXParagraph::META_INSET &&
2574             par->GetInset(pos) && par->GetInset(pos)->display()){
2575           par->GetInset(pos)->display(false);
2576         }
2577
2578         long y;
2579         Row * row = GetRow(par, pos, y);
2580         
2581         int tmpheight = row->height();
2582         SetHeightOfRow(bview, row);
2583
2584         LyXParagraph::size_type tmp_pos = pos;
2585         /* update the table information */
2586         while (tmp_pos && !par->IsNewline(tmp_pos - 1))
2587                 --tmp_pos;
2588         if (par->table->SetWidthOfCell(NumberOfCell(par, pos),
2589                                        WidthOfCell(bview, par, tmp_pos))) {
2590                 LyXCursor tmpcursor = cursor;
2591                 SetCursorIntern(bview, par, pos, false);
2592                 /* make a complete redraw */
2593                 RedoDrawingOfParagraph(bview, cursor);
2594                 cursor = tmpcursor;
2595         }
2596         else {
2597                 /* redraw only the row */
2598                 LyXCursor tmpcursor = cursor;
2599                 SetCursorIntern(bview, par, pos);
2600                 //CHECK See comment on top of text.C
2601                 refresh_y = y;
2602                 refresh_x = cursor.x();
2603                 refresh_row = row;
2604                 refresh_pos = cursor.pos();
2605                 cursor = tmpcursor;
2606                 
2607                 if (tmpheight == row->height())
2608                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2609                 else
2610                         status = LyXText::NEED_MORE_REFRESH;
2611         }
2612         SetCursorIntern(bview, cursor.par(), cursor.pos(), false,
2613                         cursor.boundary());
2614 }
2615
2616
2617 void LyXText::BackspaceInTable(BufferView * bview)
2618 {
2619         Row * tmprow, * row;
2620         long y;
2621         
2622         LyXFont rawtmpfont = current_font;
2623         LyXFont realtmpfont = real_current_font;
2624
2625         // Get the font that is used to calculate the baselineskip
2626         int const lastpos = cursor.par()->Last();
2627         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2628                                                            lastpos - 1);
2629         
2630         if (cursor.pos() == 0) {
2631                 /* no pasting of table paragraphs */
2632                 
2633                 CursorLeft(bview);
2634         } else {
2635                 /* this is the code for a normal backspace, not pasting
2636                  * any paragraphs */ 
2637                 SetUndo(bview->buffer(), Undo::DELETE, 
2638                         cursor.par()->ParFromPos(cursor.pos())->previous, 
2639                         cursor.par()->ParFromPos(cursor.pos())->next); 
2640           
2641                 CursorLeftIntern(bview);
2642                 
2643                 /* some insets are undeletable here */
2644                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
2645                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
2646                                 return;
2647                 }
2648                 
2649                 row = cursor.row();
2650                 y = cursor.y() - row->baseline();
2651                 
2652                 /* some special code when deleting a newline. */
2653                 if (cursor.par()->IsNewline(cursor.pos())) {
2654                         /* nothing :-) */
2655                         return;
2656                 } else {
2657                         cursor.par()->Erase(cursor.pos());
2658                         
2659                         /* refresh the positions */
2660                         tmprow = row;
2661                         while (tmprow->next()
2662                                && tmprow->next()->par() == row->par()) {
2663                                 tmprow = tmprow->next();
2664                                 tmprow->pos(tmprow->pos() - 1);
2665                         }
2666                 }
2667       
2668                 CheckParagraphInTable(bview, cursor.par(), cursor.pos());
2669       
2670                 /* check, wether the last characters font has changed. */ 
2671                 if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2672                     && rawparfont != rawtmpfont)
2673                         RedoHeightOfParagraph(bview, cursor);
2674
2675                 /* restore the current font 
2676                  * That is what a user expects! */
2677                 current_font = rawtmpfont;
2678                 real_current_font = realtmpfont;
2679         }
2680         SetCursorIntern(bview, cursor.par(), cursor.pos(), true,
2681                         cursor.boundary());
2682         if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos()) != cursor.boundary())
2683                 SetCursor(bview, cursor.par(), cursor.pos(), false, !cursor.boundary());
2684 }
2685
2686 /* table stuff -- end*/
2687 #endif
2688
2689
2690 // Just a macro to make some thing easier. 
2691 void LyXText::RedoParagraph(BufferView * bview) const
2692 {
2693         ClearSelection();
2694         RedoParagraphs(bview, cursor, cursor.par()->Next());
2695         SetCursorIntern(bview, cursor.par(), cursor.pos());
2696 }
2697
2698
2699 /* insert a character, moves all the following breaks in the 
2700  * same Paragraph one to the right and make a rebreak */
2701 void LyXText::InsertChar(BufferView * bview, char c)
2702 {
2703         SetUndo(bview->buffer(), Undo::INSERT, 
2704                 cursor.par()->ParFromPos(cursor.pos())->previous, 
2705                 cursor.par()->ParFromPos(cursor.pos())->next);
2706
2707         // When the free-spacing option is set for the current layout,
2708         // disable the double-space checking
2709
2710         bool freeSpacing = 
2711                 textclasslist.Style(bview->buffer()->params.textclass,
2712                                cursor.row()->par()->GetLayout()).free_spacing;
2713
2714 #ifndef NEW_TABULAR
2715         /* table stuff -- begin*/
2716         if (cursor.par()->table) {
2717                 InsertCharInTable(bview, c);
2718                 charInserted();
2719                 return;
2720         }
2721         /* table stuff -- end*/
2722 #endif
2723         /* First check, if there will be two blanks together or a blank at 
2724           the beginning of a paragraph. 
2725           I decided to handle blanks like normal characters, the main 
2726           difference are the special checks when calculating the row.fill
2727           (blank does not count at the end of a row) and the check here */ 
2728
2729         // The bug is triggered when we type in a description environment:
2730         // The current_font is not changed when we go from label to main text
2731         // and it should (along with realtmpfont) when we type the space.
2732         // CHECK There is a bug here! (Asger)
2733         
2734         LyXFont realtmpfont = real_current_font;
2735         LyXFont rawtmpfont = current_font;  /* store the current font.
2736                                      * This is because of the use
2737                                      * of cursor movements. The moving
2738                                      * cursor would refresh the 
2739                                      * current font */
2740
2741         // Get the font that is used to calculate the baselineskip
2742         LyXParagraph::size_type lastpos = cursor.par()->Last();
2743         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2744                                                            lastpos - 1);
2745
2746         bool jumped_over_space = false;
2747    
2748         if (!freeSpacing && IsLineSeparatorChar(c)) {
2749                 if ((cursor.pos() > 0 
2750                      && cursor.par()->IsLineSeparator(cursor.pos() - 1))
2751                     || (cursor.pos() > 0
2752                         && cursor.par()->IsNewline(cursor.pos() - 1))
2753                     || (cursor.pos() == 0
2754                         && !(cursor.par()->Previous()
2755                              && cursor.par()->Previous()->footnoteflag
2756                              == LyXParagraph::OPEN_FOOTNOTE))) {
2757                         if (cursor.pos() == 0 )
2758                                 bview->owner()->getMiniBuffer()->Set(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
2759                         else
2760                                 bview->owner()->getMiniBuffer()->Set(_("You cannot type two spaces this way.  Please read the Tutorial."));
2761                         charInserted();
2762                         return;
2763                 }
2764         } else if (IsNewlineChar(c)) {
2765                 if (cursor.par()->FirstPhysicalPar() == cursor.par()
2766                     && cursor.pos() <= BeginningOfMainBody(bview->buffer(), cursor.par())) {
2767                         charInserted();
2768                         return;
2769                 }
2770                 /* No newline at first position 
2771                  * of a paragraph or behind labels. 
2772                  * TeX does not allow that. */
2773                 
2774                 if (cursor.pos() < cursor.par()->Last() &&
2775                     cursor.par()->IsLineSeparator(cursor.pos()))
2776                         // newline always after a blank!
2777                         CursorRightIntern(bview);
2778                 cursor.row()->fill(-1);        // to force a new break
2779         }
2780    
2781         // the display inset stuff
2782         if (cursor.row()->par()->GetChar(cursor.row()->pos()) == LyXParagraph::META_INSET
2783             && cursor.row()->par()->GetInset(cursor.row()->pos())
2784             && cursor.row()->par()->GetInset(cursor.row()->pos())->display())
2785                 cursor.row()->fill(-1); // to force a new break  
2786
2787         // get the cursor row fist
2788         Row * row = cursor.row();
2789         long y = cursor.y() - row->baseline();
2790         if (c != LyXParagraph::META_INSET) /* Here case LyXText::InsertInset 
2791                                             * already insertet the character */
2792                 cursor.par()->InsertChar(cursor.pos(), c);
2793         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
2794
2795         if (!jumped_over_space) {
2796                 // refresh the positions
2797                 Row * tmprow = row;
2798                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2799                         tmprow = tmprow->next();
2800                         tmprow->pos(tmprow->pos() + 1);
2801                 }
2802         }
2803    
2804         // Is there a break one row above
2805         if ((cursor.par()->IsLineSeparator(cursor.pos())
2806              || cursor.par()->IsNewline(cursor.pos())
2807              || cursor.row()->fill() == -1)
2808             && row->previous() && row->previous()->par() == row->par()) {
2809                 LyXParagraph::size_type z = NextBreakPoint(bview,
2810                                                            row->previous(),
2811                                                            workWidth(bview));
2812                 if ( z >= row->pos()) {
2813                         row->pos(z + 1);
2814                         
2815                         // set the dimensions of the row above
2816                         row->previous()->fill(Fill(bview,
2817                                                    row->previous(),
2818                                                    workWidth(bview)));
2819
2820                         SetHeightOfRow(bview, row->previous());
2821              
2822                         y -= row->previous()->height();
2823                         refresh_y = y;
2824                         refresh_row = row->previous();
2825                         status = LyXText::NEED_MORE_REFRESH;
2826              
2827                         BreakAgainOneRow(bview, row);
2828
2829                         current_font = rawtmpfont;
2830                         real_current_font = realtmpfont;
2831                         SetCursor(bview, cursor.par(), cursor.pos() + 1,
2832                                   false, cursor.boundary());
2833                         // cursor MUST be in row now.
2834              
2835                         if (row->next() && row->next()->par() == row->par())
2836                                 need_break_row = row->next();
2837                         else
2838                                 need_break_row = 0;
2839              
2840                         // check, wether the last characters font has changed. 
2841                         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2842                             && rawparfont != rawtmpfont)
2843                                 RedoHeightOfParagraph(bview, cursor);
2844                         
2845                         charInserted();
2846                         return;
2847                 }
2848         }
2849    
2850         // recalculate the fill of the row
2851         if (row->fill() >= 0)  /* needed because a newline
2852                               * will set fill to -1. Otherwise
2853                               * we would not get a rebreak! */
2854                 row->fill(Fill(bview, row, workWidth(bview)));
2855         if (row->fill() < 0 ) {
2856                 refresh_y = y;
2857                 refresh_row = row; 
2858                 refresh_x = cursor.x();
2859                 refresh_pos = cursor.pos();
2860                 status = LyXText::NEED_MORE_REFRESH;
2861                 BreakAgainOneRow(bview, row); 
2862                 // will the cursor be in another row now?
2863                 if (RowLast(row) <= cursor.pos() + 1 && row->next()) {
2864                         if (row->next() && row->next()->par() == row->par())
2865                                 // this should always be true
2866                                 row = row->next();
2867                         BreakAgainOneRow(bview, row);
2868                 }
2869                 current_font = rawtmpfont;
2870                 real_current_font = realtmpfont;
2871
2872                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
2873                           cursor.boundary());
2874                 if (row->next() && row->next()->par() == row->par())
2875                         need_break_row = row->next();
2876                 else
2877                         need_break_row = 0;             
2878         } else {
2879                 refresh_y = y;
2880                 refresh_x = cursor.x();
2881                 refresh_row = row;
2882                 refresh_pos = cursor.pos();
2883                 
2884                 int tmpheight = row->height();
2885                 SetHeightOfRow(bview, row);
2886                 if (tmpheight == row->height())
2887                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2888                 else
2889                         status = LyXText::NEED_MORE_REFRESH;
2890             
2891                 current_font = rawtmpfont;
2892                 real_current_font = realtmpfont;
2893                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
2894                           cursor.boundary());
2895         }
2896
2897         // check, wether the last characters font has changed.
2898         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2899             && rawparfont != rawtmpfont) {
2900                 RedoHeightOfParagraph(bview, cursor);
2901         } else {
2902                 // now the special right address boxes
2903                 if (textclasslist.Style(bview->buffer()->params.textclass,
2904                                    cursor.par()->GetLayout()).margintype
2905                     == MARGIN_RIGHT_ADDRESS_BOX) {
2906                         RedoDrawingOfParagraph(bview, cursor); 
2907                 }
2908         }
2909
2910         charInserted();
2911 }
2912    
2913
2914 void LyXText::charInserted()
2915 {
2916         // Here we could call FinishUndo for every 20 characters inserted.
2917         // This is from my experience how emacs does it.
2918         static unsigned int counter = 0;
2919         if (counter < 20) {
2920                 ++counter;
2921         } else {
2922                 FinishUndo();
2923                 counter = 0;
2924         }
2925 }
2926
2927
2928 void LyXText::PrepareToPrint(BufferView * bview,
2929                              Row * row, float & x,
2930                              float & fill_separator, 
2931                              float & fill_hfill,
2932                              float & fill_label_hfill,
2933                              bool bidi) const
2934 {
2935         float nlh, ns;
2936         
2937         float w = row->fill();
2938         fill_hfill = 0;
2939         fill_label_hfill = 0;
2940         fill_separator = 0;
2941         fill_label_hfill = 0;
2942
2943 #ifndef NEW_INSETS
2944         bool is_rtl = row->par()->isRightToLeftPar(bview->buffer()->params);
2945
2946         if (is_rtl) {
2947                 x = RightMargin(bview->buffer(), row);
2948                 if (row->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
2949                         LyXFont font(LyXFont::ALL_SANE);
2950                         font.setSize(LyXFont::SIZE_SMALL);
2951                         x += lyxfont::width("Mwide-figM", font);
2952                 }
2953         } else
2954 #endif
2955                 if (workWidth(bview) > 0)
2956                 x = LeftMargin(bview, row);
2957         else
2958                 x = 0;
2959         
2960         // is there a manual margin with a manual label
2961         if (textclasslist.Style(bview->buffer()->params.textclass,
2962                            row->par()->GetLayout()).margintype == MARGIN_MANUAL
2963             && textclasslist.Style(bview->buffer()->params.textclass,
2964                               row->par()->GetLayout()).labeltype == LABEL_MANUAL) {
2965                
2966                 /* one more since labels are left aligned */ 
2967                 nlh = NumberOfLabelHfills(bview->buffer(), row) + 1;
2968                 if (nlh && !row->par()->GetLabelWidthString().empty()) {
2969                         fill_label_hfill = LabelFill(bview, row) / nlh;
2970                 }
2971         }
2972                 
2973         // are there any hfills in the row?
2974         float nh = NumberOfHfills(bview->buffer(), row);
2975
2976 #ifndef NEW_TABULAR
2977 /* table stuff -- begin*/
2978         if (row->par()->table) {
2979            w = workWidth(bview) - row->par()->table->WidthOfTable()
2980            - x - RightMargin(bview->buffer(), row);
2981            nh = 0; /* ignore hfills in tables */ 
2982         }
2983 /* table stuff -- end*/
2984 #endif
2985         if (nh)
2986           fill_hfill = w /nh;
2987         else  {
2988                 // is it block, flushleft or flushright? 
2989                 // set x how you need it
2990         int align;
2991         if (row->par()->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
2992           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
2993         else
2994           align = row->par()->FirstPhysicalPar()->align;
2995            
2996         // center displayed insets 
2997            if (row->par()->GetChar(row->pos()) == LyXParagraph::META_INSET
2998                && row->par()->GetInset(row->pos())
2999                && row->par()->GetInset(row->pos())->display())
3000              align = LYX_ALIGN_CENTER;
3001
3002            switch (align) {
3003             case LYX_ALIGN_BLOCK:
3004               ns = NumberOfSeparators(bview->buffer(), row);
3005               if (ns && row->next() && row->next()->par() == row->par() &&
3006                   !(row->next()->par()->IsNewline(row->next()->pos() - 1))
3007                   && !(row->next()->par()->GetChar(row->next()->pos()) == LyXParagraph::META_INSET
3008                        && row->next()->par()->GetInset(row->next()->pos())
3009                        && row->next()->par()->GetInset(row->next()->pos())->display())
3010                   )
3011                 fill_separator = w / ns;
3012               else if (is_rtl)
3013                 x += w;
3014               break;
3015             case LYX_ALIGN_RIGHT:
3016               x += w;
3017               break;
3018             case LYX_ALIGN_CENTER:
3019               x += w / 2;
3020               break;
3021            }
3022         }
3023         if (!bidi)
3024                 return;
3025
3026         ComputeBidiTables(bview->buffer(), row);
3027         if (is_rtl) {
3028                 LyXParagraph::size_type main_body = 
3029                         BeginningOfMainBody(bview->buffer(), row->par());
3030                 LyXParagraph::size_type last = RowLast(row);
3031
3032                 if (main_body > 0 &&
3033                     (main_body-1 > last || 
3034                      !row->par()->IsLineSeparator(main_body-1))) {
3035                         LyXLayout const & layout =
3036                                 textclasslist.Style(bview->buffer()->params.textclass,
3037                                                     row->par()->GetLayout());
3038                         x += lyxfont::width(layout.labelsep,
3039                                             GetFont(bview->buffer(), row->par(), -2));
3040                         if (main_body-1 <= last)
3041                                 x += fill_label_hfill;
3042                 }
3043         }
3044 }
3045       
3046 /* important for the screen */
3047
3048
3049 /* the cursor set functions have a special mechanism. When they
3050 * realize, that you left an empty paragraph, they will delete it.
3051 * They also delete the corresponding row */
3052
3053 void LyXText::CursorRightOneWord(BufferView * bview) const
3054 {
3055         // treat floats, HFills and Insets as words
3056         LyXCursor tmpcursor = cursor;
3057         // CHECK See comment on top of text.C
3058
3059         if (tmpcursor.pos() == tmpcursor.par()->Last()
3060             && tmpcursor.par()->Next()) {
3061                         tmpcursor.par(tmpcursor.par()->Next());
3062                         tmpcursor.pos(0);
3063         } else {
3064                 int steps = 0;
3065
3066                 // Skip through initial nonword stuff.
3067                 while ( tmpcursor.pos() < tmpcursor.par()->Last() &&
3068                         ! tmpcursor.par()->IsWord( tmpcursor.pos() ) ) 
3069                 {
3070                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
3071                         tmpcursor.pos(tmpcursor.pos() + 1);
3072                         ++steps;
3073                 }
3074                 // Advance through word.
3075                 while ( tmpcursor.pos() < tmpcursor.par()->Last() &&
3076                         tmpcursor.par()->IsWord( tmpcursor.pos() ) )
3077                 {
3078                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
3079                         tmpcursor.pos(tmpcursor.pos() + 1);
3080                         ++steps;
3081                 }
3082         }
3083         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3084 }
3085
3086
3087 void LyXText::CursorTab(BufferView * bview) const
3088 {
3089 #ifndef NEW_TABULAR
3090     if (cursor.par()->table) {
3091         int cell = NumberOfCell(cursor.par(), cursor.pos());
3092         while(cursor.par()->table->IsContRow(cell)) {
3093             CursorUp(bview);
3094             cell = NumberOfCell(cursor.par(), cursor.pos());
3095         }
3096         if (cursor.par()->table->ShouldBeVeryLastCell(cell))
3097             TableFeatures(bview, LyXTable::APPEND_ROW);
3098     }
3099 #endif
3100     LyXCursor tmpcursor = cursor;
3101     while (tmpcursor.pos() < tmpcursor.par()->Last()
3102            && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
3103         tmpcursor.pos(tmpcursor.pos() + 1);
3104    
3105     if (tmpcursor.pos() == tmpcursor.par()->Last()){
3106         if (tmpcursor.par()->Next()) {
3107             tmpcursor.par(tmpcursor.par()->Next());
3108             tmpcursor.pos(0);
3109         }
3110     } else
3111         tmpcursor.pos(tmpcursor.pos() + 1);
3112     SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3113 #ifndef NEW_TABULAR
3114     if (cursor.par()->table) {
3115         int cell = NumberOfCell(cursor.par(), cursor.pos());
3116         while (cursor.par()->table->IsContRow(cell) &&
3117                !cursor.par()->table->ShouldBeVeryLastCell(cell)) {
3118             tmpcursor = cursor;
3119             while (tmpcursor.pos() < tmpcursor.par()->Last()
3120                    && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
3121                 tmpcursor.pos(tmpcursor.pos() + 1);
3122    
3123             if (tmpcursor.pos() == tmpcursor.par()->Last()){
3124                 if (tmpcursor.par()->Next()) {
3125                     tmpcursor.par(tmpcursor.par()->Next());
3126                     tmpcursor.pos(0);
3127                 }
3128             } else
3129                 tmpcursor.pos(tmpcursor.pos() + 1);
3130             SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3131             cell = NumberOfCell(cursor.par(), cursor.pos());
3132         }
3133     }
3134 #endif
3135 }
3136
3137
3138 /* -------> Skip initial whitespace at end of word and move cursor to *start*
3139             of prior word, not to end of next prior word. */
3140
3141 void LyXText::CursorLeftOneWord(BufferView * bview)  const
3142 {
3143         // treat HFills, floats and Insets as words
3144         LyXCursor tmpcursor = cursor;
3145         while (tmpcursor.pos() 
3146                && (tmpcursor.par()->IsSeparator(tmpcursor.pos() - 1) 
3147                    || tmpcursor.par()->IsKomma(tmpcursor.pos() - 1))
3148                && !(tmpcursor.par()->IsHfill(tmpcursor.pos() - 1)
3149                     || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
3150                     || tmpcursor.par()->IsInset(tmpcursor.pos() - 1)))
3151                 tmpcursor.pos(tmpcursor.pos() - 1);
3152
3153         if (tmpcursor.pos()
3154             && (tmpcursor.par()->IsInset(tmpcursor.pos() - 1)
3155                 || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
3156                 || tmpcursor.par()->IsHfill(tmpcursor.pos() - 1))) {
3157                 tmpcursor.pos(tmpcursor.pos() - 1);
3158         } else if (!tmpcursor.pos()) {
3159                 if (tmpcursor.par()->Previous()){
3160                         tmpcursor.par(tmpcursor.par()->Previous());
3161                         tmpcursor.pos(tmpcursor.par()->Last());
3162                 }
3163         } else {                // Here, tmpcursor != 0 
3164                 while (tmpcursor.pos() > 0 &&
3165                        tmpcursor.par()->IsWord(tmpcursor.pos()-1) )
3166                         tmpcursor.pos(tmpcursor.pos() - 1);
3167         }
3168         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3169 }
3170
3171 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
3172                         patched as well. */
3173
3174 void LyXText::SelectWord(BufferView * bview) 
3175 {
3176         // Move cursor to the beginning, when not already there.
3177         if ( cursor.pos()
3178              && !cursor.par()->IsSeparator(cursor.pos()-1)
3179              && !cursor.par()->IsKomma(cursor.pos()-1) )
3180                 CursorLeftOneWord(bview);
3181
3182         // set the sel cursor
3183         sel_cursor = cursor;
3184
3185         while ( cursor.pos() < cursor.par()->Last()
3186                         && !cursor.par()->IsSeparator(cursor.pos())
3187                         && !cursor.par()->IsKomma(cursor.pos()) )
3188                 cursor.pos(cursor.pos() + 1);
3189         SetCursor(bview, cursor.par(), cursor.pos() );
3190         
3191         // finally set the selection
3192         SetSelection();
3193 }
3194
3195
3196 /* -------> Select the word currently under the cursor when:
3197                         1: no selection is currently set,
3198                         2: the cursor is not at the borders of the word. */
3199
3200 bool LyXText::SelectWordWhenUnderCursor(BufferView * bview) 
3201 {
3202         if (!selection &&
3203             cursor.pos() > 0 && cursor.pos() < cursor.par()->Last()
3204             && !cursor.par()->IsSeparator(cursor.pos())
3205             && !cursor.par()->IsKomma(cursor.pos())
3206             && !cursor.par()->IsSeparator(cursor.pos() -1)
3207             && !cursor.par()->IsKomma(cursor.pos() -1) ) {
3208                 SelectWord(bview);
3209                 return true;
3210         }
3211         return false;
3212 }
3213
3214
3215 // This function is only used by the spellchecker for NextWord().
3216 // It doesn't handle LYX_ACCENTs and probably never will.
3217 char * LyXText::SelectNextWord(BufferView * bview, float & value)
3218 {
3219         LyXParagraph * tmppar = cursor.par();
3220         
3221         // If this is not the very first word, skip rest of
3222         // current word because we are probably in the middle
3223         // of a word if there is text here.
3224         if (cursor.pos() || cursor.par()->previous) {
3225                 while (cursor.pos() < cursor.par()->Last()
3226                        && cursor.par()->IsLetter(cursor.pos()))
3227                         cursor.pos(cursor.pos() + 1);
3228         }
3229         // Now, skip until we have real text (will jump paragraphs)
3230         while ((cursor.par()->Last() > cursor.pos()
3231                 && (!cursor.par()->IsLetter(cursor.pos())
3232                     || cursor.par()->getFont(bview->buffer()->params, cursor.pos())
3233                     .latex() == LyXFont::ON))
3234                || (cursor.par()->Last() == cursor.pos() 
3235                    && cursor.par()->Next())){
3236                 if (cursor.pos() == cursor.par()->Last()) {
3237                         cursor.par(cursor.par()->Next());
3238                         cursor.pos(0);
3239                 } else
3240                         cursor.pos(cursor.pos() + 1);
3241         }
3242   
3243         // Update the value if we changed paragraphs
3244         if (cursor.par() != tmppar){
3245                 SetCursor(bview, cursor.par(), cursor.pos());
3246                 value = float(cursor.y())/float(height);
3247         }
3248
3249         // Start the selection from here
3250         sel_cursor = cursor;
3251
3252 #ifdef HAVE_SSTREAM
3253         std::ostringstream latex;
3254 #else
3255         ostrstream latex;
3256 #endif
3257         // and find the end of the word 
3258         // (optional hyphens are part of a word)
3259         while (cursor.pos() < cursor.par()->Last()
3260                && (cursor.par()->IsLetter(cursor.pos())) 
3261                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
3262                        && cursor.par()->GetInset(cursor.pos()) != 0
3263                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
3264 #ifdef HAVE_SSTREAM
3265                        && latex.str() == "\\-"
3266 #else
3267                        && latex.str() // protect against null pointers         
3268                        && string(latex.str(), 3) == "\\-" // this is not nice at all
3269 #endif
3270                            ))
3271                 cursor.pos(cursor.pos() + 1);
3272
3273 #ifndef HAVE_SSTREAM
3274         delete [] latex.str();
3275 #endif
3276         // Finally, we copy the word to a string and return it
3277         char * str = 0;
3278
3279         if (sel_cursor.pos() < cursor.pos()) {
3280                 str = new char [cursor.pos() - sel_cursor.pos() + 2];
3281                 LyXParagraph::size_type i, j;
3282                 for (i = sel_cursor.pos(), j = 0; i < cursor.pos(); ++i) {
3283                         if (cursor.par()->GetChar(i) != LyXParagraph::META_INSET)
3284                                 str[j++] = cursor.par()->GetChar(i);
3285                 }
3286                 str[j] = '\0';
3287         }
3288         return str;
3289 }
3290
3291
3292 // This one is also only for the spellchecker
3293 void LyXText::SelectSelectedWord(BufferView * bview)
3294 {
3295         // move cursor to the beginning
3296         SetCursor(bview, sel_cursor.par(), sel_cursor.pos());
3297         
3298         // set the sel cursor
3299         sel_cursor = cursor;
3300
3301 #ifdef HAVE_SSTREAM
3302         std::ostringstream latex;
3303 #else
3304         ostrstream latex;
3305 #endif
3306         
3307         // now find the end of the word
3308         while (cursor.pos() < cursor.par()->Last()
3309                && (cursor.par()->IsLetter(cursor.pos())
3310                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
3311                        && cursor.par()->GetInset(cursor.pos()) != 0
3312                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
3313 #ifdef HAVE_SSTREAM
3314                        && latex.str() == "\\-"
3315 #else
3316                        && string(latex.str(), 3) == "\\-"
3317 #endif
3318                            )))
3319                 cursor.pos(cursor.pos() + 1);
3320         
3321 #ifndef HAVE_SSTREAM
3322         delete [] latex.str();
3323 #endif
3324         SetCursor(bview, cursor.par(), cursor.pos());
3325         
3326         // finally set the selection
3327         SetSelection();
3328 }
3329
3330
3331 /* -------> Delete from cursor up to the end of the current or next word. */
3332 void LyXText::DeleteWordForward(BufferView * bview)
3333 {
3334         if (!cursor.par()->Last())
3335                 CursorRight(bview);
3336         else {
3337                 LyXCursor tmpcursor = cursor;
3338                 tmpcursor.row(0); // ??
3339                 selection = true; // to avoid deletion 
3340                 CursorRightOneWord(bview);
3341                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3342                 sel_cursor = cursor;
3343                 cursor = tmpcursor;
3344                 SetSelection(); 
3345                 
3346                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
3347                 CutSelection(bview);
3348         }
3349 }
3350
3351
3352 /* -------> Delete from cursor to start of current or prior word. */
3353 void LyXText::DeleteWordBackward(BufferView * bview)
3354 {
3355        if (!cursor.par()->Last())
3356                CursorLeft(bview);
3357        else {
3358                LyXCursor tmpcursor = cursor;
3359                tmpcursor.row(0); // ??
3360                selection = true; // to avoid deletion 
3361                CursorLeftOneWord(bview);
3362                SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3363                sel_cursor = cursor;
3364                cursor = tmpcursor;
3365                SetSelection();
3366                CutSelection(bview);
3367        }
3368 }
3369
3370
3371 /* -------> Kill to end of line. */
3372 void LyXText::DeleteLineForward(BufferView * bview)
3373 {
3374         if (!cursor.par()->Last())
3375                 // Paragraph is empty, so we just go to the right
3376                 CursorRight(bview);
3377         else {
3378                 LyXCursor tmpcursor = cursor;
3379                 // We can't store the row over a regular SetCursor
3380                 // so we set it to 0 and reset it afterwards.
3381                 tmpcursor.row(0); // ??
3382                 selection = true; // to avoid deletion 
3383                 CursorEnd(bview);
3384                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3385                 sel_cursor = cursor;
3386                 cursor = tmpcursor;
3387                 SetSelection();
3388                 // What is this test for ??? (JMarc)
3389                 if (!selection) {
3390                         DeleteWordForward(bview);
3391                 } else {
3392                         CutSelection(bview);
3393                 }
3394         }
3395 }
3396
3397
3398 // Change the case of a word at cursor position. 
3399 // This function directly manipulates LyXParagraph::text because there
3400 // is no LyXParagraph::SetChar currently. I did what I could to ensure
3401 // that it is correct. I guess part of it should be moved to
3402 // LyXParagraph, but it will have to change for 1.1 anyway. At least
3403 // it does not access outside of the allocated array as the older
3404 // version did. (JMarc) 
3405 void LyXText::ChangeWordCase(BufferView * bview, LyXText::TextCase action) 
3406 {
3407         LyXParagraph * tmppar = cursor.par()->ParFromPos(cursor.pos());
3408
3409         SetUndo(bview->buffer(),Undo::FINISH, tmppar->previous, tmppar->next); 
3410
3411         LyXParagraph::size_type tmppos = 
3412                 cursor.par()->PositionInParFromPos(cursor.pos());
3413         while (tmppos < tmppar->size()) {
3414                 unsigned char c = tmppar->GetChar(tmppos);
3415                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
3416                         break;
3417                 if (c != LyXParagraph::META_INSET) {
3418                         switch (action) {
3419                         case text_lowercase:
3420                                 c = tolower(c);
3421                                 break;
3422                         case text_capitalization:
3423                                 c = toupper(c);
3424                                 action = text_lowercase;
3425                                 break;
3426                         case text_uppercase:
3427                                 c = toupper(c);
3428                                 break;
3429                         }
3430                 }
3431                 
3432                 //tmppar->text[tmppos] = c;
3433                 tmppar->SetChar(tmppos, c);
3434                 ++tmppos;
3435         }
3436         CheckParagraph(bview, tmppar, tmppos);
3437         CursorRightOneWord(bview);
3438 }
3439
3440
3441 void LyXText::Delete(BufferView * bview)
3442 {
3443         // this is a very easy implementation
3444
3445         LyXCursor old_cursor = cursor;
3446         int old_cur_par_id = old_cursor.par()->id();
3447         int old_cur_par_prev_id = old_cursor.par()->previous ?
3448                 old_cursor.par()->previous->id() : 0;
3449         
3450         // just move to the right
3451         CursorRightIntern(bview);
3452
3453         // CHECK Look at the comment here.
3454         // This check is not very good...
3455         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
3456         // and that can very well delete the par or par->previous in
3457         // old_cursor. Will a solution where we compare paragraph id's
3458         //work better?
3459         if ((cursor.par()->previous ? cursor.par()->previous->id() : 0)
3460             == old_cur_par_prev_id
3461             && cursor.par()->id() != old_cur_par_id)
3462                 return; // delete-empty-paragraph-mechanism has done it
3463
3464         // if you had success make a backspace
3465         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
3466                 LyXCursor tmpcursor = cursor;
3467                 cursor = old_cursor; // to make sure undo gets the right cursor position
3468                 SetUndo(bview->buffer(), Undo::DELETE, 
3469                         cursor.par()->ParFromPos(cursor.pos())->previous, 
3470                         cursor.par()->ParFromPos(cursor.pos())->next); 
3471                 cursor = tmpcursor;
3472                 Backspace(bview);
3473         }
3474 }
3475
3476
3477 void LyXText::Backspace(BufferView * bview)
3478 {
3479 #ifndef NEW_TABULAR
3480         /* table stuff -- begin */
3481         if (cursor.par()->table) {
3482                 BackspaceInTable(bview);
3483                 return;
3484         }
3485         /* table stuff -- end */
3486 #endif
3487         // LyXFont rawtmpfont = current_font;
3488         // LyXFont realtmpfont = real_current_font;
3489         //    We don't need the above variables as calling to SetCursor() with third
3490         //    argument eqaul to false, will not change current_font & real_current_font
3491         
3492         // Get the font that is used to calculate the baselineskip
3493         LyXParagraph::size_type lastpos = cursor.par()->Last();
3494         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
3495                                                          lastpos - 1);
3496
3497         if (cursor.pos() == 0) {
3498                 // The cursor is at the beginning of a paragraph, so the the backspace
3499                 // will collapse two paragraphs into one.
3500                 
3501                 // we may paste some paragraphs
3502       
3503                 // is it an empty paragraph?
3504       
3505                 if ((lastpos == 0
3506                      || (lastpos == 1 && cursor.par()->IsSeparator(0)))
3507                     && !(cursor.par()->Next() 
3508                          && cursor.par()->footnoteflag == LyXParagraph::NO_FOOTNOTE
3509                          && cursor.par()->Next()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)) {
3510                         // This is an empty paragraph and we delete it just by moving the cursor one step
3511                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
3512                         // of the paragraph.
3513                         
3514                         if (cursor.par()->previous) {
3515                                 LyXParagraph * tmppar = cursor.par()->previous->FirstPhysicalPar();
3516                                 if (cursor.par()->GetLayout() == tmppar->GetLayout()
3517                                     && cursor.par()->footnoteflag == tmppar->footnoteflag
3518                                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
3519                                         // Inherit botom DTD from the paragraph below.
3520                                         // (the one we are deleting)
3521                                         tmppar->line_bottom = cursor.par()->line_bottom;
3522                                         tmppar->added_space_bottom = cursor.par()->added_space_bottom;
3523                                         tmppar->pagebreak_bottom = cursor.par()->pagebreak_bottom;
3524                                 }
3525                                 
3526                                 CursorLeftIntern(bview);
3527                      
3528                                 // the layout things can change the height of a row !
3529                                 int tmpheight = cursor.row()->height();
3530                                 SetHeightOfRow(bview, cursor.row());
3531                                 if (cursor.row()->height() != tmpheight) {
3532                                         refresh_y = cursor.y() - cursor.row()->baseline();
3533                                         refresh_row = cursor.row();
3534                                         status = LyXText::NEED_MORE_REFRESH;
3535                                 }
3536                                 return;
3537                         }
3538                 }
3539                 
3540                 if (cursor.par()->ParFromPos(cursor.pos())->previous){
3541                         SetUndo(bview->buffer(), Undo::DELETE,
3542                                 cursor.par()->ParFromPos(cursor.pos())->previous->previous,
3543                                 cursor.par()->ParFromPos(cursor.pos())->next);
3544                 }
3545                 
3546                 LyXParagraph * tmppar = cursor.par();
3547                 Row * tmprow = cursor.row();
3548
3549                 // We used to do CursorLeftIntern() here, but it is
3550                 // not a good idea since it triggers the auto-delete
3551                 // mechanism. So we do a CursorLeftIntern()-lite,
3552                 // without the dreaded mechanism. (JMarc)
3553                 if (cursor.par()->Previous()) { 
3554                         // steps into the above paragraph.
3555                         SetCursorIntern(bview, cursor.par()->Previous(), 
3556                                         cursor.par()->Previous()->Last(), false);
3557                 }
3558
3559                 /* Pasting is not allowed, if the paragraphs have different
3560                    layout. I think it is a real bug of all other
3561                    word processors to allow it. It confuses the user.
3562                    Even so with a footnote paragraph and a non-footnote
3563                    paragraph. I will not allow pasting in this case, 
3564                    because the user would be confused if the footnote behaves 
3565                    different wether it is open or closed.
3566                   
3567                    Correction: Pasting is always allowed with standard-layout
3568                 */
3569                 if (cursor.par() != tmppar
3570                     && (cursor.par()->GetLayout() == tmppar->GetLayout()
3571                         || tmppar->GetLayout() == 0 /*standard*/)
3572                     && cursor.par()->footnoteflag == tmppar->footnoteflag
3573 #ifndef NEW_TABULAR
3574                     /* table stuff -- begin*/
3575                     && !cursor.par()->table /* no pasting of tables */ 
3576                     /* table stuff -- end*/
3577 #endif
3578                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
3579
3580                         RemoveParagraph(tmprow);
3581                         RemoveRow(tmprow);
3582                         cursor.par()->PasteParagraph(bview->buffer()->params);
3583                         
3584                         if (!cursor.pos() || !cursor.par()->IsSeparator(cursor.pos() - 1))
3585                                 ; //cursor.par()->InsertChar(cursor.pos(), ' ');
3586                         // strangely enough it seems that commenting out the line above removes
3587                         // most or all of the segfaults. I will however also try to move the
3588                         // two Remove... lines in front of the PasteParagraph too.
3589                         else
3590                                 if (cursor.pos())
3591                                         cursor.pos(cursor.pos() - 1);
3592                         
3593                         status = LyXText::NEED_MORE_REFRESH;
3594                         refresh_row = cursor.row();
3595                         refresh_y = cursor.y() - cursor.row()->baseline();
3596                         
3597                         // remove the lost paragraph
3598                         // This one is not safe, since the paragraph that the tmprow and the
3599                         // following rows belong to has been deleted by the PasteParagraph
3600                         // above. The question is... could this be moved in front of the
3601                         // PasteParagraph?
3602                         //RemoveParagraph(tmprow);
3603                         //RemoveRow(tmprow);  
3604                         
3605                         // This rebuilds the rows.
3606                         AppendParagraph(bview, cursor.row());
3607                         UpdateCounters(bview, cursor.row());
3608                         
3609                         // the row may have changed, block, hfills etc.
3610                         SetCursor(bview, cursor.par(), cursor.pos(), false);
3611                 }
3612         } else {
3613                 /* this is the code for a normal backspace, not pasting
3614                  * any paragraphs */ 
3615                 SetUndo(bview->buffer(), Undo::DELETE, 
3616                         cursor.par()->ParFromPos(cursor.pos())->previous, 
3617                         cursor.par()->ParFromPos(cursor.pos())->next); 
3618                 // We used to do CursorLeftIntern() here, but it is
3619                 // not a good idea since it triggers the auto-delete
3620                 // mechanism. So we do a CursorLeftIntern()-lite,
3621                 // without the dreaded mechanism. (JMarc)
3622                 SetCursorIntern(bview, cursor.par(), cursor.pos()- 1,
3623                                 false, cursor.boundary());
3624                 
3625                 // some insets are undeletable here
3626                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
3627                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
3628                                 return; 
3629                         // force complete redo when erasing display insets
3630                         // this is a cruel method but safe..... Matthias 
3631                         if (cursor.par()->GetInset(cursor.pos())->display()){
3632                                 cursor.par()->Erase(cursor.pos());
3633                                 RedoParagraph(bview);
3634                                 return;
3635                         }
3636                 }
3637                 
3638                 Row * row = cursor.row();
3639                 long y = cursor.y() - row->baseline();
3640                 LyXParagraph::size_type z;
3641                 /* remember that a space at the end of a row doesnt count
3642                  * when calculating the fill */ 
3643                 if (cursor.pos() < RowLast(row) ||
3644                     !cursor.par()->IsLineSeparator(cursor.pos())) {
3645                         row->fill(row->fill() + SingleWidth(bview,
3646                                                             cursor.par(),
3647                                                             cursor.pos()));
3648                 }
3649                 
3650                 /* some special code when deleting a newline. This is similar
3651                  * to the behavior when pasting paragraphs */ 
3652                 if (cursor.pos() && cursor.par()->IsNewline(cursor.pos())) {
3653                         cursor.par()->Erase(cursor.pos());
3654                         // refresh the positions
3655                         Row * tmprow = row;
3656                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
3657                                 tmprow = tmprow->next();
3658                                 tmprow->pos(tmprow->pos() - 1);
3659                         }
3660                         if (cursor.par()->IsLineSeparator(cursor.pos() - 1))
3661                                 cursor.pos(cursor.pos() - 1);
3662                         
3663                         if (cursor.pos() < cursor.par()->Last() && !cursor.par()->IsSeparator(cursor.pos())) {
3664                                 cursor.par()->InsertChar(cursor.pos(), ' ');
3665                                 // refresh the positions
3666                                 tmprow = row;
3667                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
3668                                         tmprow = tmprow->next();
3669                                         tmprow->pos(tmprow->pos() + 1);
3670                                 }
3671                         }
3672                 } else {
3673                         cursor.par()->Erase(cursor.pos());
3674                         
3675                         // refresh the positions
3676                         Row * tmprow = row;
3677                         while (tmprow->next()
3678                                && tmprow->next()->par() == row->par()) {
3679                                 tmprow = tmprow->next();
3680                                 tmprow->pos(tmprow->pos() - 1);
3681                         }
3682
3683                         // delete newlines at the beginning of paragraphs
3684                         while (cursor.par()->Last() &&
3685                                cursor.par()->IsNewline(cursor.pos()) &&
3686                                cursor.pos() == BeginningOfMainBody(bview->buffer(),
3687                                                                    cursor.par())) {
3688                                 cursor.par()->Erase(cursor.pos());
3689                                 // refresh the positions
3690                                 tmprow = row;
3691                                 while (tmprow->next() && 
3692                                        tmprow->next()->par() == row->par()) {
3693                                         tmprow = tmprow->next();
3694                                         tmprow->pos(tmprow->pos() - 1);
3695                                 }
3696                         }
3697                 }
3698                 
3699                 // is there a break one row above
3700                 if (row->previous() && row->previous()->par() == row->par()) {
3701                         z = NextBreakPoint(bview, row->previous(),
3702                                            workWidth(bview));
3703                         if ( z >= row->pos()) {
3704                                 row->pos(z + 1);
3705                                 
3706                                 Row * tmprow = row->previous();
3707                                 
3708                                 // maybe the current row is now empty
3709                                 if (row->pos() >= row->par()->Last()) {
3710                                         // remove it
3711                                         RemoveRow(row);
3712                                         need_break_row = 0;
3713                                 } else {
3714                                         BreakAgainOneRow(bview, row);
3715                                         if (row->next() && row->next()->par() == row->par())
3716                                                 need_break_row = row->next();
3717                                         else
3718                                                 need_break_row = 0;
3719                                 }
3720                                 
3721                                 // set the dimensions of the row above
3722                                 y -= tmprow->height();
3723                                 tmprow->fill(Fill(bview, tmprow,
3724                                                   workWidth(bview)));
3725                                 SetHeightOfRow(bview, tmprow);
3726                                 
3727                                 refresh_y = y;
3728                                 refresh_row = tmprow;
3729                                 status = LyXText::NEED_MORE_REFRESH;
3730                                 SetCursor(bview, cursor.par(), cursor.pos(),
3731                                           false, cursor.boundary());
3732                                 //current_font = rawtmpfont;
3733                                 //real_current_font = realtmpfont;
3734                                 // check, whether the last character's font has changed.
3735                                 if (rawparfont !=
3736                                     cursor.par()->GetFontSettings(bview->buffer()->params,
3737                                                                   cursor.par()->Last() - 1))
3738                                         RedoHeightOfParagraph(bview, cursor);
3739                                 return;
3740                         }
3741                 }
3742                 
3743                 // break the cursor row again
3744                 z = NextBreakPoint(bview, row, workWidth(bview));
3745                 
3746                 if (z != RowLast(row) || 
3747                     (row->next() && row->next()->par() == row->par() &&
3748                      RowLast(row) == row->par()->Last() - 1)){
3749                         
3750                         /* it can happen that a paragraph loses one row
3751                          * without a real breakup. This is when a word
3752                          * is to long to be broken. Well, I don t care this 
3753                          * hack ;-) */ 
3754                         if (row->next() && row->next()->par() == row->par() &&
3755                             RowLast(row) == row->par()->Last() - 1)
3756                                 RemoveRow(row->next());
3757                         
3758                         refresh_y = y;
3759                         refresh_row = row;
3760                         status = LyXText::NEED_MORE_REFRESH;
3761                         
3762                         BreakAgainOneRow(bview, row);
3763                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3764                         // cursor MUST be in row now
3765                         
3766                         if (row->next() && row->next()->par() == row->par())
3767                                 need_break_row = row->next();
3768                         else
3769                                 need_break_row = 0;
3770                 } else  {
3771                         // set the dimensions of the row
3772                         row->fill(Fill(bview, row, workWidth(bview)));
3773                         int tmpheight = row->height();
3774                         SetHeightOfRow(bview, row);
3775                         if (tmpheight == row->height())
3776                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
3777                         else
3778                                 status = LyXText::NEED_MORE_REFRESH;
3779                         refresh_y = y;
3780                         refresh_row = row;
3781                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3782                 }
3783         }
3784
3785         // current_font = rawtmpfont;
3786         // real_current_font = realtmpfont;
3787
3788         lastpos = cursor.par()->Last();
3789         if (cursor.pos() == lastpos) {
3790                 SetCurrentFont(bview);
3791                 if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos()) != cursor.boundary())
3792                         SetCursor(bview, cursor.par(), cursor.pos(), false, !cursor.boundary());
3793         }
3794         
3795         // check, wether the last characters font has changed.
3796         if (rawparfont != 
3797             cursor.par()->GetFontSettings(bview->buffer()->params, lastpos - 1)) {
3798                 RedoHeightOfParagraph(bview, cursor);
3799         } else {
3800                 // now the special right address boxes
3801                 if (textclasslist.Style(bview->buffer()->params.textclass,
3802                                         cursor.par()->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3803                         RedoDrawingOfParagraph(bview, cursor); 
3804                 }
3805         }
3806 }
3807
3808
3809 void LyXText::GetVisibleRow(BufferView * bview, int y_offset, int x_offset,
3810                             Row * row_ptr, long y)
3811 {
3812         /* returns a printed row */
3813         Painter & pain = bview->painter();
3814         
3815         bool is_rtl = row_ptr->par()->isRightToLeftPar(bview->buffer()->params);
3816         LyXParagraph::size_type last = RowLastPrintable(row_ptr);
3817
3818         LyXParagraph::size_type vpos, pos;
3819         float x, tmpx;
3820         int y_top, y_bottom;
3821         float fill_separator, fill_hfill, fill_label_hfill;
3822
3823         LyXFont font(LyXFont::ALL_SANE);
3824         int maxdesc;
3825         if (row_ptr->height() <= 0) {
3826                 lyxerr << "LYX_ERROR: row.height: "
3827                        << row_ptr->height() << endl;
3828                 return;
3829         }
3830         PrepareToPrint(bview, row_ptr, x, fill_separator,
3831                        fill_hfill, fill_label_hfill);
3832         
3833         x += x_offset;
3834         
3835         // clear the area where we want to paint/print
3836         int ww;
3837         ww = bview->workWidth();
3838
3839         bool clear_area = true;
3840
3841         if ((last == row_ptr->pos()) &&
3842             (row_ptr->par()->GetChar(row_ptr->pos()) == LyXParagraph::META_INSET) &&
3843             (row_ptr->par()->GetInset(row_ptr->pos())))
3844         {
3845                 clear_area = row_ptr->par()->GetInset(row_ptr->pos())->doClearArea();
3846         }
3847         if (clear_area) {
3848                 int w;
3849                 if (inset_owner)
3850                         w = inset_owner->width(bview->painter(), font);
3851                 else
3852                         w = ww;
3853                 pain.fillRectangle(x_offset, y_offset, w, row_ptr->height());
3854         }
3855         
3856         if (selection) {
3857                 /* selection code */
3858                 if (bidi_same_direction) {
3859                         if (sel_start_cursor.row() == row_ptr &&
3860                             sel_end_cursor.row() == row_ptr) {
3861                                 if (sel_start_cursor.x() < sel_end_cursor.x())
3862                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3863                                                            y_offset,
3864                                                            sel_end_cursor.x() - sel_start_cursor.x(),
3865                                                            row_ptr->height(),
3866                                                            LColor::selection);
3867                                 else
3868                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3869                                                            y_offset,
3870                                                            sel_start_cursor.x() - sel_end_cursor.x(),
3871                                                            row_ptr->height(),
3872                                                            LColor::selection);
3873                         } else if (sel_start_cursor.row() == row_ptr) {
3874                                 if (is_rtl)
3875                                         pain.fillRectangle(x_offset, y_offset,
3876                                                            sel_start_cursor.x(),
3877                                                            row_ptr->height(),
3878                                                            LColor::selection);
3879                                 else
3880                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3881                                                            y_offset,
3882                                                            ww - sel_start_cursor.x(),
3883                                                            row_ptr->height(),
3884                                                            LColor::selection);
3885                         } else if (sel_end_cursor.row() == row_ptr) {
3886                                 if (is_rtl)
3887                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3888                                                            y_offset,
3889                                                            ww - sel_end_cursor.x(),
3890                                                            row_ptr->height(),
3891                                                            LColor::selection);
3892                                 else
3893                                         pain.fillRectangle(x_offset, y_offset,
3894                                                            sel_end_cursor.x(),
3895                                                            row_ptr->height(),
3896                                                            LColor::selection);
3897                         } else if (y > long(sel_start_cursor.y())
3898                                    && y < long(sel_end_cursor.y())) {
3899                                 pain.fillRectangle(x_offset, y_offset, ww,
3900                                                    row_ptr->height(),
3901                                                    LColor::selection);
3902                         }
3903                 } else if ( sel_start_cursor.row() != row_ptr &&
3904                             sel_end_cursor.row() != row_ptr &&
3905                             y > long(sel_start_cursor.y())
3906                             && y < long(sel_end_cursor.y())) {
3907                         pain.fillRectangle(x_offset, y_offset, ww,
3908                                            row_ptr->height(),
3909                                            LColor::selection);
3910                 } else if (sel_start_cursor.row() == row_ptr ||
3911                            sel_end_cursor.row() == row_ptr) {
3912                         float tmpx = x;
3913                         int cell = 0;
3914 #ifndef NEW_TABULAR
3915                         if (row_ptr->par()->table) {
3916                                 cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
3917                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3918                         }
3919 #endif
3920                         if ( (sel_start_cursor.row() != row_ptr && !is_rtl) ||
3921                              (sel_end_cursor.row() != row_ptr && is_rtl))
3922                                 pain.fillRectangle(x_offset, y_offset,
3923                                                    int(tmpx),
3924                                                    row_ptr->height(),
3925                                                    LColor::selection);
3926 #ifndef NEW_TABULAR
3927                         if (row_ptr->par()->table) {
3928                                 float x_old = x;
3929                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3930                                         pos = vis2log(vpos);
3931                                         float old_tmpx = tmpx;
3932                                         if (row_ptr->par()->IsNewline(pos)) {
3933                                                 tmpx = x_old + row_ptr->par()->table->WidthOfColumn(cell);
3934                                                 x_old = tmpx;
3935                                                 ++cell;
3936                                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3937                                         } else {
3938                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3939                                         }
3940                                         if ( (sel_start_cursor.row() != row_ptr ||
3941                                               sel_start_cursor.pos() <= pos) &&
3942                                              (sel_end_cursor.row() != row_ptr ||
3943                                               pos < sel_end_cursor.pos()) )
3944                                                 pain.fillRectangle(x_offset + int(old_tmpx),
3945                                                                    y_offset,
3946                                                                    int(tmpx - old_tmpx + 1),
3947                                                                    row_ptr->height(),
3948                                                                    LColor::selection);
3949                                 }
3950                         } else {
3951 #endif
3952                                 LyXParagraph::size_type main_body =
3953                                         BeginningOfMainBody(bview->buffer(),
3954                                                             row_ptr->par());
3955
3956                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3957                                         pos = vis2log(vpos);
3958                                         float old_tmpx = tmpx;
3959                                         if (main_body > 0 && pos == main_body-1) {
3960                                                 tmpx += fill_label_hfill +
3961                                                         lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
3962                                                                                            row_ptr->par()->GetLayout()).labelsep,
3963                                                                        GetFont(bview->buffer(),row_ptr->par(), -2));
3964                                                 if (row_ptr->par()->IsLineSeparator(main_body-1))
3965                                                         tmpx -= SingleWidth(bview, row_ptr->par(), main_body-1);
3966                                         }
3967                                         if (HfillExpansion(bview->buffer(), row_ptr, pos)) {
3968                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3969                                                 if (pos >= main_body)
3970                                                         tmpx += fill_hfill;
3971                                                 else 
3972                                                         tmpx += fill_label_hfill;
3973                                         }
3974                                         else if (row_ptr->par()->IsSeparator(pos)) {
3975                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3976                                                 if (pos >= main_body)
3977                                                         tmpx += fill_separator;
3978                                         } else
3979                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
3980
3981                                         if ( (sel_start_cursor.row() != row_ptr ||
3982                                               sel_start_cursor.pos() <= pos) &&
3983                                              (sel_end_cursor.row() != row_ptr ||
3984                                               pos < sel_end_cursor.pos()) )
3985                                                 pain.fillRectangle(x_offset + int(old_tmpx),
3986                                                                    y_offset,
3987                                                                    int(tmpx - old_tmpx + 1),
3988                                                                    row_ptr->height(),
3989                                                                    LColor::selection);
3990                                 }
3991 #ifndef NEW_TABULAR
3992                         }
3993 #endif
3994                         if ( (sel_start_cursor.row() != row_ptr && is_rtl) ||
3995                              (sel_end_cursor.row() != row_ptr && !is_rtl) )
3996                                 pain.fillRectangle(x_offset + int(tmpx),
3997                                                    y_offset,
3998                                                    int(ww - tmpx),
3999                                                    row_ptr->height(),
4000                                                    LColor::selection);
4001                 }
4002         }
4003
4004         int box_x = 0;
4005 #ifndef NEW_INSETS
4006         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
4007                 LyXFont font(LyXFont::ALL_SANE);
4008                 font.setSize(LyXFont::SIZE_FOOTNOTE);
4009                 font.setColor(LColor::footnote);
4010                 
4011                 box_x = LYX_PAPER_MARGIN + lyxfont::width(" wide-tab ", font);
4012                 if (row_ptr->previous() &&
4013                     row_ptr->previous()->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
4014                         string fs;
4015                         switch (row_ptr->par()->footnotekind) {
4016                         case LyXParagraph::MARGIN:
4017                                 fs = " margin";
4018                                 break;
4019                         case LyXParagraph::FIG:
4020                                 fs = " fig";
4021                                 break;
4022                         case LyXParagraph::TAB:
4023                                 fs = " tab";
4024                                 break;
4025                         case LyXParagraph::WIDE_FIG:
4026                                 fs = " wide-fig";
4027                                 break;
4028                         case LyXParagraph::WIDE_TAB:
4029                                 fs = " wide-tab";
4030                                 break;
4031                         case LyXParagraph::ALGORITHM:
4032                                 fs = " alg";
4033                                 break;
4034                         case LyXParagraph::FOOTNOTE:
4035                                 fs = " foot";
4036                                 break;
4037                         }
4038                         
4039                         pain.fillRectangle(LYX_PAPER_MARGIN,
4040                                            y_offset + 1,
4041                                            box_x - LYX_PAPER_MARGIN,
4042                                            int(lyxfont::maxAscent(font)
4043                                                + lyxfont::maxDescent(font)),
4044                                            LColor::footnotebg);
4045                         
4046                         pain.line(LYX_PAPER_MARGIN, y_offset,
4047                                   workWidth(bview) - LYX_PAPER_MARGIN, y_offset,
4048                                   LColor::footnoteframe);
4049                         
4050                         pain.text(LYX_PAPER_MARGIN,
4051                                   y_offset + int(lyxfont::maxAscent(font)) + 1,
4052                                   fs, font);
4053                         
4054                         pain.line(LYX_PAPER_MARGIN, y_offset,
4055                                   LYX_PAPER_MARGIN,
4056                                   y_offset + int(lyxfont::maxAscent(font)
4057                                                + lyxfont::maxDescent(font)),
4058                                   LColor::footnoteframe);
4059                         
4060                         pain.line(LYX_PAPER_MARGIN,
4061                                   y_offset + int(lyxfont::maxAscent(font)
4062                                                + lyxfont::maxDescent(font)) + 1,
4063                                   box_x,
4064                                   y_offset + int(lyxfont::maxAscent(font)
4065                                                + lyxfont::maxDescent(font)) + 1,
4066                                   LColor::footnoteframe);
4067                         
4068                 }
4069                 
4070                 /* draw the open floats in a red box */
4071                 pain.line(box_x, y_offset,
4072                           box_x, y_offset + row_ptr->height(),
4073                           LColor::footnoteframe);
4074                 
4075                 pain.line(workWidth(bview) - LYX_PAPER_MARGIN,
4076                           y_offset,
4077                           workWidth(bview) - LYX_PAPER_MARGIN,
4078                           y_offset + row_ptr->height(),
4079                           LColor::footnoteframe);
4080
4081
4082                 // Draw appendix lines
4083                 LyXParagraph * p = row_ptr->par()->PreviousBeforeFootnote()->FirstPhysicalPar();
4084                 if (p->appendix){
4085                         pain.line(1, y_offset,
4086                                   1, y_offset + row_ptr->height(),
4087                                   LColor::appendixline);
4088                         pain.line(workWidth(bview) - 2, y_offset,
4089                                   workWidth(bview) - 2,
4090                                   y_offset + row_ptr->height(),
4091                                   LColor::appendixline);
4092                 }
4093
4094                 // Draw minipage line
4095                 bool minipage = p->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4096                 if (minipage)
4097                         pain.line(LYX_PAPER_MARGIN/5, y_offset,
4098                                   LYX_PAPER_MARGIN/5, 
4099                                   y_offset + row_ptr->height() - 1,
4100                                   LColor::minipageline);
4101
4102                 // Draw depth lines
4103                 int depth = p->GetDepth();
4104                 for (int i = 1; i <= depth; ++i) {
4105                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage);
4106                         pain.line(line_x, y_offset, line_x,
4107                                   y_offset + row_ptr->height() - 1,
4108                                   LColor::depthbar);
4109                 }
4110         } else if (row_ptr->previous() &&
4111                    row_ptr->previous()->par()->footnoteflag
4112                    == LyXParagraph::OPEN_FOOTNOTE) {
4113                 LyXFont font(LyXFont::ALL_SANE);
4114                 font.setSize(LyXFont::SIZE_FOOTNOTE);
4115                 
4116                 int box_x = LYX_PAPER_MARGIN;
4117                 box_x += lyxfont::width(" wide-tab ", font);
4118                 
4119                 pain.line(box_x, y_offset,
4120                           workWidth(bview) - LYX_PAPER_MARGIN,
4121                           y_offset, LColor::footnote);
4122         }
4123 #endif
4124         // Draw appendix lines
4125         LyXParagraph * firstpar = row_ptr->par()->FirstPhysicalPar();
4126         if (firstpar->appendix){
4127                 pain.line(1, y_offset,
4128                           1, y_offset + row_ptr->height(),
4129                           LColor::appendixline);
4130                 pain.line(ww - 2, y_offset,
4131                           ww - 2, y_offset + row_ptr->height(),
4132                           LColor::appendixline);
4133         }
4134
4135         // Draw minipage line
4136         bool minipage = firstpar->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4137         if (minipage)
4138                 pain.line(LYX_PAPER_MARGIN/5 + box_x, y_offset,
4139                           LYX_PAPER_MARGIN/5 + box_x, 
4140                           y_offset + row_ptr->height() - 1,
4141                           LColor::minipageline);
4142
4143         // Draw depth lines
4144         int depth = firstpar->GetDepth();
4145         if (depth > 0) {
4146                 int next_depth = 0;
4147                 int prev_depth = 0;
4148                 if (row_ptr->next())
4149                         if (row_ptr->par()->footnoteflag ==
4150                             row_ptr->next()->par()->footnoteflag)
4151                                 next_depth = row_ptr->next()->par()->GetDepth();
4152                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4153                                 next_depth = depth;
4154
4155                 if (row_ptr->previous())
4156                         if (row_ptr->par()->footnoteflag ==
4157                             row_ptr->previous()->par()->footnoteflag)
4158                                 prev_depth = row_ptr->previous()->par()->GetDepth();
4159                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4160                                 prev_depth = depth;
4161
4162                 for (int i = 1; i <= depth; ++i) {
4163                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage) + box_x;
4164                         pain.line(line_x, y_offset, line_x,
4165                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
4166                                   LColor::depthbar);
4167                 
4168                         if (i > prev_depth)
4169                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
4170                                                    LColor::depthbar);
4171                         if (i > next_depth)
4172                                 pain.fillRectangle(line_x,
4173                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
4174                                                    LYX_PAPER_MARGIN / 5, 2,
4175                                                    LColor::depthbar);
4176                 }
4177         }
4178
4179         
4180         LyXLayout const & layout =
4181                 textclasslist.Style(bview->buffer()->params.textclass,
4182                                     row_ptr->par()->GetLayout());
4183
4184         y_top = 0;
4185         y_bottom = row_ptr->height();
4186         
4187         /* is it a first row? */ 
4188         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
4189                 
4190                 /* start of appendix? */
4191                 if (row_ptr->par()->start_of_appendix){
4192                         pain.line(1, y_offset,
4193                                   ww - 2, y_offset,
4194                                   LColor::appendixline);
4195                 }
4196                 
4197                 /* think about the margins */ 
4198                 if (!row_ptr->previous() && bv_owner)
4199                         y_top += LYX_PAPER_MARGIN;
4200                 
4201                 if (row_ptr->par()->pagebreak_top){ /* draw a top pagebreak  */
4202                         LyXFont pb_font;
4203                         pb_font.setColor(LColor::pagebreak).decSize();
4204                         int w = 0, a = 0, d = 0;
4205                         pain.line(0, y_offset + y_top + 2*DefaultHeight(),
4206                                   ww, 
4207                                   y_offset + y_top + 2 * DefaultHeight(),
4208                                   LColor::pagebreak, 
4209                                   Painter::line_onoffdash)
4210                                 .rectText(0,
4211                                           0,
4212                                           _("Page Break (top)"),
4213                                           pb_font,
4214                                           LColor::background,
4215                                           LColor::background, false, w, a, d);
4216                         pain.rectText((ww - w)/2,
4217                                       y_offset + y_top + 2 * DefaultHeight() + d,
4218                                       _("Page Break (top)"),
4219                                       pb_font,
4220                                       LColor::background,
4221                                       LColor::background);
4222                         y_top += 3 * DefaultHeight();
4223                 }
4224                 
4225                 if (row_ptr->par()->added_space_top.kind() == VSpace::VFILL) {
4226                         /* draw a vfill top  */
4227                         pain.line(0, y_offset + 2 + y_top,
4228                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
4229                                   LColor::vfillline);
4230                         
4231                         pain.line(0, y_offset + y_top + 3 * DefaultHeight(),
4232                                   LYX_PAPER_MARGIN,
4233                                   y_offset + y_top + 3 * DefaultHeight(),
4234                                   LColor::vfillline);
4235                         
4236                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
4237                                   LYX_PAPER_MARGIN / 2,
4238                                   y_offset + y_top + 3 * DefaultHeight(),
4239                                   LColor::vfillline);
4240                         
4241                         y_top += 3 * DefaultHeight();
4242                 }
4243                 
4244                 /* think about user added space */ 
4245                 y_top += int(row_ptr->par()->added_space_top.inPixels(bview));
4246                 
4247                 /* think about the parskip */ 
4248                 /* some parskips VERY EASY IMPLEMENTATION */ 
4249                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
4250                         if (layout.latextype == LATEX_PARAGRAPH
4251                             && firstpar->GetDepth() == 0
4252                             && firstpar->Previous())
4253                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4254                         else if (firstpar->Previous()
4255                                  && textclasslist.Style(bview->buffer()->params.textclass,
4256                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
4257                                  && firstpar->Previous()->GetDepth() == 0)
4258                                 // is it right to use defskip here, too? (AS) 
4259                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4260                 }
4261                 
4262                 if (row_ptr->par()->line_top) {      /* draw a top line  */
4263                         y_top +=  lyxfont::ascent('x',
4264                                                   GetFont(bview->buffer(),
4265                                                           row_ptr->par(), 0));
4266                         
4267                         pain.line(0, y_offset + y_top,
4268                                   ww, y_offset + y_top,
4269                                   LColor::topline,
4270                                   Painter::line_solid,
4271                                   Painter::line_thick);
4272                         
4273                         y_top +=  lyxfont::ascent('x',GetFont(bview->buffer(),
4274                                                               row_ptr->par(), 0));
4275                 }
4276                 
4277                 /* should we print a label? */ 
4278                 if (layout.labeltype >= LABEL_STATIC
4279                     && (layout.labeltype != LABEL_STATIC
4280                         || layout.latextype != LATEX_ENVIRONMENT
4281                         || row_ptr->par()->IsFirstInSequence())) {
4282                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4283                         if (!row_ptr->par()->GetLabelstring().empty()) {
4284                                 tmpx = x;
4285                                 string tmpstring = row_ptr->par()->GetLabelstring();
4286                                 
4287                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
4288                                         if (bview->buffer()->params.secnumdepth >= 0) {
4289                                                 /* this is special code for the chapter layout. This is printed in
4290                                                  * an extra row and has a pagebreak at the top. */
4291                                                 float spacing_val = 1.0;
4292                                                 if (!row_ptr->par()->spacing.isDefault()) {
4293                                                         spacing_val = row_ptr->par()->spacing.getValue();
4294                                                 } else {
4295                                                         spacing_val = bview->buffer()->params.spacing.getValue();
4296                                                 }
4297    
4298                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
4299                                                         + int(layout.parsep) * DefaultHeight();
4300                                                 if (is_rtl)
4301                                                         tmpx = ww - LeftMargin(bview, row_ptr) - 
4302                                                                 lyxfont::width(tmpstring, font);
4303                                                 pain.text(int(tmpx),
4304                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
4305                                                           tmpstring, font);
4306                                         }
4307                                 } else {
4308                                         if (is_rtl) {
4309                                                 tmpx = ww - LeftMargin(bview, row_ptr)
4310                                                         + lyxfont::width(layout.labelsep, font);
4311                                                 if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
4312                                                         LyXFont font(LyXFont::ALL_SANE);
4313                                                         font.setSize(LyXFont::SIZE_SMALL);
4314                                                         tmpx += lyxfont::width("Mwide-fixM", font);
4315                                                 }
4316                                         } else
4317                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4318                                                         - lyxfont::width(tmpstring, font);
4319
4320                                         /* draw it! */
4321                                         pain.text(int(tmpx),
4322                                                   y_offset + row_ptr->baseline(),
4323                                                   tmpstring, font);
4324                                 }
4325                         }
4326                         /* the labels at the top of an environment. More or less for bibliography */ 
4327                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
4328                            layout.labeltype == LABEL_BIBLIO ||
4329                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
4330                         if (row_ptr->par()->IsFirstInSequence()) {
4331                                 font = GetFont(bview->buffer(),
4332                                                row_ptr->par(), -2);
4333                                 if (!row_ptr->par()->GetLabelstring().empty()) {
4334                                         string tmpstring = row_ptr->par()->GetLabelstring();
4335                                         float spacing_val = 1.0;
4336                                         if (!row_ptr->par()->spacing.isDefault()) {
4337                                                 spacing_val = row_ptr->par()->spacing.getValue();
4338                                         } else {
4339                                                 spacing_val = bview->buffer()->params.spacing.getValue();
4340                                         }
4341    
4342                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
4343                                                       + (layout.labelbottomsep * DefaultHeight()));
4344                                         
4345                                         tmpx = x;
4346                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
4347                                                 tmpx = ( (is_rtl ? LeftMargin(bview, row_ptr) : x)
4348                                                          + ww - RightMargin(bview->buffer(), row_ptr) ) / 2; 
4349                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
4350                                         } else if (is_rtl)
4351                                                 tmpx = ww - LeftMargin(bview, row_ptr) - 
4352                                                         lyxfont::width(tmpstring, font);
4353                                         pain.text(int(tmpx),
4354                                                   y_offset + row_ptr->baseline()
4355                                                   - row_ptr->ascent_of_text()
4356                                                   - maxdesc,
4357                                                   tmpstring, font);
4358                                 }
4359                         }
4360                 }
4361                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
4362                         font = GetFont(bview->buffer(), row_ptr->par(), -1);
4363                         if (is_rtl)
4364                                 tmpx = ww - LeftMargin(bview, row_ptr)
4365                                         + lyxfont::width(layout.labelsep, font);
4366                         else
4367                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4368                                         - row_ptr->par()->bibkey->width(bview->painter(), font);
4369                         row_ptr->par()->bibkey->draw(bview, font,
4370                                                    y_offset + row_ptr->baseline(), 
4371                                                    tmpx, clear_area);
4372                 }
4373         }
4374         
4375         /* is it a last row? */
4376         LyXParagraph * par = row_ptr->par()->LastPhysicalPar();
4377         if ((row_ptr->par()->ParFromPos(last + 1) == par) &&
4378             (!row_ptr->next() || (row_ptr->next()->par() != row_ptr->par())))
4379         {
4380                 /* think about the margins */ 
4381                 if (!row_ptr->next() && bv_owner)
4382                         y_bottom -= LYX_PAPER_MARGIN;
4383                 
4384                 /* draw a bottom pagebreak */ 
4385                 if (firstpar->pagebreak_bottom) {
4386                         LyXFont pb_font;
4387                         pb_font.setColor(LColor::pagebreak).decSize();
4388                         int w = 0, a = 0, d = 0;
4389                         pain.line(0,
4390                                   y_offset + y_bottom - 2 * DefaultHeight(), 
4391                                   ww, 
4392                                   y_offset + y_bottom - 2 * DefaultHeight(),
4393                                   LColor::pagebreak,
4394                                   Painter::line_onoffdash)
4395                                 .rectText(0,
4396                                           0,
4397                                           _("Page Break (bottom)"),
4398                                           pb_font,
4399                                           LColor::background,
4400                                           LColor::background, false, w, a, d);
4401                         pain.rectText((ww - w) / 2,
4402                                       y_offset + y_top + 2 * DefaultHeight() + d,
4403                                       _("Page Break (bottom)"),
4404                                       pb_font,
4405                                       LColor::background,
4406                                       LColor::background);
4407                         y_bottom -= 3 * DefaultHeight();
4408                 }
4409                 
4410                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
4411                         /* draw a vfill bottom  */
4412                         pain.line(0, y_offset + y_bottom - 3 * DefaultHeight(),
4413                                   LYX_PAPER_MARGIN,
4414                                   y_offset + y_bottom - 3 * DefaultHeight(),
4415                                   LColor::vfillline);
4416                         pain.line(0, y_offset + y_bottom - 2,
4417                                   LYX_PAPER_MARGIN,
4418                                   y_offset + y_bottom - 2,
4419                                   LColor::vfillline);
4420                         pain.line(LYX_PAPER_MARGIN / 2,
4421                                   y_offset + y_bottom - 3 * DefaultHeight(),
4422                                   LYX_PAPER_MARGIN / 2,
4423                                   y_offset + y_bottom - 2,
4424                                   LColor::vfillline);
4425                         y_bottom -= 3 * DefaultHeight();
4426                 }
4427                 
4428                 /* think about user added space */ 
4429                 y_bottom -= int(firstpar->added_space_bottom.inPixels(bview));
4430                 
4431                 if (firstpar->line_bottom) {
4432                         /* draw a bottom line */
4433                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4434                                                                  par, par->Last() - 1));
4435                         pain.line(0, y_offset + y_bottom,
4436                                   ww, y_offset + y_bottom,
4437                                   LColor::topline, Painter::line_solid,
4438                                   Painter::line_thick);
4439                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4440                                                                  par, par->Last() - 1));
4441                 }
4442
4443                 // draw an endlabel
4444                 int endlabel = row_ptr->par()->GetEndLabel(bview->buffer()->params);
4445                 switch (endlabel) {
4446                 case END_LABEL_BOX:
4447                 case END_LABEL_FILLED_BOX:
4448                 {
4449                         LyXFont font = GetFont(bview->buffer(),
4450                                                row_ptr->par(), last);
4451                         int size = int(0.75 * lyxfont::maxAscent(font));
4452                         int y = (y_offset + row_ptr->baseline()) - size;
4453                         int x = is_rtl ? LYX_PAPER_MARGIN 
4454                                 : ww - LYX_PAPER_MARGIN - size;
4455                         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
4456                                 if (is_rtl) {
4457                                         LyXFont font(LyXFont::ALL_SANE);
4458                                         font.setSize(LyXFont::SIZE_SMALL);
4459                                         x += lyxfont::width("Mwide-figM", font);
4460                                 } else
4461                                         x -= LYX_PAPER_MARGIN/2;
4462                         if (row_ptr->fill() <= size)
4463                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
4464                         if (endlabel == END_LABEL_BOX) {
4465                                 pain.line(x, y, x, y + size,
4466                                           LColor::eolmarker);
4467                                 pain.line(x + size, y, x + size , y + size,
4468                                           LColor::eolmarker);
4469                                 pain.line(x, y, x + size, y,
4470                                           LColor::eolmarker);
4471                                 pain.line(x, y + size, x + size, y + size,
4472                                           LColor::eolmarker);
4473                         } else
4474                                 pain.fillRectangle(x, y, size, size,
4475                                                    LColor::eolmarker);
4476                         break;
4477                 }
4478                 case END_LABEL_STATIC:
4479                 {
4480                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->GetLayout();
4481                         string tmpstring = textclasslist.Style(bview->buffer()->params.textclass,
4482                                                          layout).endlabelstring();
4483                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4484                         int tmpx = is_rtl ? int(x) - lyxfont::width(tmpstring, font)
4485                                 : ww - RightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
4486                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
4487                         break;
4488                 }
4489                 case END_LABEL_NO_LABEL:
4490                         break;
4491                 }
4492         }
4493         
4494         /* draw the text in the pixmap */  
4495         
4496         vpos = row_ptr->pos();
4497 #ifndef NEW_TABULAR
4498         /* table stuff -- begin*/
4499         if (row_ptr->par()->table) {
4500                 bool on_off;
4501                 int cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
4502                 float x_old = x;
4503                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4504                 
4505                 while (vpos <= last)  {
4506                         pos = vis2log(vpos);
4507                         if (row_ptr->par()->IsNewline(pos)) {
4508                                 
4509                                 x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4510                                 /* draw the table lines, still very simple */
4511                                 on_off = !row_ptr->par()->table->TopLine(cell);
4512                                 if ((!on_off ||
4513                                      !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4514                                     !row_ptr->par()->table->IsContRow(cell))
4515                                         pain.line(int(x_old),
4516                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4517                                                   int(x),
4518                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4519                                                   LColor::tableline,
4520                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4521                                 
4522                                 on_off = !row_ptr->par()->table->BottomLine(cell);
4523                                 if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4524                                     row_ptr->par()->table->VeryLastRow(cell))
4525                                         
4526                                         pain.line(int(x_old),
4527                                                   y_offset + y_bottom - 1,
4528                                                   int(x),
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->LeftLine(cell);
4534                                 
4535                                 pain.line(int(x_old),
4536                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4537                                           int(x_old),
4538                                           y_offset + y_bottom - 1,
4539                                           LColor::tableline,
4540                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4541                                 
4542                                 on_off = !row_ptr->par()->table->RightLine(cell);
4543                                 
4544                                 pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4545                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4546                                           int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4547                                           y_offset + y_bottom - 1,
4548                                           LColor::tableline,
4549                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4550                                 
4551                                 x_old = x;
4552                                 /* take care about the alignment and other spaces */
4553                                 ++cell;
4554                                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4555                                 if (row_ptr->par()->table->IsFirstCell(cell))
4556                                         --cell; // little hack, sorry
4557                                 ++vpos;
4558                         } else if (row_ptr->par()->IsHfill(pos)) {
4559                                 x += 1;
4560                                 
4561                                 pain.line(int(x),
4562                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4563                                           int(x),
4564                                           y_offset + row_ptr->baseline(),
4565                                           LColor::vfillline);
4566                                 
4567                                 x += 2;
4568                                 ++vpos;
4569                         } else if (row_ptr->par()->IsSeparator(pos)) {
4570                                 tmpx = x;
4571                                 x+= SingleWidth(bview, 
4572                                                 row_ptr->par(), pos);
4573                                 ++vpos;
4574                         } else
4575                                 draw(bview, row_ptr, vpos, y_offset, x, clear_area);
4576                 }
4577                 
4578                 /* do not forget the very last cell. This has no NEWLINE so 
4579                  * ignored by the code above*/ 
4580                 if (cell == row_ptr->par()->table->GetNumberOfCells() - 1) {
4581                         x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4582                         on_off = !row_ptr->par()->table->TopLine(cell);
4583                         if ((!on_off ||
4584                              !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4585                             !row_ptr->par()->table->IsContRow(cell))
4586                                 
4587                                 pain.line(int(x_old),
4588                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4589                                           int(x),
4590                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4591                                           LColor::tableline,
4592                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4593                         on_off = !row_ptr->par()->table->BottomLine(cell);
4594                         if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4595                             row_ptr->par()->table->VeryLastRow(cell))
4596                                 
4597                                 pain.line(int(x_old),
4598                                           y_offset + y_bottom - 1,
4599                                           int(x),
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->LeftLine(cell);
4605                         
4606                         pain.line(int(x_old),
4607                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4608                                   int(x_old),
4609                                   y_offset + y_bottom - 1,
4610                                   LColor::tableline,
4611                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4612                         
4613                         on_off = !row_ptr->par()->table->RightLine(cell);
4614                         
4615                         pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4616                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4617                                   int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4618                                   y_offset + y_bottom - 1,
4619                                   LColor::tableline,
4620                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4621                 }
4622         } else {
4623                 /* table stuff -- end*/
4624 #endif
4625                 LyXParagraph::size_type main_body = 
4626                         BeginningOfMainBody(bview->buffer(), row_ptr->par());
4627                 if (main_body > 0 &&
4628                     (main_body-1 > last || 
4629                      !row_ptr->par()->IsLineSeparator(main_body - 1)))
4630                         main_body = 0;
4631                 
4632                 while (vpos <= last)  {
4633                         pos = vis2log(vpos);
4634                         if (main_body > 0 && pos == main_body - 1) {
4635                                 x += fill_label_hfill
4636                                         + lyxfont::width(layout.labelsep,
4637                                                          GetFont(bview->buffer(),
4638                                                                  row_ptr->par(), -2))
4639                                         - SingleWidth(bview,
4640                                                       row_ptr->par(),
4641                                                       main_body - 1);
4642                         }
4643                         
4644                         if (row_ptr->par() ->IsHfill(pos)) {
4645                                 x += 1;
4646                                 pain.line(int(x),
4647                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4648                                           int(x),
4649                                           y_offset + row_ptr->baseline(),
4650                                           LColor::vfillline);
4651                                 
4652                                 if (HfillExpansion(bview->buffer(),
4653                                                    row_ptr, pos)) {
4654                                         if (pos >= main_body) {
4655                                                 pain.line(int(x),
4656                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4657                                                           int(x + fill_hfill),
4658                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4659                                                           LColor::vfillline,
4660                                                           Painter::line_onoffdash);
4661                                                 x += fill_hfill;
4662                                         } else {
4663                                                 pain.line(int(x),
4664                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4665                                                           int(x + fill_label_hfill),
4666                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4667                                                           LColor::vfillline,
4668                                                           Painter::line_onoffdash);
4669                                                 
4670                                                 x += fill_label_hfill;
4671                                         }
4672                                         pain.line(int(x),
4673                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4674                                                   int(x),
4675                                                   y_offset + row_ptr->baseline(),
4676                                                   LColor::vfillline);
4677                                 }
4678                                 x += 2;
4679                                 ++vpos;
4680                         } else if (row_ptr->par()->IsSeparator(pos)) {
4681                                 x += SingleWidth(bview,
4682                                                  row_ptr->par(), pos);
4683                                 if (pos >= main_body)
4684                                         x += fill_separator;
4685                                 ++vpos;
4686                         } else
4687                                 draw(bview, row_ptr, vpos, y_offset, x, clear_area);
4688                 }
4689 #ifndef NEW_TABULAR
4690         }
4691 #endif
4692 }
4693
4694
4695 int LyXText::DefaultHeight() const
4696 {
4697         LyXFont font(LyXFont::ALL_SANE);
4698         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
4699 }
4700
4701    
4702 /* returns the column near the specified x-coordinate of the row 
4703 * x is set to the real beginning of this column  */ 
4704 int LyXText::GetColumnNearX(BufferView * bview, Row * row, int & x,
4705                             bool & boundary) const
4706 {
4707         float tmpx = 0.0;
4708         float fill_separator, fill_hfill, fill_label_hfill;
4709    
4710         PrepareToPrint(bview, row, tmpx, fill_separator,
4711                        fill_hfill, fill_label_hfill);
4712
4713         LyXParagraph::size_type vc = row->pos();
4714         LyXParagraph::size_type last = RowLastPrintable(row);
4715         LyXParagraph::size_type c = 0;
4716         LyXLayout const & layout =
4717                 textclasslist.Style(bview->buffer()->params.textclass,
4718                                     row->par()->GetLayout());
4719         bool left_side = false;
4720
4721 #ifndef NEW_TABULAR
4722         /* table stuff -- begin */
4723         if (row->par()->table) {
4724                 //the last row doesn't need a newline at the end
4725                 if (row->next() && row->next()->par() == row->par()
4726                     && row->par()->IsNewline(last))
4727                         --last;
4728                 int cell = NumberOfCell(row->par(), row->pos());
4729                 float cell_x = tmpx + row->par()->table->WidthOfColumn(cell);
4730                 tmpx += row->par()->table->GetBeginningOfTextInCell(cell);
4731                 float last_tmpx = tmpx;
4732                 while (vc <= last && tmpx <= x) {
4733                        c = vis2log(vc);
4734                        last_tmpx = tmpx;
4735                        if (row->par()->IsNewline(c)) {
4736                                if (cell_x <= x){
4737                                        ++cell;
4738                                        tmpx = cell_x + row->par()->table->GetBeginningOfTextInCell(cell);
4739                                        cell_x += row->par()->table->WidthOfColumn(cell);
4740                                        ++vc;
4741                                } else
4742                                        break;
4743                        } else {
4744                                tmpx += SingleWidth(bview, row->par(), c);
4745                                ++vc;
4746                        }
4747                 }
4748                 if (vc > row->pos() && !row->par()->IsNewline(c) &&
4749                     (tmpx + last_tmpx) / 2 > x) {
4750                         tmpx = last_tmpx;
4751                         left_side = true;
4752                 }
4753         } else {
4754                 /* table stuff -- end*/
4755 #endif
4756                 LyXParagraph::size_type
4757                         main_body = BeginningOfMainBody(bview->buffer(), row->par());
4758                 float last_tmpx = tmpx;
4759
4760                 if (main_body > 0 &&
4761                     (main_body-1 > last || 
4762                      !row->par()->IsLineSeparator(main_body - 1)))
4763                         main_body = 0;
4764
4765                 while (vc <= last && tmpx <= x) {
4766                         c = vis2log(vc);
4767                         last_tmpx = tmpx;
4768                         if (main_body > 0 && c == main_body-1) {
4769                                 tmpx += fill_label_hfill +
4770                                         lyxfont::width(layout.labelsep,
4771                                                GetFont(bview->buffer(), row->par(), -2));
4772                                 if (row->par()->IsLineSeparator(main_body - 1))
4773                                         tmpx -= SingleWidth(bview, row->par(), main_body-1);
4774                         }
4775              
4776                         if (HfillExpansion(bview->buffer(), row, c)) {
4777                                 x += SingleWidth(bview, row->par(), c);
4778                                 if (c >= main_body)
4779                                         tmpx += fill_hfill;
4780                                 else
4781                                         tmpx += fill_label_hfill;
4782                         }
4783                         else if (row->par()->IsSeparator(c)) {
4784                                 tmpx += SingleWidth(bview, row->par(), c);
4785                                 if (c >= main_body)
4786                                         tmpx+= fill_separator;
4787                         } else
4788                                 tmpx += SingleWidth(bview, row->par(), c);
4789                         ++vc;
4790                 }
4791
4792                 if (vc > row->pos() && (tmpx + last_tmpx) / 2 > x) {
4793                         tmpx = last_tmpx;
4794                         left_side = true;
4795                 }
4796 #ifndef NEW_TABULAR
4797         }
4798 #endif
4799
4800
4801         if (vc > last + 1)  // This shouldn't happen.
4802                 vc = last + 1;
4803
4804         boundary = false;
4805
4806         if (row->pos() > last)  // Row is empty?
4807                 c = row->pos();
4808         else if (vc == row->pos() ||
4809                  (row->par()->table
4810                   && vc <= last && row->par()->IsNewline(vc-1)) ) {
4811                 c = vis2log(vc);
4812                 if (bidi_level(c) % 2 == 1)
4813                         ++c;
4814         } else {
4815                 c = vis2log(vc - 1);
4816                 bool rtl = (bidi_level(c) % 2 == 1);
4817                 if (left_side == rtl) {
4818                         ++c;
4819                         boundary = IsBoundary(bview->buffer(), row->par(), c);
4820                 }
4821         }
4822
4823         if (!row->par()->table && row->pos() <= last && c > last
4824             && row->par()->IsNewline(last)) {
4825                 if (bidi_level(last) % 2 == 0)
4826                         tmpx -= SingleWidth(bview, row->par(), last);
4827                 else
4828                         tmpx += SingleWidth(bview, row->par(), last);
4829                 c = last;
4830         }
4831
4832         c -= row->pos();
4833         x = int(tmpx);
4834         return c;
4835 }
4836
4837
4838 #ifndef NEW_INSETS
4839 /* turn the selection into a new environment. If there is no selection,
4840 * create an empty environment */ 
4841 void LyXText::InsertFootnoteEnvironment(BufferView * bview, 
4842                                         LyXParagraph::footnote_kind kind)
4843 {
4844    /* no footnoteenvironment in a footnoteenvironment */ 
4845    if (cursor.par()->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4846       WriteAlert(_("Impossible operation"), 
4847                  _("You can't insert a float in a float!"), 
4848                  _("Sorry."));
4849      return;
4850    }
4851    /* no marginpars in minipages */
4852    if (kind == LyXParagraph::MARGIN 
4853       && cursor.par()->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
4854       WriteAlert(_("Impossible operation"), 
4855                  _("You can't insert a marginpar in a minipage!"), 
4856                  _("Sorry."));
4857       return;
4858    }
4859    
4860    /* this doesnt make sense, if there is no selection */ 
4861    bool dummy_selection = false;
4862    if (!selection) {
4863       sel_start_cursor = cursor;       /* dummy selection  */
4864       sel_end_cursor = cursor;
4865       dummy_selection = true;
4866    }
4867    
4868    LyXParagraph * tmppar;
4869
4870 #ifndef NEW_TABULAR
4871    if (sel_start_cursor.par()->table || sel_end_cursor.par()->table){
4872       WriteAlert(_("Impossible operation"), _("Cannot cut table."), _("Sorry."));
4873       return;
4874    }
4875 #endif
4876    /* a test to make sure there is not already a footnote
4877     * in the selection. */
4878    
4879    tmppar = sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos());
4880    
4881    while (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos()) && 
4882           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
4883      tmppar = tmppar->next;
4884    
4885    if (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())
4886        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4887       WriteAlert(_("Impossible operation"), 
4888                  _("Float would include float!"), 
4889                  _("Sorry."));
4890       return;
4891    }
4892    
4893    /* ok we have a selection. This is always between sel_start_cursor
4894     * and sel_end cursor */
4895
4896    SetUndo(bview->buffer(), Undo::FINISH, 
4897            sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos())->previous, 
4898            sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())->next); 
4899    
4900    if (sel_end_cursor.pos() > 0 
4901        && sel_end_cursor.par()->IsLineSeparator(sel_end_cursor.pos() - 1))
4902            sel_end_cursor.pos(sel_end_cursor.pos() - 1);
4903    /* please break before a space at the end */
4904    if (sel_start_cursor.par() == sel_end_cursor.par()
4905        && sel_start_cursor.pos() > sel_end_cursor.pos())
4906            sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4907
4908    sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, sel_end_cursor.pos());
4909    
4910    sel_end_cursor.par(sel_end_cursor.par()->Next());
4911    sel_end_cursor.pos(0);
4912    
4913    // don't forget to insert a dummy layout paragraph if necessary
4914    if (sel_start_cursor.par()->GetLayout() != sel_end_cursor.par()->layout){
4915      sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, 0);
4916      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4917      sel_end_cursor.par(sel_end_cursor.par()->next);
4918    }
4919    else
4920      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4921
4922    cursor = sel_end_cursor;
4923
4924    /* please break behind a space, if there is one. The space should
4925     * be erased too */ 
4926    if (sel_start_cursor.pos() > 0 
4927        && sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos() - 1))
4928      sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4929    if (sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos())) {
4930       sel_start_cursor.par()->Erase(sel_start_cursor.pos());
4931    }
4932    
4933    sel_start_cursor.par()->BreakParagraphConservative(bview->buffer()->params,
4934                                                     sel_start_cursor.pos());
4935    tmppar = sel_start_cursor.par()->Next();
4936    
4937    if (dummy_selection) {
4938            tmppar->Clear();
4939            if (kind == LyXParagraph::TAB
4940                || kind == LyXParagraph::FIG 
4941                || kind == LyXParagraph::WIDE_TAB
4942                || kind == LyXParagraph::WIDE_FIG 
4943                || kind == LyXParagraph::ALGORITHM) {
4944                    pair<bool, LyXTextClass::size_type> lres =
4945                            textclasslist.NumberOfLayout(bview->buffer()->params.textclass,
4946                                                         "Caption");
4947                    LyXTextClass::size_type lay;
4948                    if (lres.first) {
4949                            // layout fount
4950                            lay = lres.second;
4951                    } else {
4952                            // layout not found
4953                            lay = 0; // use default layout "Standard" (0)
4954                    }
4955                    tmppar->SetLayout(bview->buffer()->params, lay);
4956            }
4957    } else {
4958      if (sel_start_cursor.pos() > 0) {
4959        /* the footnote-environment should begin with a standard layout.
4960         * Imagine you insert a footnote within an enumeration, you 
4961         * certainly do not want an enumerated footnote! */ 
4962        tmppar->Clear();
4963      } else {
4964        /* this is a exception the user would sometimes expect, I hope */
4965        sel_start_cursor.par()->Clear();
4966      }
4967    }
4968    
4969    while (tmppar != sel_end_cursor.par()) {
4970       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
4971       tmppar->footnotekind = kind;
4972       tmppar = tmppar->Next();
4973    }
4974
4975    RedoParagraphs(bview, sel_start_cursor, sel_end_cursor.par()->Next());
4976    
4977    SetCursor(bview, sel_start_cursor.par()->Next(), 0);
4978
4979    ClearSelection();
4980 }
4981 #endif
4982
4983
4984 // returns pointer to a specified row
4985 Row * LyXText::GetRow(LyXParagraph * par,
4986                       LyXParagraph::size_type pos, long & y) const
4987 {
4988         Row * tmprow = firstrow;
4989         y = 0;
4990         
4991         // find the first row of the specified paragraph
4992         while (tmprow->next() && tmprow->par() != par) {
4993                 y += tmprow->height();
4994                 tmprow = tmprow->next();
4995         }
4996         
4997         // now find the wanted row
4998         while (tmprow->pos() < pos
4999                && tmprow->next()
5000                && tmprow->next()->par() == par
5001                && tmprow->next()->pos() <= pos) {
5002                 y += tmprow->height();
5003                 tmprow = tmprow->next();
5004         }
5005         
5006         return tmprow;
5007 }