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