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