]> git.lyx.org Git - lyx.git/blob - src/text.C
fix break before minipages too
[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-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "paragraph.h"
16 #include "gettext.h"
17 #include "bufferparams.h"
18 #include "buffer.h"
19 #include "debug.h"
20 #include "intl.h"
21 #include "lyxrc.h"
22 #include "encoding.h"
23 #include "frontends/LyXView.h"
24 #include "frontends/Painter.h"
25 #include "frontends/font_metrics.h"
26 #include "frontends/screen.h"
27 #include "frontends/WorkArea.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "WordLangTuple.h"
34 #include "paragraph_funcs.h"
35 #include "rowpainter.h"
36
37 #include "insets/insettext.h"
38
39 #include "support/textutils.h"
40 #include "support/LAssert.h"
41 #include "support/lstrings.h"
42
43 #include <algorithm>
44
45 using std::max;
46 using std::min;
47 using std::endl;
48 using std::pair;
49 using lyx::pos_type;
50
51 /// top, right, bottom pixel margin
52 extern int const PAPER_MARGIN = 20;
53 /// margin for changebar
54 extern int const CHANGEBAR_MARGIN = 10;
55 /// left margin
56 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
57
58 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
59
60
61 int LyXText::top_y() const
62 {
63         if (!top_row_)
64                 return 0;
65         
66         int y = 0;
67         for (Row * row = firstrow; row && row != top_row_; row = row->next()) {
68                 y += row->height();
69         }
70         return y + top_row_offset_;
71 }
72
73
74 void LyXText::top_y(int newy)
75 {
76         if (!firstrow)
77                 return;
78         lyxerr[Debug::GUI] << "setting top y = " << newy << endl;
79         
80         int y = newy;
81         top_row_ = getRowNearY(y);
82         top_row_offset_ = newy - y;
83         lyxerr[Debug::GUI] << "changing reference to row: " << top_row_
84                << " offset: " << top_row_offset_ << endl;
85 }
86
87
88 int LyXText::workWidth(BufferView & bview) const
89 {
90         if (inset_owner) {
91                 // FIXME: pass (const ?) ref
92                 return inset_owner->textWidth(&bview);
93         }
94         return bview.workWidth();
95 }
96
97
98 int LyXText::workWidth(BufferView & bview, Inset * inset) const
99 {
100         Paragraph * par = inset->parOwner();
101         lyx::Assert(par);
102
103         pos_type pos = par->getPositionOfInset(inset);
104         lyx::Assert(pos != -1);
105
106         LyXLayout_ptr const & layout = par->layout();
107
108         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
109                 // Optimization here: in most cases, the real row is
110                 // not needed, but only the par/pos values. So we just
111                 // construct a dummy row for leftMargin. (JMarc)
112                 Row dummyrow;
113                 dummyrow.par(par);
114                 dummyrow.pos(pos);
115                 return workWidth(bview) - leftMargin(&bview, &dummyrow);
116         } else {
117                 int dummy_y;
118                 Row * row = getRow(par, pos, dummy_y);
119                 Row * frow = row;
120                 while (frow->previous() && frow->par() == frow->previous()->par())
121                         frow = frow->previous();
122
123                 // FIXME: I don't understand this code - jbl
124
125                 unsigned int maxw = 0;
126                 while (!frow->isParEnd()) {
127                         if ((frow != row) && (maxw < frow->width()))
128                                 maxw = frow->width();
129                         frow = frow->next();
130                 }
131                 if (maxw)
132                         return maxw;
133
134         }
135         return workWidth(bview);
136 }
137
138
139 int LyXText::getRealCursorX(BufferView * bview) const
140 {
141         int x = cursor.x();
142         if (the_locking_inset && (the_locking_inset->getLyXText(bview)!=this))
143                 x = the_locking_inset->getLyXText(bview)->getRealCursorX(bview);
144         return x;
145 }
146
147
148 unsigned char LyXText::transformChar(unsigned char c, Paragraph * par,
149                         pos_type pos) const
150 {
151         if (!Encodings::is_arabic(c))
152                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
153                         return c + (0xb0 - '0');
154                 else
155                         return c;
156
157         unsigned char const prev_char = pos > 0 ? par->getChar(pos-1) : ' ';
158         unsigned char next_char = ' ';
159
160         for (pos_type i = pos+1; i < par->size(); ++i)
161                 if (!Encodings::IsComposeChar_arabic(par->getChar(i))) {
162                         next_char = par->getChar(i);
163                         break;
164                 }
165
166         if (Encodings::is_arabic(next_char)) {
167                 if (Encodings::is_arabic(prev_char) &&
168                         !Encodings::is_arabic_special(prev_char))
169                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
170                 else
171                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
172         } else {
173                 if (Encodings::is_arabic(prev_char) &&
174                         !Encodings::is_arabic_special(prev_char))
175                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
176                 else
177                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
178         }
179 }
180
181 // This is the comments that some of the warnings below refers to.
182 // There are some issues in this file and I don't think they are
183 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
184 // this is a problem that has been here almost from day one and that a
185 // larger userbase with differenct access patters triggers the bad
186 // behaviour. (segfaults.) What I think happen is: In several places
187 // we store the paragraph in the current cursor and then moves the
188 // cursor. This movement of the cursor will delete paragraph at the
189 // old position if it is now empty. This will make the temporary
190 // pointer to the old cursor paragraph invalid and dangerous to use.
191 // And is some cases this will trigger a segfault. I have marked some
192 // of the cases where this happens with a warning, but I am sure there
193 // are others in this file and in text2.C. There is also a note in
194 // Delete() that you should read. In Delete I store the paragraph->id
195 // instead of a pointer to the paragraph. I am pretty sure this faulty
196 // use of temporary pointers to paragraphs that might have gotten
197 // invalidated (through a cursor movement) before they are used, are
198 // the cause of the strange crashes we get reported often.
199 //
200 // It is very tiresom to change this code, especially when it is as
201 // hard to read as it is. Help to fix all the cases where this is done
202 // would be greately appreciated.
203 //
204 // Lgb
205
206 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
207                          pos_type pos) const
208 {
209         char const c = par->getChar(pos);
210         return singleWidth(bview, par, pos, c);
211 }
212
213
214 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
215                          pos_type pos, char c) const
216 {
217         LyXFont const font = getFont(bview->buffer(), par, pos);
218
219         // The most common case is handled first (Asger)
220         if (IsPrintable(c)) {
221                 if (font.language()->RightToLeft()) {
222                         if (font.language()->lang() == "arabic" &&
223                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
224                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
225                                 if (Encodings::IsComposeChar_arabic(c))
226                                         return 0;
227                                 else
228                                         c = transformChar(c, par, pos);
229                         else if (font.language()->lang() == "hebrew" &&
230                                  Encodings::IsComposeChar_hebrew(c))
231                                 return 0;
232                 }
233                 return font_metrics::width(c, font);
234
235         } else if (IsHfillChar(c)) {
236                 // Because of the representation as vertical lines
237                 return 3;
238         } else if (c == Paragraph::META_INSET) {
239                 Inset * tmpinset = par->getInset(pos);
240                 if (tmpinset) {
241 #if 1
242                         // this IS needed otherwise on initialitation we don't get the fill
243                         // of the row right (ONLY on initialization if we read a file!)
244                         // should be changed! (Jug 20011204)
245                         tmpinset->update(bview, font);
246 #endif
247                         return tmpinset->width(bview, font);
248                 } else
249                         return 0;
250
251         } else if (IsSeparatorChar(c))
252                 c = ' ';
253         else if (IsNewlineChar(c))
254                 c = 'n';
255         return font_metrics::width(c, font);
256 }
257
258
259 void LyXText::computeBidiTables(Buffer const * buf, Row * row) const
260 {
261         bidi_same_direction = true;
262         if (!lyxrc.rtl_support) {
263                 bidi_start = -1;
264                 return;
265         }
266
267         Inset * inset = row->par()->inInset();
268         if (inset && inset->owner() &&
269             inset->owner()->lyxCode() == Inset::ERT_CODE) {
270                 bidi_start = -1;
271                 return;
272         }
273
274         bidi_start = row->pos();
275         bidi_end = row->lastPrintablePos();
276
277         if (bidi_start > bidi_end) {
278                 bidi_start = -1;
279                 return;
280         }
281
282         if (bidi_end + 2 - bidi_start >
283             static_cast<pos_type>(log2vis_list.size())) {
284                 pos_type new_size =
285                         (bidi_end + 2 - bidi_start < 500) ?
286                         500 : 2 * (bidi_end + 2 - bidi_start);
287                 log2vis_list.resize(new_size);
288                 vis2log_list.resize(new_size);
289                 bidi_levels.resize(new_size);
290         }
291
292         vis2log_list[bidi_end + 1 - bidi_start] = -1;
293         log2vis_list[bidi_end + 1 - bidi_start] = -1;
294
295         pos_type stack[2];
296         bool const rtl_par =
297                 row->par()->isRightToLeftPar(buf->params);
298         int level = 0;
299         bool rtl = false;
300         bool rtl0 = false;
301         pos_type const body_pos = row->par()->beginningOfBody();
302
303         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
304                 bool is_space = row->par()->isLineSeparator(lpos);
305                 pos_type const pos =
306                         (is_space && lpos + 1 <= bidi_end &&
307                          !row->par()->isLineSeparator(lpos + 1) &&
308                          !row->par()->isNewline(lpos + 1))
309                         ? lpos + 1 : lpos;
310                 LyXFont font = row->par()->getFontSettings(buf->params, pos);
311                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
312                     font.number() == LyXFont::ON &&
313                     row->par()->getFontSettings(buf->params, lpos - 1).number()
314                     == LyXFont::ON) {
315                         font = row->par()->getFontSettings(buf->params, lpos);
316                         is_space = false;
317                 }
318
319
320                 bool new_rtl = font.isVisibleRightToLeft();
321                 bool new_rtl0 = font.isRightToLeft();
322                 int new_level;
323
324                 if (lpos == body_pos - 1
325                     && row->pos() < body_pos - 1
326                     && is_space) {
327                         new_level = (rtl_par) ? 1 : 0;
328                         new_rtl = new_rtl0 = rtl_par;
329                 } else if (new_rtl0)
330                         new_level = (new_rtl) ? 1 : 2;
331                 else
332                         new_level = (rtl_par) ? 2 : 0;
333
334                 if (is_space && new_level >= level) {
335                         new_level = level;
336                         new_rtl = rtl;
337                         new_rtl0 = rtl0;
338                 }
339
340                 int new_level2 = new_level;
341
342                 if (level == new_level && rtl0 != new_rtl0) {
343                         --new_level2;
344                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
345                 } else if (level < new_level) {
346                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
347                         if (new_level > rtl_par)
348                                 bidi_same_direction = false;
349                 } else
350                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
351                 rtl = new_rtl;
352                 rtl0 = new_rtl0;
353                 bidi_levels[lpos - bidi_start] = new_level;
354
355                 while (level > new_level2) {
356                         pos_type old_lpos = stack[--level];
357                         int delta = lpos - old_lpos - 1;
358                         if (level % 2)
359                                 delta = -delta;
360                         log2vis_list[lpos - bidi_start] += delta;
361                         log2vis_list[old_lpos - bidi_start] += delta;
362                 }
363                 while (level < new_level)
364                         stack[level++] = lpos;
365         }
366
367         while (level > 0) {
368                 pos_type const old_lpos = stack[--level];
369                 int delta = bidi_end - old_lpos;
370                 if (level % 2)
371                         delta = -delta;
372                 log2vis_list[old_lpos - bidi_start] += delta;
373         }
374
375         pos_type vpos = bidi_start - 1;
376         for (pos_type lpos = bidi_start;
377              lpos <= bidi_end; ++lpos) {
378                 vpos += log2vis_list[lpos - bidi_start];
379                 vis2log_list[vpos - bidi_start] = lpos;
380                 log2vis_list[lpos - bidi_start] = vpos;
381         }
382 }
383
384
385 // This method requires a previous call to ComputeBidiTables()
386 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
387                          pos_type pos) const
388 {
389         if (!lyxrc.rtl_support || pos == 0)
390                 return false;
391
392         if (!bidi_InRange(pos - 1)) {
393                 /// This can happen if pos is the first char of a row.
394                 /// Returning false in this case is incorrect!
395                 return false;
396         }
397
398         bool const rtl = bidi_level(pos - 1) % 2;
399         bool const rtl2 = bidi_InRange(pos)
400                 ? bidi_level(pos) % 2
401                 : par->isRightToLeftPar(buf->params);
402         return rtl != rtl2;
403 }
404
405
406 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
407                          pos_type pos, LyXFont const & font) const
408 {
409         if (!lyxrc.rtl_support)
410                 return false;    // This is just for speedup
411
412         bool const rtl = font.isVisibleRightToLeft();
413         bool const rtl2 = bidi_InRange(pos)
414                 ? bidi_level(pos) % 2
415                 : par->isRightToLeftPar(buf->params);
416         return rtl != rtl2;
417 }
418
419
420 int LyXText::leftMargin(BufferView * bview, Row const * row) const
421 {
422         Inset * ins;
423         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
424                 (ins=row->par()->getInset(row->pos())) &&
425                 (ins->needFullRow() || ins->display()))
426                 return LEFT_MARGIN;
427
428         LyXTextClass const & tclass =
429                 bview->buffer()->params.getLyXTextClass();
430         LyXLayout_ptr const & layout = row->par()->layout();
431
432         string parindent = layout->parindent;
433
434         int x = LEFT_MARGIN;
435
436         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
437
438         // this is the way, LyX handles the LaTeX-Environments.
439         // I have had this idea very late, so it seems to be a
440         // later added hack and this is true
441         if (!row->par()->getDepth()) {
442                 if (row->par()->layout() == tclass.defaultLayout()) {
443                         // find the previous same level paragraph
444                         if (row->par()->previous()) {
445                                 Paragraph * newpar = row->par()
446                                         ->depthHook(row->par()->getDepth());
447                                 if (newpar &&
448                                     newpar->layout()->nextnoindent)
449                                         parindent.erase();
450                         }
451                 }
452         } else {
453                 // find the next level paragraph
454
455                 Paragraph * newpar = row->par()->outerHook();
456
457                 // make a corresponding row. Needed to call LeftMargin()
458
459                 // check wether it is a sufficent paragraph
460                 if (newpar && newpar->layout()->isEnvironment()) {
461                         Row dummyrow;
462                         dummyrow.par(newpar);
463                         dummyrow.pos(newpar->size());
464                         x = leftMargin(bview, &dummyrow);
465                 } else {
466                         // this is no longer an error, because this function
467                         // is used to clear impossible depths after changing
468                         // a layout. Since there is always a redo,
469                         // LeftMargin() is always called
470                         row->par()->params().depth(0);
471                 }
472
473                 if (newpar && row->par()->layout() == tclass.defaultLayout()) {
474                         if (newpar->params().noindent())
475                                 parindent.erase();
476                         else {
477                                 parindent = newpar->layout()->parindent;
478                         }
479
480                 }
481         }
482
483         LyXFont const labelfont = getLabelFont(bview->buffer(), row->par());
484         switch (layout->margintype) {
485         case MARGIN_DYNAMIC:
486                 if (!layout->leftmargin.empty()) {
487                         x += font_metrics::signedWidth(layout->leftmargin,
488                                                   tclass.defaultfont());
489                 }
490                 if (!row->par()->getLabelstring().empty()) {
491                         x += font_metrics::signedWidth(layout->labelindent,
492                                                   labelfont);
493                         x += font_metrics::width(row->par()->getLabelstring(),
494                                             labelfont);
495                         x += font_metrics::width(layout->labelsep, labelfont);
496                 }
497                 break;
498         case MARGIN_MANUAL:
499                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
500                 // The width of an empty par, even with manual label, should be 0
501                 if (!row->par()->empty() && row->pos() >= row->par()->beginningOfBody()) {
502                         if (!row->par()->getLabelWidthString().empty()) {
503                                 x += font_metrics::width(row->par()->getLabelWidthString(),
504                                                labelfont);
505                                 x += font_metrics::width(layout->labelsep, labelfont);
506                         }
507                 }
508                 break;
509         case MARGIN_STATIC:
510                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
511                         / (row->par()->getDepth() + 4);
512                 break;
513         case MARGIN_FIRST_DYNAMIC:
514                 if (layout->labeltype == LABEL_MANUAL) {
515                         if (row->pos() >= row->par()->beginningOfBody()) {
516                                 x += font_metrics::signedWidth(layout->leftmargin,
517                                                           labelfont);
518                         } else {
519                                 x += font_metrics::signedWidth(layout->labelindent,
520                                                           labelfont);
521                         }
522                 } else if (row->pos()
523                            // Special case to fix problems with
524                            // theorems (JMarc)
525                            || (layout->labeltype == LABEL_STATIC
526                                && layout->latextype == LATEX_ENVIRONMENT
527                                && ! row->par()->isFirstInSequence())) {
528                         x += font_metrics::signedWidth(layout->leftmargin,
529                                                   labelfont);
530                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
531                            && layout->labeltype != LABEL_BIBLIO
532                            && layout->labeltype !=
533                            LABEL_CENTERED_TOP_ENVIRONMENT) {
534                         x += font_metrics::signedWidth(layout->labelindent,
535                                                   labelfont);
536                         x += font_metrics::width(layout->labelsep, labelfont);
537                         x += font_metrics::width(row->par()->getLabelstring(),
538                                             labelfont);
539                 }
540                 break;
541
542         case MARGIN_RIGHT_ADDRESS_BOX:
543         {
544                 // ok, a terrible hack. The left margin depends on the widest
545                 // row in this paragraph. Do not care about footnotes, they
546                 // are *NOT* allowed in the LaTeX realisation of this layout.
547
548                 // find the first row of this paragraph
549                 Row const * tmprow = row;
550                 while (tmprow->previous()
551                        && tmprow->previous()->par() == row->par())
552                         tmprow = tmprow->previous();
553
554                 int minfill = tmprow->fill();
555                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
556                         tmprow = tmprow->next();
557                         if (tmprow->fill() < minfill)
558                                 minfill = tmprow->fill();
559                 }
560
561                 x += font_metrics::signedWidth(layout->leftmargin,
562                         tclass.defaultfont());
563                 x += minfill;
564         }
565         break;
566         }
567
568         if ((workWidth(*bview) > 0) &&
569                 !row->par()->params().leftIndent().zero())
570         {
571                 LyXLength const len = row->par()->params().leftIndent();
572                 int const tw = inset_owner ?
573                         inset_owner->latexTextWidth(bview) : workWidth(*bview);
574                 x += len.inPixels(tw);
575         }
576
577         LyXAlignment align; // wrong type
578
579         if (row->par()->params().align() == LYX_ALIGN_LAYOUT)
580                 align = layout->align;
581         else
582                 align = row->par()->params().align();
583
584         // set the correct parindent
585         if (row->pos() == 0) {
586                 if ((layout->labeltype == LABEL_NO_LABEL
587                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
588                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
589                      || (layout->labeltype == LABEL_STATIC
590                          && layout->latextype == LATEX_ENVIRONMENT
591                          && ! row->par()->isFirstInSequence()))
592                     && align == LYX_ALIGN_BLOCK
593                     && !row->par()->params().noindent()
594                         // in tabulars and ert paragraphs are never indented!
595                         && (!row->par()->inInset() || !row->par()->inInset()->owner() ||
596                                 (row->par()->inInset()->owner()->lyxCode() != Inset::TABULAR_CODE &&
597                                  row->par()->inInset()->owner()->lyxCode() != Inset::ERT_CODE))
598                     && (row->par()->layout() != tclass.defaultLayout() ||
599                         bview->buffer()->params.paragraph_separation ==
600                         BufferParams::PARSEP_INDENT)) {
601                         x += font_metrics::signedWidth(parindent,
602                                                   tclass.defaultfont());
603                 } else if (layout->labeltype == LABEL_BIBLIO) {
604                         // ale970405 Right width for bibitems
605                         x += bibitemMaxWidth(bview, tclass.defaultfont());
606                 }
607         }
608
609         return x;
610 }
611
612
613 int LyXText::rightMargin(Buffer const & buf, Row const & row) const
614 {
615         Inset * ins;
616         if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
617                 (ins=row.par()->getInset(row.pos())) &&
618                 (ins->needFullRow() || ins->display()))
619                 return PAPER_MARGIN;
620
621         LyXTextClass const & tclass = buf.params.getLyXTextClass();
622         LyXLayout_ptr const & layout = row.par()->layout();
623
624         int x = PAPER_MARGIN
625                 + font_metrics::signedWidth(tclass.rightmargin(),
626                                        tclass.defaultfont());
627
628         // this is the way, LyX handles the LaTeX-Environments.
629         // I have had this idea very late, so it seems to be a
630         // later added hack and this is true
631         if (row.par()->getDepth()) {
632                 // find the next level paragraph
633
634                 Paragraph const * newpar = row.par();
635
636                 do {
637                         newpar = newpar->previous();
638                 } while (newpar
639                          && newpar->getDepth() >= row.par()->getDepth());
640
641                 // make a corresponding row. Needed to call LeftMargin()
642
643                 // check wether it is a sufficent paragraph
644                 if (newpar && newpar->layout()->isEnvironment()) {
645                         Row dummyrow;
646                         dummyrow.par(const_cast<Paragraph *>(newpar));
647                         dummyrow.pos(0);
648                         x = rightMargin(buf, dummyrow);
649                 } else {
650                         // this is no longer an error, because this function
651                         // is used to clear impossible depths after changing
652                         // a layout. Since there is always a redo,
653                         // LeftMargin() is always called
654                         row.par()->params().depth(0);
655                 }
656         }
657
658         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
659         x += font_metrics::signedWidth(layout->rightmargin,
660                                        tclass.defaultfont())
661                 * 4 / (row.par()->getDepth() + 4);
662         return x;
663 }
664
665
666 int LyXText::labelEnd(BufferView & bview, Row const & row) const
667 {
668         if (row.par()->layout()->margintype == MARGIN_MANUAL) {
669                 Row tmprow = row;
670                 tmprow.pos(row.par()->size());
671                 // return the beginning of the body
672                 return leftMargin(&bview, &tmprow);
673         }
674
675         // LabelEnd is only needed if the layout
676         // fills a flushleft label.
677         return 0;
678 }
679
680
681 namespace {
682
683 // this needs special handling - only newlines count as a break point
684 pos_type addressBreakPoint(pos_type i, Paragraph * par)
685 {
686         for (; i < par->size(); ++i) {
687                 if (par->isNewline(i)) {
688                         return i;
689                 } else if (par->isInset(i) && par->getInset(i)->display()) {
690                         // FIXME: what are we doing modifying stuff here !
691                         par->getInset(i)->display(false);
692                 }
693                 ++i;
694         }
695
696         return par->size();
697 }
698
699 };
700
701
702 pos_type
703 LyXText::rowBreakPoint(BufferView & bv, Row const & row) const
704 {
705         Paragraph * par = row.par();
706
707         // maximum pixel width of a row.
708         int width = workWidth(bv) - rightMargin(*bv.buffer(), row);
709
710         // inset->textWidth() returns -1 via workWidth(),
711         // but why ?
712         if (width < 0)
713                 return par->size();
714
715         LyXLayout_ptr const & layout = par->layout();
716
717         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
718                 return addressBreakPoint(row.pos(), par);
719
720         pos_type const pos = row.pos();
721         pos_type const body_pos = par->beginningOfBody();
722         pos_type const last = par->size();
723         pos_type point = last;
724         pos_type i = pos;
725
726         // Now we iterate through until we reach the right margin
727         // or the end of the par, then choose the possible break
728         // nearest that.
729
730         int const left = leftMargin(&bv, &row);
731         int x = left;
732
733         // pixel width since last breakpoint
734         int chunkwidth = 0;
735
736         for (i = pos; i < last; ++i) {
737
738                 char const c = par->getChar(i);
739
740                 if (IsNewlineChar(c)) {
741                         point = i;
742                         break;
743                 }
744
745                 int thiswidth = singleWidth(&bv, par, i, c);
746
747                 // add the auto-hfill from label end to the body
748                 if (body_pos && i == body_pos) {
749                         thiswidth += font_metrics::width(layout->labelsep,
750                                     getLabelFont(bv.buffer(), par));
751                         if (par->isLineSeparator(i - 1))
752                                 thiswidth -= singleWidth(&bv, par, i - 1);
753                         int left_margin = labelEnd(bv, row);
754                         if (thiswidth < left_margin)
755                                 thiswidth = left_margin;
756                 }
757
758                 x += thiswidth;
759                 chunkwidth += thiswidth;
760
761                 Inset * in = par->isInset(i) ? par->getInset(i) : 0;
762                 bool display = (in && (in->display() || in->needFullRow()));
763
764                 // check whether a Display() inset is valid here.
765                 // If not, change it to non-display. FIXME:
766                 // we should not be modifying things at this
767                 // point !
768                 if (in && in->display() && (layout->isCommand() ||
769                     (layout->labeltype == LABEL_MANUAL && i < body_pos)))
770                         in->display(false);
771
772                 // break before a character that will fall off
773                 // the right of the row
774                 if (x >= width) {
775                         // if no break before or we are at an inset
776                         // that will take up a row, break here
777                         if (point == last || display || chunkwidth >= (width - left)) {
778                                 if (pos < i)
779                                         point = i - 1;
780                                 else
781                                         point = i;
782                         }
783                         break;
784                 }
785
786                 if (!in || in->isChar()) {
787                         // some insets are line separators too
788                         if (par->isLineSeparator(i)) {
789                                 point = i;
790                                 chunkwidth = 0;
791                         }
792                         continue;
793                 }
794
795                 if (!display)
796                         continue;
797                         
798                 // full row insets start at a new row
799                 if (i == pos) {
800                         if (pos < last - 1) {
801                                 point = i;
802                                 if (par->isLineSeparator(i + 1))
803                                         ++point;
804                         } else {
805                                 // to avoid extra rows
806                                 point = last;
807                         }
808                 } else {
809                         point = i - 1;
810                 }
811                 break;
812         }
813
814         if (point == last && x >= width) {
815                 // didn't find one, break at the point we reached the edge
816                 point = i;
817         } else if (i == last && x < width) {
818                 // found one, but we fell off the end of the par, so prefer
819                 // that.
820                 point = last;
821         }
822
823         // manual labels cannot be broken in LaTeX
824         if (body_pos && point < body_pos)
825                 point = body_pos - 1;
826
827         return point;
828 }
829
830
831 // returns the minimum space a row needs on the screen in pixel
832 int LyXText::fill(BufferView & bview, Row & row, int paper_width) const
833 {
834         if (paper_width < 0)
835                 return 0;
836
837         int w;
838         // get the pure distance
839         pos_type const last = row.lastPrintablePos();
840
841         // special handling of the right address boxes
842         if (row.par()->layout()->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
843                 int const tmpfill = row.fill();
844                 row.fill(0); // the minfill in MarginLeft()
845                 w = leftMargin(&bview, &row);
846                 row.fill(tmpfill);
847         } else
848                 w = leftMargin(&bview, &row);
849
850         Paragraph * par = row.par();
851         LyXLayout_ptr const & layout = par->layout();
852
853         pos_type const body_pos = par->beginningOfBody();
854         pos_type i = row.pos();
855
856         while (i <= last) {
857                 if (body_pos > 0 && i == body_pos) {
858                         w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
859                         if (par->isLineSeparator(i - 1))
860                                 w -= singleWidth(&bview, par, i - 1);
861                         int left_margin = labelEnd(bview, row);
862                         if (w < left_margin)
863                                 w = left_margin;
864                 }
865                 w += singleWidth(&bview, par, i);
866                 ++i;
867         }
868         if (body_pos > 0 && body_pos > last) {
869                 w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
870                 if (last >= 0 && par->isLineSeparator(last))
871                         w -= singleWidth(&bview, par, last);
872                 int const left_margin = labelEnd(bview, row);
873                 if (w < left_margin)
874                         w = left_margin;
875         }
876
877         int const fill = paper_width - w - rightMargin(*bview.buffer(), row);
878         return fill;
879 }
880
881
882 // returns the minimum space a manual label needs on the screen in pixel
883 int LyXText::labelFill(BufferView & bview, Row const & row) const
884 {
885         pos_type last = row.par()->beginningOfBody();
886
887         lyx::Assert(last > 0);
888
889         // -1 because a label ends either with a space that is in the label,
890         // or with the beginning of a footnote that is outside the label.
891         --last;
892
893         // a separator at this end does not count
894         if (row.par()->isLineSeparator(last))
895                 --last;
896
897         int w = 0;
898         pos_type i = row.pos();
899         while (i <= last) {
900                 w += singleWidth(&bview, row.par(), i);
901                 ++i;
902         }
903
904         int fill = 0;
905         string const & labwidstr = row.par()->params().labelWidthString();
906         if (!labwidstr.empty()) {
907                 LyXFont const labfont = getLabelFont(bview.buffer(), row.par());
908                 int const labwidth = font_metrics::width(labwidstr, labfont);
909                 fill = max(labwidth - w, 0);
910         }
911
912         return fill;
913 }
914
915
916 LColor::color LyXText::backgroundColor() const
917 {
918         if (inset_owner)
919                 return inset_owner->backgroundColor();
920         else
921                 return LColor::background;
922 }
923
924 void LyXText::setHeightOfRow(BufferView * bview, Row * row) const
925 {
926         // get the maximum ascent and the maximum descent
927         int asc = 0;
928         int desc = 0;
929         float layoutasc = 0;
930         float layoutdesc = 0;
931         float tmptop = 0;
932         LyXFont tmpfont;
933         Inset * tmpinset = 0;
934
935         // ok , let us initialize the maxasc and maxdesc value.
936         // This depends in LaTeX of the font of the last character
937         // in the paragraph. The hack below is necessary because
938         // of the possibility of open footnotes
939
940         // Correction: only the fontsize count. The other properties
941         //  are taken from the layoutfont. Nicer on the screen :)
942         Paragraph * par = row->par();
943         Paragraph * firstpar = row->par();
944
945         LyXLayout_ptr const & layout = firstpar->layout();
946
947         // as max get the first character of this row then it can increase but not
948         // decrease the height. Just some point to start with so we don't have to
949         // do the assignment below too often.
950         LyXFont font = getFont(bview->buffer(), par, row->pos());
951         LyXFont::FONT_SIZE const tmpsize = font.size();
952         font = getLayoutFont(bview->buffer(), par);
953         LyXFont::FONT_SIZE const size = font.size();
954         font.setSize(tmpsize);
955
956         LyXFont labelfont = getLabelFont(bview->buffer(), par);
957
958         float spacing_val = 1.0;
959         if (!row->par()->params().spacing().isDefault()) {
960                 spacing_val = row->par()->params().spacing().getValue();
961         } else {
962                 spacing_val = bview->buffer()->params.spacing.getValue();
963         }
964         //lyxerr << "spacing_val = " << spacing_val << endl;
965
966         int maxasc = int(font_metrics::maxAscent(font) *
967                          layout->spacing.getValue() *
968                          spacing_val);
969         int maxdesc = int(font_metrics::maxDescent(font) *
970                           layout->spacing.getValue() *
971                           spacing_val);
972
973         pos_type const pos_end = row->lastPos();
974         int labeladdon = 0;
975         int maxwidth = 0;
976
977         // Check if any insets are larger
978         for (pos_type pos = row->pos(); pos <= pos_end; ++pos) {
979                 if (row->par()->isInset(pos)) {
980                         tmpfont = getFont(bview->buffer(), row->par(), pos);
981                         tmpinset = row->par()->getInset(pos);
982                         if (tmpinset) {
983 #if 1 // this is needed for deep update on initialitation
984                                 tmpinset->update(bview, tmpfont);
985 #endif
986                                 asc = tmpinset->ascent(bview, tmpfont);
987                                 desc = tmpinset->descent(bview, tmpfont);
988                                 maxwidth += tmpinset->width(bview, tmpfont);
989                                 maxasc = max(maxasc, asc);
990                                 maxdesc = max(maxdesc, desc);
991                         }
992                 } else {
993                         maxwidth += singleWidth(bview, row->par(), pos);
994                 }
995         }
996
997         // Check if any custom fonts are larger (Asger)
998         // This is not completely correct, but we can live with the small,
999         // cosmetic error for now.
1000         LyXFont::FONT_SIZE maxsize =
1001                 row->par()->highestFontInRange(row->pos(), pos_end, size);
1002         if (maxsize > font.size()) {
1003                 font.setSize(maxsize);
1004
1005                 asc = font_metrics::maxAscent(font);
1006                 desc = font_metrics::maxDescent(font);
1007                 if (asc > maxasc)
1008                         maxasc = asc;
1009                 if (desc > maxdesc)
1010                         maxdesc = desc;
1011         }
1012
1013         // This is nicer with box insets:
1014         ++maxasc;
1015         ++maxdesc;
1016
1017         row->ascent_of_text(maxasc);
1018
1019         // is it a top line?
1020         if (!row->pos() && (row->par() == firstpar)) {
1021
1022                 // some parksips VERY EASY IMPLEMENTATION
1023                 if (bview->buffer()->params.paragraph_separation ==
1024                         BufferParams::PARSEP_SKIP)
1025                 {
1026                         if (layout->isParagraph()
1027                                 && firstpar->getDepth() == 0
1028                                 && firstpar->previous())
1029                         {
1030                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
1031                         } else if (firstpar->previous() &&
1032                                    firstpar->previous()->layout()->isParagraph() &&
1033                                    firstpar->previous()->getDepth() == 0)
1034                         {
1035                                 // is it right to use defskip here too? (AS)
1036                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
1037                         }
1038                 }
1039
1040                 // the top margin
1041                 if (!row->par()->previous() && isTopLevel())
1042                         maxasc += PAPER_MARGIN;
1043
1044                 // add the vertical spaces, that the user added
1045                 maxasc += getLengthMarkerHeight(*bview, firstpar->params().spaceTop());
1046
1047                 // do not forget the DTP-lines!
1048                 // there height depends on the font of the nearest character
1049                 if (firstpar->params().lineTop())
1050
1051                         maxasc += 2 * font_metrics::ascent('x', getFont(bview->buffer(),
1052                                         firstpar, 0));
1053                 // and now the pagebreaks
1054                 if (firstpar->params().pagebreakTop())
1055                         maxasc += 3 * defaultRowHeight();
1056
1057                 // This is special code for the chapter, since the label of this
1058                 // layout is printed in an extra row
1059                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1060                         && bview->buffer()->params.secnumdepth >= 0)
1061                 {
1062                         float spacing_val = 1.0;
1063                         if (!row->par()->params().spacing().isDefault()) {
1064                                 spacing_val = row->par()->params().spacing().getValue();
1065                         } else {
1066                                 spacing_val = bview->buffer()->params.spacing.getValue();
1067                         }
1068
1069                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1070                                          layout->spacing.getValue() *
1071                                          spacing_val)
1072                                 + int(font_metrics::maxAscent(labelfont) *
1073                                       layout->spacing.getValue() *
1074                                       spacing_val);
1075                 }
1076
1077                 // special code for the top label
1078                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1079                      || layout->labeltype == LABEL_BIBLIO
1080                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1081                     && row->par()->isFirstInSequence()
1082                     && !row->par()->getLabelstring().empty())
1083                 {
1084                         float spacing_val = 1.0;
1085                         if (!row->par()->params().spacing().isDefault()) {
1086                                 spacing_val = row->par()->params().spacing().getValue();
1087                         } else {
1088                                 spacing_val = bview->buffer()->params.spacing.getValue();
1089                         }
1090
1091                         labeladdon = int(
1092                                 (font_metrics::maxAscent(labelfont) *
1093                                  layout->spacing.getValue() *
1094                                  spacing_val)
1095                                 +(font_metrics::maxDescent(labelfont) *
1096                                   layout->spacing.getValue() *
1097                                   spacing_val)
1098                                 + layout->topsep * defaultRowHeight()
1099                                 + layout->labelbottomsep * defaultRowHeight());
1100                 }
1101
1102                 // and now the layout spaces, for example before and after a section,
1103                 // or between the items of a itemize or enumerate environment
1104
1105                 if (!firstpar->params().pagebreakTop()) {
1106                         Paragraph * prev = row->par()->previous();
1107                         if (prev)
1108                                 prev = row->par()->depthHook(row->par()->getDepth());
1109                         if (prev && prev->layout() == firstpar->layout() &&
1110                                 prev->getDepth() == firstpar->getDepth() &&
1111                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1112                         {
1113                                 layoutasc = (layout->itemsep * defaultRowHeight());
1114                         } else if (row->previous()) {
1115                                 tmptop = layout->topsep;
1116
1117                                 if (row->previous()->par()->getDepth() >= row->par()->getDepth())
1118                                         tmptop -= row->previous()->par()->layout()->bottomsep;
1119
1120                                 if (tmptop > 0)
1121                                         layoutasc = (tmptop * defaultRowHeight());
1122                         } else if (row->par()->params().lineTop()) {
1123                                 tmptop = layout->topsep;
1124
1125                                 if (tmptop > 0)
1126                                         layoutasc = (tmptop * defaultRowHeight());
1127                         }
1128
1129                         prev = row->par()->outerHook();
1130                         if (prev)  {
1131                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1132                         } else {
1133                                 if (firstpar->previous() &&
1134                                         firstpar->previous()->getDepth() == 0 &&
1135                                         firstpar->previous()->layout() !=
1136                                         firstpar->layout())
1137                                 {
1138                                         // avoid parsep
1139                                 } else if (firstpar->previous()) {
1140                                         maxasc += int(layout->parsep * defaultRowHeight());
1141                                 }
1142                         }
1143                 }
1144         }
1145
1146         // is it a bottom line?
1147         if (row->par() == par
1148                 && (!row->next() || row->next()->par() != row->par())) {
1149                 // the bottom margin
1150                 if (!par->next() && isTopLevel())
1151                         maxdesc += PAPER_MARGIN;
1152
1153                 // add the vertical spaces, that the user added
1154                 maxdesc += getLengthMarkerHeight(*bview, firstpar->params().spaceBottom());
1155
1156                 // do not forget the DTP-lines!
1157                 // there height depends on the font of the nearest character
1158                 if (firstpar->params().lineBottom())
1159                         maxdesc += 2 * font_metrics::ascent('x',
1160                                                        getFont(bview->buffer(),
1161                                                                par,
1162                                                                max(pos_type(0), par->size() - 1)));
1163
1164                 // and now the pagebreaks
1165                 if (firstpar->params().pagebreakBottom())
1166                         maxdesc += 3 * defaultRowHeight();
1167
1168                 // and now the layout spaces, for example before and after
1169                 // a section, or between the items of a itemize or enumerate
1170                 // environment
1171                 if (!firstpar->params().pagebreakBottom()
1172                     && row->par()->next()) {
1173                         Paragraph * nextpar = row->par()->next();
1174                         Paragraph * comparepar = row->par();
1175                         float usual = 0;
1176                         float unusual = 0;
1177
1178                         if (comparepar->getDepth() > nextpar->getDepth()) {
1179                                 usual = (comparepar->layout()->bottomsep * defaultRowHeight());
1180                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1181                                 if (comparepar->layout()!= nextpar->layout()
1182                                         || nextpar->getLabelWidthString() !=
1183                                         comparepar->getLabelWidthString())
1184                                 {
1185                                         unusual = (comparepar->layout()->bottomsep * defaultRowHeight());
1186                                 }
1187                                 if (unusual > usual)
1188                                         layoutdesc = unusual;
1189                                 else
1190                                         layoutdesc = usual;
1191                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1192
1193                                 if (comparepar->layout() != nextpar->layout()
1194                                         || nextpar->getLabelWidthString() !=
1195                                         comparepar->getLabelWidthString())
1196                                         layoutdesc = int(comparepar->layout()->bottomsep * defaultRowHeight());
1197                         }
1198                 }
1199         }
1200
1201         // incalculate the layout spaces
1202         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1203         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1204
1205         // calculate the new height of the text
1206         height -= row->height();
1207
1208         row->height(maxasc + maxdesc + labeladdon);
1209         row->baseline(maxasc + labeladdon);
1210
1211         height += row->height();
1212
1213         row->top_of_text(row->baseline() - font_metrics::maxAscent(font));
1214
1215         float x = 0;
1216         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1217                 float dummy;
1218                 // this IS needed
1219                 row->width(maxwidth);
1220                 prepareToPrint(bview, row, x, dummy, dummy, dummy, false);
1221         }
1222         row->width(int(maxwidth + x));
1223         if (inset_owner) {
1224                 Row * r = firstrow;
1225                 width = max(0, workWidth(*bview));
1226                 while (r) {
1227                         if (r->width() > width)
1228                                 width = r->width();
1229                         r = r->next();
1230                 }
1231         }
1232 }
1233
1234
1235 // Appends the implicit specified paragraph before the specified row,
1236 // start at the implicit given position
1237 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1238 {
1239         pos_type const last = row->par()->size();
1240         bool done = false;
1241
1242         do {
1243                 pos_type z = rowBreakPoint(*bview, *row);
1244
1245                 Row * tmprow = row;
1246
1247                 if (z < last) {
1248                         ++z;
1249                         insertRow(row, row->par(), z);
1250                         row = row->next();
1251                         row->height(0);
1252                 } else {
1253                         done = true;
1254                 }
1255
1256                 // Set the dimensions of the row
1257                 // fixed fill setting now by calling inset->update() in
1258                 // SingleWidth when needed!
1259                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1260                 setHeightOfRow(bview, tmprow);
1261
1262         } while (!done);
1263 }
1264
1265
1266 // Do we even need this at all ? Code that uses  RowPainter *already*
1267 // sets need_break_row when it sees a CHANGED_IN_DRAW, though not
1268 // quite like this
1269 void LyXText::markChangeInDraw(BufferView * bv, Row * row, Row * prev)
1270 {
1271         if (prev && prev->par() == row->par()) {
1272                 breakAgainOneRow(bv, prev);
1273                 if (prev->next() != row) {
1274                         // breakAgainOneRow() has removed row_
1275                         need_break_row = prev;
1276                 } else {
1277                         need_break_row = row;
1278                 }
1279         } else if (!prev) {
1280                 need_break_row = firstrow;
1281         } else {
1282                 need_break_row = prev->next();
1283         }
1284         setCursor(bv, cursor.par(), cursor.pos());
1285         /* FIXME */
1286 }
1287
1288
1289 void LyXText::breakAgain(BufferView * bview, Row * row) const
1290 {
1291         bool not_ready = true;
1292
1293         do  {
1294                 pos_type z = rowBreakPoint(*bview, *row);
1295                 Row * tmprow = row;
1296
1297                 if (z < row->par()->size()) {
1298                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1299                                 // insert a new row
1300                                 ++z;
1301                                 insertRow(row, row->par(), z);
1302                                 row = row->next();
1303                                 row->height(0);
1304                         } else  {
1305                                 row = row->next();
1306                                 ++z;
1307                                 if (row->pos() == z)
1308                                         not_ready = false;     // the rest will not change
1309                                 else {
1310                                         row->pos(z);
1311                                 }
1312                         }
1313                 } else {
1314                         // if there are some rows too much, delete them
1315                         // only if you broke the whole paragraph!
1316                         Row * tmprow2 = row;
1317                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1318                                 tmprow2 = tmprow2->next();
1319                         }
1320                         while (tmprow2 != row) {
1321                                 tmprow2 = tmprow2->previous();
1322                                 removeRow(tmprow2->next());
1323                         }
1324                         not_ready = false;
1325                 }
1326
1327                 // set the dimensions of the row
1328                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1329                 setHeightOfRow(bview, tmprow);
1330         } while (not_ready);
1331 }
1332
1333
1334 // this is just a little changed version of break again
1335 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1336 {
1337         pos_type z = rowBreakPoint(*bview, *row);
1338         Row * tmprow = row;
1339
1340         if (z < row->par()->size()) {
1341                 if (!row->next()
1342                     || (row->next() && row->next()->par() != row->par())) {
1343                         // insert a new row
1344                         ++z;
1345                         insertRow(row, row->par(), z);
1346                         row = row->next();
1347                         row->height(0);
1348                 } else  {
1349                         row = row->next();
1350                         ++z;
1351                         if (row->pos() != z)
1352                                 row->pos(z);
1353                 }
1354         } else {
1355                 // if there are some rows too much, delete them
1356                 // only if you broke the whole paragraph!
1357                 Row * tmprow2 = row;
1358                 while (tmprow2->next()
1359                        && tmprow2->next()->par() == row->par()) {
1360                         tmprow2 = tmprow2->next();
1361                 }
1362                 while (tmprow2 != row) {
1363                         tmprow2 = tmprow2->previous();
1364                         removeRow(tmprow2->next());
1365                 }
1366         }
1367
1368         // set the dimensions of the row
1369         tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1370         setHeightOfRow(bview, tmprow);
1371 }
1372
1373
1374 void LyXText::breakParagraph(BufferView * bview,
1375                              ParagraphList & paragraphs, char keep_layout)
1376 {
1377         // allow only if at start or end, or all previous is new text
1378         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1379                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1380                 return;
1381
1382         LyXTextClass const & tclass =
1383                 bview->buffer()->params.getLyXTextClass();
1384         LyXLayout_ptr const & layout = cursor.par()->layout();
1385
1386         // this is only allowed, if the current paragraph is not empty or caption
1387         // and if it has not the keepempty flag aktive
1388         if (cursor.par()->empty()
1389            && layout->labeltype != LABEL_SENSITIVE
1390            && !layout->keepempty)
1391                 return;
1392
1393         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1394
1395         // Always break behind a space
1396         //
1397         // It is better to erase the space (Dekel)
1398         if (cursor.pos() < cursor.par()->size()
1399              && cursor.par()->isLineSeparator(cursor.pos()))
1400            cursor.par()->erase(cursor.pos());
1401         // cursor.pos(cursor.pos() + 1);
1402
1403         // break the paragraph
1404         if (keep_layout)
1405                 keep_layout = 2;
1406         else
1407                 keep_layout = layout->isEnvironment();
1408
1409         // we need to set this before we insert the paragraph. IMO the
1410         // breakParagraph call should return a bool if it inserts the
1411         // paragraph before or behind and we should react on that one
1412         // but we can fix this in 1.3.0 (Jug 20020509)
1413         bool const isempty = (layout->keepempty && cursor.par()->empty());
1414         ::breakParagraph(bview->buffer()->params, paragraphs, cursor.par(), cursor.pos(),
1415                        keep_layout);
1416
1417         // well this is the caption hack since one caption is really enough
1418         if (layout->labeltype == LABEL_SENSITIVE) {
1419                 if (!cursor.pos())
1420                         // set to standard-layout
1421                         cursor.par()->applyLayout(tclass.defaultLayout());
1422                 else
1423                         // set to standard-layout
1424                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1425         }
1426
1427         // if the cursor is at the beginning of a row without prior newline,
1428         // move one row up!
1429         // This touches only the screen-update. Otherwise we would may have
1430         // an empty row on the screen
1431         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1432                          && cursor.row()->pos() == cursor.pos())
1433         {
1434                 cursorLeft(bview);
1435         }
1436
1437         status(bview, LyXText::NEED_MORE_REFRESH);
1438         refresh_row = cursor.row();
1439         refresh_y = cursor.y() - cursor.row()->baseline();
1440
1441         // Do not forget the special right address boxes
1442         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1443                 while (refresh_row->previous() &&
1444                        refresh_row->previous()->par() == refresh_row->par())
1445                 {
1446                         refresh_row = refresh_row->previous();
1447                         refresh_y -= refresh_row->height();
1448                 }
1449         }
1450         removeParagraph(cursor.row());
1451
1452         // set the dimensions of the cursor row
1453         cursor.row()->fill(fill(*bview, *cursor.row(), workWidth(*bview)));
1454
1455         setHeightOfRow(bview, cursor.row());
1456
1457 #warning Trouble Point! (Lgb)
1458         // When ::breakParagraph is called from within an inset we must
1459         // ensure that the correct ParagraphList is used. Today that is not
1460         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1461         while (!cursor.par()->next()->empty()
1462           && cursor.par()->next()->isNewline(0))
1463            cursor.par()->next()->erase(0);
1464
1465         insertParagraph(bview, cursor.par()->next(), cursor.row());
1466
1467         updateCounters(bview);
1468
1469         // This check is necessary. Otherwise the new empty paragraph will
1470         // be deleted automatically. And it is more friendly for the user!
1471         if (cursor.pos() || isempty)
1472                 setCursor(bview, cursor.par()->next(), 0);
1473         else
1474                 setCursor(bview, cursor.par(), 0);
1475
1476         if (cursor.row()->next())
1477                 breakAgain(bview, cursor.row()->next());
1478
1479         need_break_row = 0;
1480 }
1481
1482
1483 // Just a macro to make some thing easier.
1484 void LyXText::redoParagraph(BufferView * bview) const
1485 {
1486         clearSelection();
1487         redoParagraphs(bview, cursor, cursor.par()->next());
1488         setCursorIntern(bview, cursor.par(), cursor.pos());
1489 }
1490
1491
1492 // insert a character, moves all the following breaks in the
1493 // same Paragraph one to the right and make a rebreak
1494 void LyXText::insertChar(BufferView * bview, char c)
1495 {
1496         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1497
1498         // When the free-spacing option is set for the current layout,
1499         // disable the double-space checking
1500
1501         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1502                 cursor.row()->par()->isFreeSpacing();
1503
1504         if (lyxrc.auto_number) {
1505                 static string const number_operators = "+-/*";
1506                 static string const number_unary_operators = "+-";
1507                 static string const number_seperators = ".,:";
1508
1509                 if (current_font.number() == LyXFont::ON) {
1510                         if (!IsDigit(c) && !contains(number_operators, c) &&
1511                             !(contains(number_seperators, c) &&
1512                               cursor.pos() >= 1 &&
1513                               cursor.pos() < cursor.par()->size() &&
1514                               getFont(bview->buffer(),
1515                                       cursor.par(),
1516                                       cursor.pos()).number() == LyXFont::ON &&
1517                               getFont(bview->buffer(),
1518                                       cursor.par(),
1519                                       cursor.pos() - 1).number() == LyXFont::ON)
1520                            )
1521                                 number(bview); // Set current_font.number to OFF
1522                 } else if (IsDigit(c) &&
1523                            real_current_font.isVisibleRightToLeft()) {
1524                         number(bview); // Set current_font.number to ON
1525
1526                         if (cursor.pos() > 0) {
1527                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1528                                 if (contains(number_unary_operators, c) &&
1529                                     (cursor.pos() == 1 ||
1530                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1531                                      cursor.par()->isNewline(cursor.pos() - 2))
1532                                   ) {
1533                                         setCharFont(bview->buffer(),
1534                                                     cursor.par(),
1535                                                     cursor.pos() - 1,
1536                                                     current_font);
1537                                 } else if (contains(number_seperators, c) &&
1538                                            cursor.pos() >= 2 &&
1539                                            getFont(bview->buffer(),
1540                                                    cursor.par(),
1541                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1542                                         setCharFont(bview->buffer(),
1543                                                     cursor.par(),
1544                                                     cursor.pos() - 1,
1545                                                     current_font);
1546                                 }
1547                         }
1548                 }
1549         }
1550
1551
1552         // First check, if there will be two blanks together or a blank at
1553         // the beginning of a paragraph.
1554         // I decided to handle blanks like normal characters, the main
1555         // difference are the special checks when calculating the row.fill
1556         // (blank does not count at the end of a row) and the check here
1557
1558         // The bug is triggered when we type in a description environment:
1559         // The current_font is not changed when we go from label to main text
1560         // and it should (along with realtmpfont) when we type the space.
1561         // CHECK There is a bug here! (Asger)
1562
1563         LyXFont realtmpfont = real_current_font;
1564         LyXFont rawtmpfont = current_font;
1565         // store the current font.  This is because of the use of cursor
1566         // movements. The moving cursor would refresh the current font
1567
1568         // Get the font that is used to calculate the baselineskip
1569         pos_type const lastpos = cursor.par()->size();
1570         LyXFont rawparfont =
1571                 cursor.par()->getFontSettings(bview->buffer()->params,
1572                                               lastpos - 1);
1573
1574         bool jumped_over_space = false;
1575
1576         if (!freeSpacing && IsLineSeparatorChar(c)) {
1577                 if ((cursor.pos() > 0
1578                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1579                     || (cursor.pos() > 0
1580                         && cursor.par()->isNewline(cursor.pos() - 1))
1581                     || (cursor.pos() == 0)) {
1582                         static bool sent_space_message = false;
1583                         if (!sent_space_message) {
1584                                 if (cursor.pos() == 0)
1585                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1586                                 else
1587                                         bview->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1588                                 sent_space_message = true;
1589                         }
1590                         charInserted();
1591                         return;
1592                 }
1593         } else if (IsNewlineChar(c)) {
1594                 if (cursor.pos() <= cursor.par()->beginningOfBody()) {
1595                         charInserted();
1596                         return;
1597                 }
1598                 // No newline at first position of a paragraph or behind labels.
1599                 // TeX does not allow that
1600
1601                 if (cursor.pos() < cursor.par()->size() &&
1602                     cursor.par()->isLineSeparator(cursor.pos()))
1603                         // newline always after a blank!
1604                         cursorRight(bview);
1605                 cursor.row()->fill(-1);        // to force a new break
1606         }
1607
1608         // the display inset stuff
1609         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1610                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1611                 if (inset && (inset->display() || inset->needFullRow())) {
1612                         // force a new break
1613                         cursor.row()->fill(-1); // to force a new break
1614                 }
1615         }
1616
1617         // get the cursor row fist
1618         Row * row = cursor.row();
1619         int y = cursor.y() - row->baseline();
1620         if (c != Paragraph::META_INSET) {
1621                 // Here case LyXText::InsertInset  already insertet the character
1622                 cursor.par()->insertChar(cursor.pos(), c);
1623         }
1624         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1625
1626         if (!jumped_over_space) {
1627                 // refresh the positions
1628                 Row * tmprow = row;
1629                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1630                         tmprow = tmprow->next();
1631                         tmprow->pos(tmprow->pos() + 1);
1632                 }
1633         }
1634
1635         // Is there a break one row above
1636         if (row->previous() && row->previous()->par() == row->par()
1637             && (cursor.par()->isLineSeparator(cursor.pos())
1638                 || cursor.par()->isNewline(cursor.pos())
1639                 || ((cursor.pos() < cursor.par()->size()) &&
1640                     cursor.par()->isInset(cursor.pos()+1))
1641                 || cursor.row()->fill() == -1))
1642         {
1643                 pos_type z = rowBreakPoint(*bview, *row->previous());
1644
1645                 if (z >= row->pos()) {
1646                         row->pos(z + 1);
1647
1648                         // set the dimensions of the row above
1649                         row->previous()->fill(fill(*bview,
1650                                                    *row->previous(),
1651                                                    workWidth(*bview)));
1652
1653                         setHeightOfRow(bview, row->previous());
1654
1655                         y -= row->previous()->height();
1656                         refresh_y = y;
1657                         refresh_row = row->previous();
1658                         status(bview, LyXText::NEED_MORE_REFRESH);
1659
1660                         breakAgainOneRow(bview, row);
1661
1662                         current_font = rawtmpfont;
1663                         real_current_font = realtmpfont;
1664                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1665                                   false, cursor.boundary());
1666                         // cursor MUST be in row now.
1667
1668                         if (row->next() && row->next()->par() == row->par())
1669                                 need_break_row = row->next();
1670                         else
1671                                 need_break_row = 0;
1672
1673                         // check, wether the last characters font has changed.
1674                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1675                             && rawparfont != rawtmpfont)
1676                                 redoHeightOfParagraph(bview, cursor);
1677
1678                         charInserted();
1679                         return;
1680                 }
1681         }
1682
1683         // recalculate the fill of the row
1684         if (row->fill() >= 0) {
1685                 // needed because a newline will set fill to -1. Otherwise
1686                 // we would not get a rebreak!
1687                 row->fill(fill(*bview, *row, workWidth(*bview)));
1688         }
1689
1690         if (c == Paragraph::META_INSET || row->fill() < 0) {
1691                 refresh_y = y;
1692                 refresh_row = row;
1693                 status(bview, LyXText::NEED_MORE_REFRESH);
1694                 breakAgainOneRow(bview, row);
1695                 // will the cursor be in another row now?
1696                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1697                         if (row->next() && row->next()->par() == row->par())
1698                                 // this should always be true
1699                                 row = row->next();
1700                         breakAgainOneRow(bview, row);
1701                 }
1702                 current_font = rawtmpfont;
1703                 real_current_font = realtmpfont;
1704
1705                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1706                           cursor.boundary());
1707                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1708                     != cursor.boundary())
1709                         setCursor(bview, cursor.par(), cursor.pos(), false,
1710                           !cursor.boundary());
1711                 if (row->next() && row->next()->par() == row->par())
1712                         need_break_row = row->next();
1713                 else
1714                         need_break_row = 0;
1715         } else {
1716                 refresh_y = y;
1717                 refresh_row = row;
1718
1719                 int const tmpheight = row->height();
1720                 setHeightOfRow(bview, row);
1721                 if (tmpheight == row->height())
1722                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1723                 else
1724                         status(bview, LyXText::NEED_MORE_REFRESH);
1725
1726                 current_font = rawtmpfont;
1727                 real_current_font = realtmpfont;
1728                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1729                           cursor.boundary());
1730         }
1731
1732         // check, wether the last characters font has changed.
1733         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1734             && rawparfont != rawtmpfont) {
1735                 redoHeightOfParagraph(bview, cursor);
1736         } else {
1737                 // now the special right address boxes
1738                 if (cursor.par()->layout()->margintype
1739                     == MARGIN_RIGHT_ADDRESS_BOX) {
1740                         redoDrawingOfParagraph(bview, cursor);
1741                 }
1742         }
1743
1744         charInserted();
1745 }
1746
1747
1748 void LyXText::charInserted()
1749 {
1750         // Here we could call FinishUndo for every 20 characters inserted.
1751         // This is from my experience how emacs does it.
1752         static unsigned int counter;
1753         if (counter < 20) {
1754                 ++counter;
1755         } else {
1756                 finishUndo();
1757                 counter = 0;
1758         }
1759 }
1760
1761
1762 void LyXText::prepareToPrint(BufferView * bview,
1763                              Row * row, float & x,
1764                              float & fill_separator,
1765                              float & fill_hfill,
1766                              float & fill_label_hfill,
1767                              bool bidi) const
1768 {
1769         float nlh;
1770         float ns;
1771
1772         float w = row->fill();
1773         fill_hfill = 0;
1774         fill_label_hfill = 0;
1775         fill_separator = 0;
1776         fill_label_hfill = 0;
1777
1778         bool const is_rtl =
1779                 row->par()->isRightToLeftPar(bview->buffer()->params);
1780         if (is_rtl) {
1781                 x = (workWidth(*bview) > 0)
1782                         ? rightMargin(*bview->buffer(), *row) : 0;
1783         } else
1784                 x = (workWidth(*bview) > 0)
1785                         ? leftMargin(bview, row) : 0;
1786
1787         // is there a manual margin with a manual label
1788         LyXLayout_ptr const & layout = row->par()->layout();
1789
1790         if (layout->margintype == MARGIN_MANUAL
1791             && layout->labeltype == LABEL_MANUAL) {
1792                 /// We might have real hfills in the label part
1793                 nlh = row->numberOfLabelHfills();
1794
1795                 // A manual label par (e.g. List) has an auto-hfill
1796                 // between the label text and the body of the
1797                 // paragraph too.
1798                 // But we don't want to do this auto hfill if the par
1799                 // is empty.
1800                 if (!row->par()->empty())
1801                         ++nlh;
1802                         
1803                 if (nlh && !row->par()->getLabelWidthString().empty()) {
1804                         fill_label_hfill = labelFill(*bview, *row) / nlh;
1805                 }
1806         }
1807
1808         // are there any hfills in the row?
1809         float const nh = row->numberOfHfills();
1810
1811         if (nh) {
1812                 if (w > 0)
1813                         fill_hfill = w / nh;
1814         // we don't have to look at the alignment if it is ALIGN_LEFT and
1815         // if the row is already larger then the permitted width as then
1816         // we force the LEFT_ALIGN'edness!
1817         } else if (static_cast<int>(row->width()) < workWidth(*bview)) {
1818                 // is it block, flushleft or flushright?
1819                 // set x how you need it
1820                 int align;
1821                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
1822                         align = layout->align;
1823                 } else {
1824                         align = row->par()->params().align();
1825                 }
1826
1827                 // center displayed insets
1828                 Inset * inset;
1829                 if (row->par()->isInset(row->pos())
1830                     && (inset=row->par()->getInset(row->pos()))
1831                     && (inset->display())) // || (inset->scroll() < 0)))
1832                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1833                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1834                 // ERT insets should always be LEFT ALIGNED on screen
1835                 inset = row->par()->inInset();
1836                 if (inset && inset->owner() &&
1837                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1838                 {
1839                         align = LYX_ALIGN_LEFT;
1840                 }
1841
1842                 switch (align) {
1843             case LYX_ALIGN_BLOCK:
1844                         ns = row->numberOfSeparators();
1845                         if (ns && row->next() && row->next()->par() == row->par() &&
1846                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
1847                             && !(row->next()->par()->isInset(row->next()->pos())
1848                                  && row->next()->par()->getInset(row->next()->pos())
1849                                  && row->next()->par()->getInset(row->next()->pos())->display())
1850                                 )
1851                         {
1852                                 fill_separator = w / ns;
1853                         } else if (is_rtl) {
1854                                 x += w;
1855                         }
1856                         break;
1857             case LYX_ALIGN_RIGHT:
1858                         x += w;
1859                         break;
1860             case LYX_ALIGN_CENTER:
1861                         x += w / 2;
1862                         break;
1863                 }
1864         }
1865         if (!bidi)
1866                 return;
1867
1868         computeBidiTables(bview->buffer(), row);
1869         if (is_rtl) {
1870                 pos_type body_pos = row->par()->beginningOfBody();
1871                 pos_type last = row->lastPos();
1872
1873                 if (body_pos > 0 &&
1874                     (body_pos - 1 > last ||
1875                      !row->par()->isLineSeparator(body_pos - 1))) {
1876                         x += font_metrics::width(layout->labelsep,
1877                                             getLabelFont(bview->buffer(), row->par()));
1878                         if (body_pos - 1 <= last)
1879                                 x += fill_label_hfill;
1880                 }
1881         }
1882 }
1883
1884
1885 // important for the screen
1886
1887
1888 // the cursor set functions have a special mechanism. When they
1889 // realize, that you left an empty paragraph, they will delete it.
1890 // They also delete the corresponding row
1891
1892 void LyXText::cursorRightOneWord(BufferView * bview) const
1893 {
1894         // treat floats, HFills and Insets as words
1895         LyXCursor tmpcursor = cursor;
1896         // CHECK See comment on top of text.C
1897
1898         if (tmpcursor.pos() == tmpcursor.par()->size()
1899             && tmpcursor.par()->next()) {
1900                         tmpcursor.par(tmpcursor.par()->next());
1901                         tmpcursor.pos(0);
1902         } else {
1903                 int steps = 0;
1904
1905                 // Skip through initial nonword stuff.
1906                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1907                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
1908                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
1909                         tmpcursor.pos(tmpcursor.pos() + 1);
1910                         ++steps;
1911                 }
1912                 // Advance through word.
1913                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1914                         tmpcursor.par()->isWord(tmpcursor.pos())) {
1915                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
1916                         tmpcursor.pos(tmpcursor.pos() + 1);
1917                         ++steps;
1918                 }
1919         }
1920         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1921 }
1922
1923
1924 void LyXText::cursorTab(BufferView * bview) const
1925 {
1926         LyXCursor tmpcursor = cursor;
1927         while (tmpcursor.pos() < tmpcursor.par()->size()
1928            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
1929         tmpcursor.pos(tmpcursor.pos() + 1);
1930
1931         if (tmpcursor.pos() == tmpcursor.par()->size()) {
1932                 if (tmpcursor.par()->next()) {
1933                         tmpcursor.par(tmpcursor.par()->next());
1934                         tmpcursor.pos(0);
1935                 }
1936         } else
1937                 tmpcursor.pos(tmpcursor.pos() + 1);
1938         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1939 }
1940
1941
1942 // Skip initial whitespace at end of word and move cursor to *start*
1943 // of prior word, not to end of next prior word.
1944 void LyXText::cursorLeftOneWord(BufferView * bview)  const
1945 {
1946         LyXCursor tmpcursor = cursor;
1947         cursorLeftOneWord(tmpcursor);
1948         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1949 }
1950
1951
1952 void LyXText::cursorLeftOneWord(LyXCursor & cur) const
1953 {
1954         // treat HFills, floats and Insets as words
1955         cur = cursor;
1956         while (cur.pos()
1957                && (cur.par()->isSeparator(cur.pos() - 1)
1958                    || cur.par()->isKomma(cur.pos() - 1))
1959                && !(cur.par()->isHfill(cur.pos() - 1)
1960                     || cur.par()->isInset(cur.pos() - 1)))
1961                 cur.pos(cur.pos() - 1);
1962
1963         if (cur.pos()
1964             && (cur.par()->isInset(cur.pos() - 1)
1965                 || cur.par()->isHfill(cur.pos() - 1))) {
1966                 cur.pos(cur.pos() - 1);
1967         } else if (!cur.pos()) {
1968                 if (cur.par()->previous()) {
1969                         cur.par(cur.par()->previous());
1970                         cur.pos(cur.par()->size());
1971                 }
1972         } else {                // Here, cur != 0
1973                 while (cur.pos() > 0 &&
1974                        cur.par()->isWord(cur.pos() - 1))
1975                         cur.pos(cur.pos() - 1);
1976         }
1977 }
1978
1979
1980 // Select current word. This depends on behaviour of
1981 // CursorLeftOneWord(), so it is patched as well.
1982 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
1983                       word_location const loc) const
1984 {
1985         // first put the cursor where we wana start to select the word
1986         from = cursor;
1987         switch (loc) {
1988         case WHOLE_WORD_STRICT:
1989                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
1990                     || cursor.par()->isSeparator(cursor.pos())
1991                     || cursor.par()->isKomma(cursor.pos())
1992                     || cursor.par()->isSeparator(cursor.pos() - 1)
1993                     || cursor.par()->isKomma(cursor.pos() - 1)) {
1994                         to = from;
1995                         return;
1996                 }
1997                 // no break here, we go to the next
1998
1999         case WHOLE_WORD:
2000                 // Move cursor to the beginning, when not already there.
2001                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2002                     && !from.par()->isKomma(from.pos() - 1))
2003                         cursorLeftOneWord(from);
2004                 break;
2005         case PREVIOUS_WORD:
2006                 // always move the cursor to the beginning of previous word
2007                 cursorLeftOneWord(from);
2008                 break;
2009         case NEXT_WORD:
2010                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2011                 break;
2012         case PARTIAL_WORD:
2013                 break;
2014         }
2015         to = from;
2016         while (to.pos() < to.par()->size()
2017                && !to.par()->isSeparator(to.pos())
2018                && !to.par()->isKomma(to.pos())
2019                && !to.par()->isHfill(to.pos())
2020                && !to.par()->isInset(to.pos()))
2021         {
2022                 to.pos(to.pos() + 1);
2023         }
2024 }
2025
2026
2027 void LyXText::selectWord(BufferView * bview, word_location const loc)
2028 {
2029         LyXCursor from;
2030         LyXCursor to;
2031         getWord(from, to, loc);
2032         if (cursor != from)
2033                 setCursor(bview, from.par(), from.pos());
2034         if (to == from)
2035                 return;
2036         selection.cursor = cursor;
2037         setCursor(bview, to.par(), to.pos());
2038         setSelection(bview);
2039 }
2040
2041
2042 // Select the word currently under the cursor when no
2043 // selection is currently set
2044 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2045                                         word_location const loc)
2046 {
2047         if (!selection.set()) {
2048                 selectWord(bview, loc);
2049                 return selection.set();
2050         }
2051         return false;
2052 }
2053
2054
2055 void LyXText::acceptChange(BufferView * bv)
2056 {
2057         if (!selection.set() && cursor.par()->size())
2058                 return;
2059
2060         bv->hideCursor();
2061
2062         if (selection.start.par() == selection.end.par()) {
2063                 LyXCursor & startc = selection.start;
2064                 LyXCursor & endc = selection.end;
2065                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2066                 startc.par()->acceptChange(startc.pos(), endc.pos());
2067                 finishUndo();
2068                 clearSelection();
2069                 redoParagraphs(bv, startc, startc.par()->next());
2070                 setCursorIntern(bv, startc.par(), 0);
2071         }
2072 #warning handle multi par selection
2073 }
2074
2075
2076 void LyXText::rejectChange(BufferView * bv)
2077 {
2078         if (!selection.set() && cursor.par()->size())
2079                 return;
2080
2081         bv->hideCursor();
2082
2083         if (selection.start.par() == selection.end.par()) {
2084                 LyXCursor & startc = selection.start;
2085                 LyXCursor & endc = selection.end;
2086                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2087                 startc.par()->rejectChange(startc.pos(), endc.pos());
2088                 finishUndo();
2089                 clearSelection();
2090                 redoParagraphs(bv, startc, startc.par()->next());
2091                 setCursorIntern(bv, startc.par(), 0);
2092         }
2093 #warning handle multi par selection
2094 }
2095
2096
2097 // This function is only used by the spellchecker for NextWord().
2098 // It doesn't handle LYX_ACCENTs and probably never will.
2099 WordLangTuple const
2100 LyXText::selectNextWordToSpellcheck(BufferView * bview, float & value) const
2101 {
2102         if (the_locking_inset) {
2103                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2104                 if (!word.word().empty()) {
2105                         value += float(cursor.y());
2106                         value /= float(height);
2107                         return word;
2108                 }
2109                 // we have to go on checking so move cursor to the next char
2110                 if (cursor.pos() == cursor.par()->size()) {
2111                         if (!cursor.par()->next())
2112                                 return word;
2113                         cursor.par(cursor.par()->next());
2114                         cursor.pos(0);
2115                 } else
2116                         cursor.pos(cursor.pos() + 1);
2117         }
2118         Paragraph * tmppar = cursor.par();
2119
2120         // If this is not the very first word, skip rest of
2121         // current word because we are probably in the middle
2122         // of a word if there is text here.
2123         if (cursor.pos() || cursor.par()->previous()) {
2124                 while (cursor.pos() < cursor.par()->size()
2125                        && cursor.par()->isLetter(cursor.pos()))
2126                         cursor.pos(cursor.pos() + 1);
2127         }
2128
2129         // Now, skip until we have real text (will jump paragraphs)
2130         while (1) {
2131                 Paragraph * cpar(cursor.par());
2132                 pos_type const cpos(cursor.pos());
2133
2134                 if (cpos == cpar->size()) {
2135                         if (cpar->next()) {
2136                                 cursor.par(cpar->next());
2137                                 cursor.pos(0);
2138                                 continue;
2139                         }
2140                         break;
2141                 }
2142
2143                 bool const is_bad_inset(cpar->isInset(cpos)
2144                         && !cpar->getInset(cpos)->allowSpellcheck());
2145
2146                 if (cpar->isLetter(cpos) && !isDeletedText(*cpar, cpos)
2147                         && !is_bad_inset)
2148                         break;
2149
2150                 cursor.pos(cpos + 1);
2151         }
2152
2153         // now check if we hit an inset so it has to be a inset containing text!
2154         if (cursor.pos() < cursor.par()->size() &&
2155             cursor.par()->isInset(cursor.pos())) {
2156                 // lock the inset!
2157                 cursor.par()->getInset(cursor.pos())->edit(bview);
2158                 // now call us again to do the above trick
2159                 // but obviously we have to start from down below ;)
2160                 return bview->text->selectNextWordToSpellcheck(bview, value);
2161         }
2162
2163         // Update the value if we changed paragraphs
2164         if (cursor.par() != tmppar) {
2165                 setCursor(bview, cursor.par(), cursor.pos());
2166                 value = float(cursor.y())/float(height);
2167         }
2168
2169         // Start the selection from here
2170         selection.cursor = cursor;
2171
2172         string lang_code(
2173                 getFont(bview->buffer(), cursor.par(), cursor.pos())
2174                         .language()->code());
2175         // and find the end of the word (insets like optional hyphens
2176         // and ligature break are part of a word)
2177         while (cursor.pos() < cursor.par()->size()
2178                && cursor.par()->isLetter(cursor.pos())
2179                && !isDeletedText(*cursor.par(), cursor.pos()))
2180                 cursor.pos(cursor.pos() + 1);
2181
2182         // Finally, we copy the word to a string and return it
2183         string str;
2184         if (selection.cursor.pos() < cursor.pos()) {
2185                 pos_type i;
2186                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2187                         if (!cursor.par()->isInset(i))
2188                                 str += cursor.par()->getChar(i);
2189                 }
2190         }
2191         return WordLangTuple(str, lang_code);
2192 }
2193
2194
2195 // This one is also only for the spellchecker
2196 void LyXText::selectSelectedWord(BufferView * bview)
2197 {
2198         if (the_locking_inset) {
2199                 the_locking_inset->selectSelectedWord(bview);
2200                 return;
2201         }
2202         // move cursor to the beginning
2203         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2204
2205         // set the sel cursor
2206         selection.cursor = cursor;
2207
2208         // now find the end of the word
2209         while (cursor.pos() < cursor.par()->size()
2210                && (cursor.par()->isLetter(cursor.pos())))
2211                 cursor.pos(cursor.pos() + 1);
2212
2213         setCursor(bview, cursor.par(), cursor.pos());
2214
2215         // finally set the selection
2216         setSelection(bview);
2217 }
2218
2219
2220 // Delete from cursor up to the end of the current or next word.
2221 void LyXText::deleteWordForward(BufferView * bview)
2222 {
2223         if (cursor.par()->empty())
2224                 cursorRight(bview);
2225         else {
2226                 LyXCursor tmpcursor = cursor;
2227                 tmpcursor.row(0); // ??
2228                 selection.set(true); // to avoid deletion
2229                 cursorRightOneWord(bview);
2230                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2231                 selection.cursor = cursor;
2232                 cursor = tmpcursor;
2233                 setSelection(bview);
2234
2235                 // Great, CutSelection() gets rid of multiple spaces.
2236                 cutSelection(bview, true, false);
2237         }
2238 }
2239
2240
2241 // Delete from cursor to start of current or prior word.
2242 void LyXText::deleteWordBackward(BufferView * bview)
2243 {
2244         if (cursor.par()->empty())
2245                 cursorLeft(bview);
2246         else {
2247                 LyXCursor tmpcursor = cursor;
2248                 tmpcursor.row(0); // ??
2249                 selection.set(true); // to avoid deletion
2250                 cursorLeftOneWord(bview);
2251                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2252                 selection.cursor = cursor;
2253                 cursor = tmpcursor;
2254                 setSelection(bview);
2255                 cutSelection(bview, true, false);
2256         }
2257 }
2258
2259
2260 // Kill to end of line.
2261 void LyXText::deleteLineForward(BufferView * bview)
2262 {
2263         if (cursor.par()->empty())
2264                 // Paragraph is empty, so we just go to the right
2265                 cursorRight(bview);
2266         else {
2267                 LyXCursor tmpcursor = cursor;
2268                 // We can't store the row over a regular setCursor
2269                 // so we set it to 0 and reset it afterwards.
2270                 tmpcursor.row(0); // ??
2271                 selection.set(true); // to avoid deletion
2272                 cursorEnd(bview);
2273                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2274                 selection.cursor = cursor;
2275                 cursor = tmpcursor;
2276                 setSelection(bview);
2277                 // What is this test for ??? (JMarc)
2278                 if (!selection.set()) {
2279                         deleteWordForward(bview);
2280                 } else {
2281                         cutSelection(bview, true, false);
2282                 }
2283         }
2284 }
2285
2286
2287 void LyXText::changeCase(BufferView & bview, LyXText::TextCase action)
2288 {
2289         LyXCursor from;
2290         LyXCursor to;
2291
2292         if (selection.set()) {
2293                 from = selection.start;
2294                 to = selection.end;
2295         } else {
2296                 getWord(from, to, PARTIAL_WORD);
2297                 setCursor(&bview, to.par(), to.pos() + 1);
2298         }
2299
2300         lyx::Assert(from <= to);
2301
2302         setUndo(&bview, Undo::FINISH, from.par(), to.par()->next());
2303
2304         pos_type pos = from.pos();
2305         Paragraph * par = from.par();
2306
2307         while (par && (pos != to.pos() || par != to.par())) {
2308                 if (pos == par->size()) {
2309                         par = par->next();
2310                         pos = 0;
2311                         continue;
2312                 }
2313                 unsigned char c = par->getChar(pos);
2314                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2315                         switch (action) {
2316                         case text_lowercase:
2317                                 c = lowercase(c);
2318                                 break;
2319                         case text_capitalization:
2320                                 c = uppercase(c);
2321                                 action = text_lowercase;
2322                                 break;
2323                         case text_uppercase:
2324                                 c = uppercase(c);
2325                                 break;
2326                         }
2327                 }
2328 #warning changes
2329                 par->setChar(pos, c);
2330                 checkParagraph(&bview, par, pos);
2331
2332                 ++pos;
2333         }
2334         if (to.row() != from.row()) {
2335                 refresh_y = from.y() - from.row()->baseline();
2336                 refresh_row = from.row();
2337                 status(&bview, LyXText::NEED_MORE_REFRESH);
2338         }
2339 }
2340
2341
2342 void LyXText::transposeChars(BufferView & bview)
2343 {
2344         Paragraph * tmppar = cursor.par();
2345
2346         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2347
2348         pos_type tmppos = cursor.pos();
2349
2350         // First decide if it is possible to transpose at all
2351
2352         if (tmppos == 0 || tmppos == tmppar->size())
2353                 return;
2354
2355         if (isDeletedText(*tmppar, tmppos - 1)
2356                 || isDeletedText(*tmppar, tmppos))
2357                 return;
2358
2359         unsigned char c1 = tmppar->getChar(tmppos);
2360         unsigned char c2 = tmppar->getChar(tmppos - 1);
2361
2362         // We should have an implementation that handles insets
2363         // as well, but that will have to come later. (Lgb)
2364         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET)
2365                 return;
2366
2367         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2368         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2369
2370         tmppar->insertChar(ipos, c1);
2371         tmppar->insertChar(ipos + 1, c2);
2372
2373         checkParagraph(&bview, tmppar, tmppos);
2374 }
2375
2376
2377 void LyXText::Delete(BufferView * bview)
2378 {
2379         // this is a very easy implementation
2380
2381         LyXCursor old_cursor = cursor;
2382         int const old_cur_par_id = old_cursor.par()->id();
2383         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2384                 old_cursor.par()->previous()->id() : -1;
2385
2386         // just move to the right
2387         cursorRight(bview);
2388
2389         // CHECK Look at the comment here.
2390         // This check is not very good...
2391         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2392         // and that can very well delete the par or par->previous in
2393         // old_cursor. Will a solution where we compare paragraph id's
2394         //work better?
2395         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2396             == old_cur_par_prev_id
2397             && cursor.par()->id() != old_cur_par_id) {
2398                 // delete-empty-paragraph-mechanism has done it
2399                 return;
2400         }
2401
2402         // if you had success make a backspace
2403         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2404                 LyXCursor tmpcursor = cursor;
2405                 // to make sure undo gets the right cursor position
2406                 cursor = old_cursor;
2407                 setUndo(bview, Undo::DELETE,
2408                         cursor.par(), cursor.par()->next());
2409                 cursor = tmpcursor;
2410                 backspace(bview);
2411         }
2412 }
2413
2414
2415 void LyXText::backspace(BufferView * bview)
2416 {
2417         // Get the font that is used to calculate the baselineskip
2418         pos_type lastpos = cursor.par()->size();
2419         LyXFont rawparfont =
2420                 cursor.par()->getFontSettings(bview->buffer()->params,
2421                                               lastpos - 1);
2422
2423         if (cursor.pos() == 0) {
2424                 // The cursor is at the beginning of a paragraph,
2425                 // so the the backspace will collapse two paragraphs into one.
2426
2427                 // but it's not allowed unless it's new
2428                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2429                         return;
2430
2431                 // we may paste some paragraphs
2432
2433                 // is it an empty paragraph?
2434
2435                 if ((lastpos == 0
2436                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2437                         // This is an empty paragraph and we delete it just by moving the cursor one step
2438                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2439                         // of the paragraph.
2440
2441                         if (cursor.par()->previous()) {
2442                                 Paragraph * tmppar = cursor.par()->previous();
2443                                 if (cursor.par()->layout() == tmppar->layout()
2444                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2445                                         // Inherit bottom DTD from the paragraph below.
2446                                         // (the one we are deleting)
2447                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2448                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2449                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2450                                 }
2451
2452                                 cursorLeft(bview);
2453
2454                                 // the layout things can change the height of a row !
2455                                 int const tmpheight = cursor.row()->height();
2456                                 setHeightOfRow(bview, cursor.row());
2457                                 if (cursor.row()->height() != tmpheight) {
2458                                         refresh_y = cursor.y() - cursor.row()->baseline();
2459                                         refresh_row = cursor.row();
2460                                         status(bview, LyXText::NEED_MORE_REFRESH);
2461                                 }
2462                                 return;
2463                         }
2464                 }
2465
2466                 if (cursor.par()->previous()) {
2467                         setUndo(bview, Undo::DELETE,
2468                                 cursor.par()->previous(), cursor.par()->next());
2469                 }
2470
2471                 Paragraph * tmppar = cursor.par();
2472                 Row * tmprow = cursor.row();
2473
2474                 // We used to do cursorLeftIntern() here, but it is
2475                 // not a good idea since it triggers the auto-delete
2476                 // mechanism. So we do a cursorLeftIntern()-lite,
2477                 // without the dreaded mechanism. (JMarc)
2478                 if (cursor.par()->previous()) {
2479                         // steps into the above paragraph.
2480                         setCursorIntern(bview, cursor.par()->previous(),
2481                                         cursor.par()->previous()->size(),
2482                                         false);
2483                 }
2484
2485                 // Pasting is not allowed, if the paragraphs have different
2486                 // layout. I think it is a real bug of all other
2487                 // word processors to allow it. It confuses the user.
2488                 // Even so with a footnote paragraph and a non-footnote
2489                 // paragraph. I will not allow pasting in this case,
2490                 // because the user would be confused if the footnote behaves
2491                 // different wether it is open or closed.
2492
2493                 //      Correction: Pasting is always allowed with standard-layout
2494                 LyXTextClass const & tclass =
2495                         bview->buffer()->params.getLyXTextClass();
2496
2497                 if (cursor.par() != tmppar
2498                     && (cursor.par()->layout() == tmppar->layout()
2499                         || tmppar->layout() == tclass.defaultLayout())
2500                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2501                         removeParagraph(tmprow);
2502                         removeRow(tmprow);
2503                         mergeParagraph(bview->buffer()->params, bview->buffer()->paragraphs, cursor.par());
2504
2505                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2506                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2507                         // strangely enough it seems that commenting out the line above removes
2508                         // most or all of the segfaults. I will however also try to move the
2509                         // two Remove... lines in front of the PasteParagraph too.
2510                         else
2511                                 if (cursor.pos())
2512                                         cursor.pos(cursor.pos() - 1);
2513
2514                         status(bview, LyXText::NEED_MORE_REFRESH);
2515                         refresh_row = cursor.row();
2516                         refresh_y = cursor.y() - cursor.row()->baseline();
2517
2518                         // remove the lost paragraph
2519                         // This one is not safe, since the paragraph that the tmprow and the
2520                         // following rows belong to has been deleted by the PasteParagraph
2521                         // above. The question is... could this be moved in front of the
2522                         // PasteParagraph?
2523                         //RemoveParagraph(tmprow);
2524                         //RemoveRow(tmprow);
2525
2526                         // This rebuilds the rows.
2527                         appendParagraph(bview, cursor.row());
2528                         updateCounters(bview);
2529
2530                         // the row may have changed, block, hfills etc.
2531                         setCursor(bview, cursor.par(), cursor.pos(), false);
2532                 }
2533         } else {
2534                 // this is the code for a normal backspace, not pasting
2535                 // any paragraphs
2536                 setUndo(bview, Undo::DELETE,
2537                         cursor.par(), cursor.par()->next());
2538                 // We used to do cursorLeftIntern() here, but it is
2539                 // not a good idea since it triggers the auto-delete
2540                 // mechanism. So we do a cursorLeftIntern()-lite,
2541                 // without the dreaded mechanism. (JMarc)
2542                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2543                                 false, cursor.boundary());
2544
2545                 if (cursor.par()->isInset(cursor.pos())) {
2546                         // force complete redo when erasing display insets
2547                         // this is a cruel method but safe..... Matthias
2548                         if (cursor.par()->getInset(cursor.pos())->display() ||
2549                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2550                                 cursor.par()->erase(cursor.pos());
2551                                 redoParagraph(bview);
2552                                 return;
2553                         }
2554                 }
2555
2556                 Row * row = cursor.row();
2557                 int y = cursor.y() - row->baseline();
2558                 pos_type z;
2559                 // remember that a space at the end of a row doesnt count
2560                 // when calculating the fill
2561                 if (cursor.pos() < row->lastPos() ||
2562                     !cursor.par()->isLineSeparator(cursor.pos())) {
2563                         row->fill(row->fill() + singleWidth(bview,
2564                                                             cursor.par(),
2565                                                             cursor.pos()));
2566                 }
2567
2568                 // some special code when deleting a newline. This is similar
2569                 // to the behavior when pasting paragraphs
2570                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2571                         cursor.par()->erase(cursor.pos());
2572                         // refresh the positions
2573                         Row * tmprow = row;
2574                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2575                                 tmprow = tmprow->next();
2576                                 tmprow->pos(tmprow->pos() - 1);
2577                         }
2578                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2579                                 cursor.pos(cursor.pos() - 1);
2580
2581                         if (cursor.pos() < cursor.par()->size()
2582                             && !cursor.par()->isSeparator(cursor.pos())) {
2583                                 cursor.par()->insertChar(cursor.pos(), ' ');
2584                                 setCharFont(bview->buffer(), cursor.par(),
2585                                             cursor.pos(), current_font);
2586                                 // refresh the positions
2587                                 tmprow = row;
2588                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2589                                         tmprow = tmprow->next();
2590                                         tmprow->pos(tmprow->pos() + 1);
2591                                 }
2592                         }
2593                 } else {
2594                         cursor.par()->erase(cursor.pos());
2595
2596                         // refresh the positions
2597                         Row * tmprow = row;
2598                         while (tmprow->next()
2599                                && tmprow->next()->par() == row->par()) {
2600                                 tmprow = tmprow->next();
2601                                 tmprow->pos(tmprow->pos() - 1);
2602                         }
2603
2604                         // delete newlines at the beginning of paragraphs
2605                         while (!cursor.par()->empty() &&
2606                                cursor.par()->isNewline(cursor.pos()) &&
2607                                cursor.pos() == cursor.par()->beginningOfBody()) {
2608                                 cursor.par()->erase(cursor.pos());
2609                                 // refresh the positions
2610                                 tmprow = row;
2611                                 while (tmprow->next() &&
2612                                        tmprow->next()->par() == row->par()) {
2613                                         tmprow = tmprow->next();
2614                                         tmprow->pos(tmprow->pos() - 1);
2615                                 }
2616                         }
2617                 }
2618
2619                 // is there a break one row above
2620                 if (row->previous() && row->previous()->par() == row->par()) {
2621                         z = rowBreakPoint(*bview, *row->previous());
2622                         if (z >= row->pos()) {
2623                                 row->pos(z + 1);
2624
2625                                 Row * tmprow = row->previous();
2626
2627                                 // maybe the current row is now empty
2628                                 if (row->pos() >= row->par()->size()) {
2629                                         // remove it
2630                                         removeRow(row);
2631                                         need_break_row = 0;
2632                                 } else {
2633                                         breakAgainOneRow(bview, row);
2634                                         if (row->next() && row->next()->par() == row->par())
2635                                                 need_break_row = row->next();
2636                                         else
2637                                                 need_break_row = 0;
2638                                 }
2639
2640                                 // set the dimensions of the row above
2641                                 y -= tmprow->height();
2642                                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
2643                                 setHeightOfRow(bview, tmprow);
2644
2645                                 refresh_y = y;
2646                                 refresh_row = tmprow;
2647                                 status(bview, LyXText::NEED_MORE_REFRESH);
2648                                 setCursor(bview, cursor.par(), cursor.pos(),
2649                                           false, cursor.boundary());
2650                                 //current_font = rawtmpfont;
2651                                 //real_current_font = realtmpfont;
2652                                 // check, whether the last character's font has changed.
2653                                 if (rawparfont !=
2654                                     cursor.par()->getFontSettings(bview->buffer()->params,
2655                                                                   cursor.par()->size() - 1))
2656                                         redoHeightOfParagraph(bview, cursor);
2657                                 return;
2658                         }
2659                 }
2660
2661                 // break the cursor row again
2662                 if (row->next() && row->next()->par() == row->par() &&
2663                     (row->lastPos() == row->par()->size() - 1 ||
2664                      rowBreakPoint(*bview, *row) != row->lastPos())) {
2665
2666                         // it can happen that a paragraph loses one row
2667                         // without a real breakup. This is when a word
2668                         // is to long to be broken. Well, I don t care this
2669                         // hack ;-)
2670                         if (row->lastPos() == row->par()->size() - 1)
2671                                 removeRow(row->next());
2672
2673                         refresh_y = y;
2674                         refresh_row = row;
2675                         status(bview, LyXText::NEED_MORE_REFRESH);
2676
2677                         breakAgainOneRow(bview, row);
2678                         // will the cursor be in another row now?
2679                         if (row->next() && row->next()->par() == row->par() &&
2680                             row->lastPos() <= cursor.pos()) {
2681                                 row = row->next();
2682                                 breakAgainOneRow(bview, row);
2683                         }
2684
2685                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2686
2687                         if (row->next() && row->next()->par() == row->par())
2688                                 need_break_row = row->next();
2689                         else
2690                                 need_break_row = 0;
2691                 } else  {
2692                         // set the dimensions of the row
2693                         row->fill(fill(*bview, *row, workWidth(*bview)));
2694                         int const tmpheight = row->height();
2695                         setHeightOfRow(bview, row);
2696                         if (tmpheight == row->height())
2697                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2698                         else
2699                                 status(bview, LyXText::NEED_MORE_REFRESH);
2700                         refresh_y = y;
2701                         refresh_row = row;
2702                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2703                 }
2704         }
2705
2706         // current_font = rawtmpfont;
2707         // real_current_font = realtmpfont;
2708
2709         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2710             != cursor.boundary())
2711                 setCursor(bview, cursor.par(), cursor.pos(), false,
2712                           !cursor.boundary());
2713
2714         lastpos = cursor.par()->size();
2715         if (cursor.pos() == lastpos)
2716                 setCurrentFont(bview);
2717
2718         // check, whether the last characters font has changed.
2719         if (rawparfont !=
2720             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2721                 redoHeightOfParagraph(bview, cursor);
2722         } else {
2723                 // now the special right address boxes
2724                 if (cursor.par()->layout()->margintype
2725                     == MARGIN_RIGHT_ADDRESS_BOX) {
2726                         redoDrawingOfParagraph(bview, cursor);
2727                 }
2728         }
2729 }
2730
2731
2732 // returns the column near the specified x-coordinate of the row
2733 // x is set to the real beginning of this column
2734 pos_type
2735 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
2736                         bool & boundary) const
2737 {
2738         float tmpx = 0.0;
2739         float fill_separator;
2740         float fill_hfill;
2741         float fill_label_hfill;
2742
2743         prepareToPrint(bview, row, tmpx, fill_separator,
2744                        fill_hfill, fill_label_hfill);
2745
2746         pos_type vc = row->pos();
2747         pos_type last = row->lastPrintablePos();
2748         pos_type c = 0;
2749
2750         LyXLayout_ptr const & layout = row->par()->layout();
2751
2752         bool left_side = false;
2753
2754         pos_type body_pos = row->par()->beginningOfBody();
2755         float last_tmpx = tmpx;
2756
2757         if (body_pos > 0 &&
2758             (body_pos - 1 > last ||
2759              !row->par()->isLineSeparator(body_pos - 1)))
2760                 body_pos = 0;
2761
2762         // check for empty row
2763         if (!row->par()->size()) {
2764                 x = int(tmpx);
2765                 return 0;
2766         }
2767
2768         while (vc <= last && tmpx <= x) {
2769                 c = vis2log(vc);
2770                 last_tmpx = tmpx;
2771                 if (body_pos > 0 && c == body_pos-1) {
2772                         tmpx += fill_label_hfill +
2773                                 font_metrics::width(layout->labelsep,
2774                                                getLabelFont(bview->buffer(), row->par()));
2775                         if (row->par()->isLineSeparator(body_pos - 1))
2776                                 tmpx -= singleWidth(bview, row->par(), body_pos-1);
2777                 }
2778
2779                 if (row->hfillExpansion(c)) {
2780                         tmpx += singleWidth(bview, row->par(), c);
2781                         if (c >= body_pos)
2782                                 tmpx += fill_hfill;
2783                         else
2784                                 tmpx += fill_label_hfill;
2785                 } else if (row->par()->isSeparator(c)) {
2786                         tmpx += singleWidth(bview, row->par(), c);
2787                         if (c >= body_pos)
2788                                 tmpx+= fill_separator;
2789                 } else {
2790                         tmpx += singleWidth(bview, row->par(), c);
2791                 }
2792                 ++vc;
2793         }
2794
2795         if ((tmpx + last_tmpx) / 2 > x) {
2796                 tmpx = last_tmpx;
2797                 left_side = true;
2798         }
2799
2800         if (vc > last + 1)  // This shouldn't happen.
2801                 vc = last + 1;
2802
2803         boundary = false;
2804         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
2805                                          // some speedup if rtl_support=false
2806                 && (!row->next() || row->next()->par() != row->par());
2807         bool const rtl = (lastrow)
2808                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
2809                 : false; // If lastrow is false, we don't need to compute
2810                          // the value of rtl.
2811
2812         if (lastrow &&
2813                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
2814                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
2815                 c = last + 1;
2816         else if (vc == row->pos()) {
2817                 c = vis2log(vc);
2818                 if (bidi_level(c) % 2 == 1)
2819                         ++c;
2820         } else {
2821                 c = vis2log(vc - 1);
2822                 bool const rtl = (bidi_level(c) % 2 == 1);
2823                 if (left_side == rtl) {
2824                         ++c;
2825                         boundary = isBoundary(bview->buffer(), row->par(), c);
2826                 }
2827         }
2828
2829         if (row->pos() <= last && c > last
2830             && row->par()->isNewline(last)) {
2831                 if (bidi_level(last) % 2 == 0)
2832                         tmpx -= singleWidth(bview, row->par(), last);
2833                 else
2834                         tmpx += singleWidth(bview, row->par(), last);
2835                 c = last;
2836         }
2837
2838         c -= row->pos();
2839         x = int(tmpx);
2840         return c;
2841 }
2842
2843
2844 // returns pointer to a specified row
2845 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
2846 {
2847         if (!firstrow)
2848                 return 0;
2849
2850         Row * tmprow = firstrow;
2851         y = 0;
2852
2853         // find the first row of the specified paragraph
2854         while (tmprow->next() && tmprow->par() != par) {
2855                 y += tmprow->height();
2856                 tmprow = tmprow->next();
2857         }
2858
2859         // now find the wanted row
2860         while (tmprow->pos() < pos
2861                && tmprow->next()
2862                && tmprow->next()->par() == par
2863                && tmprow->next()->pos() <= pos) {
2864                 y += tmprow->height();
2865                 tmprow = tmprow->next();
2866         }
2867
2868         return tmprow;
2869 }
2870
2871
2872 Row * LyXText::getRowNearY(int & y) const
2873 {
2874 #if 1
2875         // If possible we should optimize this method. (Lgb)
2876         Row * tmprow = firstrow;
2877         int tmpy = 0;
2878
2879         while (tmprow->next() && tmpy + tmprow->height() <= y) {
2880                 tmpy += tmprow->height();
2881                 tmprow = tmprow->next();
2882         }
2883
2884         y = tmpy;   // return the real y
2885
2886         //lyxerr << "returned y = " << y << endl;
2887
2888         return tmprow;
2889 #else
2890         // Search from the current cursor position.
2891
2892         Row * tmprow = cursor.row();
2893         int tmpy = cursor.y() - tmprow->baseline();
2894
2895         lyxerr << "cursor.y() = " << tmpy << endl;
2896         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
2897         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
2898         lyxerr << "first = " << first << endl;
2899         lyxerr << "y = " << y << endl;
2900
2901         if (y < tmpy) {
2902                 lyxerr << "up" << endl;
2903                 do {
2904                         tmpy -= tmprow->height();
2905                         tmprow = tmprow->previous();
2906                 } while (tmprow && tmpy - tmprow->height() >= y);
2907         } else if (y > tmpy) {
2908                 lyxerr << "down" << endl;
2909
2910                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
2911                         tmpy += tmprow->height();
2912                         tmprow = tmprow->next();
2913                 }
2914         } else {
2915                 lyxerr << "equal" << endl;
2916         }
2917
2918         y = tmpy; // return the real y
2919
2920         lyxerr << "returned y = " << y << endl;
2921
2922         return tmprow;
2923
2924 #endif
2925 }
2926
2927
2928 int LyXText::getDepth() const
2929 {
2930         return cursor.par()->getDepth();
2931 }