]> git.lyx.org Git - lyx.git/blob - src/text.C
Fix bug 365, and nextBreakPoint cleanup
[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 x = leftMargin(&bv, &row);
731
732         for (i = pos; i < last; ++i) {
733
734                 char const c = par->getChar(i);
735
736                 if (IsNewlineChar(c)) {
737                         point = i;
738                         break;
739                 }
740
741                 x += singleWidth(&bv, par, i, c);
742
743                 // add the auto-hfill from label end to the body
744                 if (i == body_pos) {
745                         x += font_metrics::width(layout->labelsep,
746                                     getLabelFont(bv.buffer(), par));
747                         if (par->isLineSeparator(i - 1))
748                                 x-= singleWidth(&bv, par, i - 1);
749                         int left_margin = labelEnd(bv, row);
750                         if (x < left_margin)
751                                 x = left_margin;
752                 }
753
754                 // break before a character that will fall off
755                 // the right of the row
756                 if (x >= width) {
757                         // if no break before, break here.
758                         if (point == last) {
759                                 if (pos < i)
760                                         point = i - 1;
761                                 else
762                                         point = i;
763                         }
764                         break;
765                 }
766
767                 Inset * in = par->isInset(i) ? par->getInset(i) : 0;
768
769                 if (!in || in->isChar()) {
770                         // some insets are line separators too
771                         if (par->isLineSeparator(i))
772                                 point = i;
773                         continue;
774
775                 }
776
777                 // check wether a Display() inset is valid here.
778                 // If not, change it to non-display. FIXME:
779                 // we should not be modifying things at this
780                 // point !
781                 if (in->display() && (layout->isCommand() ||
782                     (layout->labeltype == LABEL_MANUAL && i < body_pos))) {
783                         in->display(false);
784                 } else if (in->display() || in->needFullRow()) {
785                         // displayed insets start at a new row
786                         if (i == pos) {
787                                 if (pos < last - 1) {
788                                         point = i;
789                                         if (par->isLineSeparator(i + 1))
790                                                 ++point;
791                                 } else {
792                                         // to avoid extra rows
793                                         point = last;
794                                 }
795                         } else {
796                                 point = i - 1;
797                         }
798                         break;
799                 }
800         }
801
802         // didn't find one, break at the point we reached the edge
803         if (point == last && x >= width)
804                 point = i;
805
806         // manual labels cannot be broken in LaTeX
807         if (body_pos && point < body_pos)
808                 point = body_pos - 1;
809
810         return point;
811 }
812
813
814 // returns the minimum space a row needs on the screen in pixel
815 int LyXText::fill(BufferView & bview, Row & row, int paper_width) const
816 {
817         if (paper_width < 0)
818                 return 0;
819
820         int w;
821         // get the pure distance
822         pos_type const last = row.lastPrintablePos();
823
824         // special handling of the right address boxes
825         if (row.par()->layout()->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
826                 int const tmpfill = row.fill();
827                 row.fill(0); // the minfill in MarginLeft()
828                 w = leftMargin(&bview, &row);
829                 row.fill(tmpfill);
830         } else
831                 w = leftMargin(&bview, &row);
832
833         Paragraph * par = row.par();
834         LyXLayout_ptr const & layout = par->layout();
835
836         pos_type const body_pos = par->beginningOfBody();
837         pos_type i = row.pos();
838
839         while (i <= last) {
840                 if (body_pos > 0 && i == body_pos) {
841                         w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
842                         if (par->isLineSeparator(i - 1))
843                                 w -= singleWidth(&bview, par, i - 1);
844                         int left_margin = labelEnd(bview, row);
845                         if (w < left_margin)
846                                 w = left_margin;
847                 }
848                 w += singleWidth(&bview, par, i);
849                 ++i;
850         }
851         if (body_pos > 0 && body_pos > last) {
852                 w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
853                 if (last >= 0 && par->isLineSeparator(last))
854                         w -= singleWidth(&bview, par, last);
855                 int const left_margin = labelEnd(bview, row);
856                 if (w < left_margin)
857                         w = left_margin;
858         }
859
860         int const fill = paper_width - w - rightMargin(*bview.buffer(), row);
861         return fill;
862 }
863
864
865 // returns the minimum space a manual label needs on the screen in pixel
866 int LyXText::labelFill(BufferView & bview, Row const & row) const
867 {
868         pos_type last = row.par()->beginningOfBody();
869
870         lyx::Assert(last > 0);
871
872         // -1 because a label ends either with a space that is in the label,
873         // or with the beginning of a footnote that is outside the label.
874         --last;
875
876         // a separator at this end does not count
877         if (row.par()->isLineSeparator(last))
878                 --last;
879
880         int w = 0;
881         pos_type i = row.pos();
882         while (i <= last) {
883                 w += singleWidth(&bview, row.par(), i);
884                 ++i;
885         }
886
887         int fill = 0;
888         string const & labwidstr = row.par()->params().labelWidthString();
889         if (!labwidstr.empty()) {
890                 LyXFont const labfont = getLabelFont(bview.buffer(), row.par());
891                 int const labwidth = font_metrics::width(labwidstr, labfont);
892                 fill = max(labwidth - w, 0);
893         }
894
895         return fill;
896 }
897
898
899 LColor::color LyXText::backgroundColor() const
900 {
901         if (inset_owner)
902                 return inset_owner->backgroundColor();
903         else
904                 return LColor::background;
905 }
906
907 void LyXText::setHeightOfRow(BufferView * bview, Row * row) const
908 {
909         // get the maximum ascent and the maximum descent
910         int asc = 0;
911         int desc = 0;
912         float layoutasc = 0;
913         float layoutdesc = 0;
914         float tmptop = 0;
915         LyXFont tmpfont;
916         Inset * tmpinset = 0;
917
918         // ok , let us initialize the maxasc and maxdesc value.
919         // This depends in LaTeX of the font of the last character
920         // in the paragraph. The hack below is necessary because
921         // of the possibility of open footnotes
922
923         // Correction: only the fontsize count. The other properties
924         //  are taken from the layoutfont. Nicer on the screen :)
925         Paragraph * par = row->par();
926         Paragraph * firstpar = row->par();
927
928         LyXLayout_ptr const & layout = firstpar->layout();
929
930         // as max get the first character of this row then it can increase but not
931         // decrease the height. Just some point to start with so we don't have to
932         // do the assignment below too often.
933         LyXFont font = getFont(bview->buffer(), par, row->pos());
934         LyXFont::FONT_SIZE const tmpsize = font.size();
935         font = getLayoutFont(bview->buffer(), par);
936         LyXFont::FONT_SIZE const size = font.size();
937         font.setSize(tmpsize);
938
939         LyXFont labelfont = getLabelFont(bview->buffer(), par);
940
941         float spacing_val = 1.0;
942         if (!row->par()->params().spacing().isDefault()) {
943                 spacing_val = row->par()->params().spacing().getValue();
944         } else {
945                 spacing_val = bview->buffer()->params.spacing.getValue();
946         }
947         //lyxerr << "spacing_val = " << spacing_val << endl;
948
949         int maxasc = int(font_metrics::maxAscent(font) *
950                          layout->spacing.getValue() *
951                          spacing_val);
952         int maxdesc = int(font_metrics::maxDescent(font) *
953                           layout->spacing.getValue() *
954                           spacing_val);
955
956         pos_type const pos_end = row->lastPos();
957         int labeladdon = 0;
958         int maxwidth = 0;
959
960         // Check if any insets are larger
961         for (pos_type pos = row->pos(); pos <= pos_end; ++pos) {
962                 if (row->par()->isInset(pos)) {
963                         tmpfont = getFont(bview->buffer(), row->par(), pos);
964                         tmpinset = row->par()->getInset(pos);
965                         if (tmpinset) {
966 #if 1 // this is needed for deep update on initialitation
967                                 tmpinset->update(bview, tmpfont);
968 #endif
969                                 asc = tmpinset->ascent(bview, tmpfont);
970                                 desc = tmpinset->descent(bview, tmpfont);
971                                 maxwidth += tmpinset->width(bview, tmpfont);
972                                 maxasc = max(maxasc, asc);
973                                 maxdesc = max(maxdesc, desc);
974                         }
975                 } else {
976                         maxwidth += singleWidth(bview, row->par(), pos);
977                 }
978         }
979
980         // Check if any custom fonts are larger (Asger)
981         // This is not completely correct, but we can live with the small,
982         // cosmetic error for now.
983         LyXFont::FONT_SIZE maxsize =
984                 row->par()->highestFontInRange(row->pos(), pos_end, size);
985         if (maxsize > font.size()) {
986                 font.setSize(maxsize);
987
988                 asc = font_metrics::maxAscent(font);
989                 desc = font_metrics::maxDescent(font);
990                 if (asc > maxasc)
991                         maxasc = asc;
992                 if (desc > maxdesc)
993                         maxdesc = desc;
994         }
995
996         // This is nicer with box insets:
997         ++maxasc;
998         ++maxdesc;
999
1000         row->ascent_of_text(maxasc);
1001
1002         // is it a top line?
1003         if (!row->pos() && (row->par() == firstpar)) {
1004
1005                 // some parksips VERY EASY IMPLEMENTATION
1006                 if (bview->buffer()->params.paragraph_separation ==
1007                         BufferParams::PARSEP_SKIP)
1008                 {
1009                         if (layout->isParagraph()
1010                                 && firstpar->getDepth() == 0
1011                                 && firstpar->previous())
1012                         {
1013                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
1014                         } else if (firstpar->previous() &&
1015                                    firstpar->previous()->layout()->isParagraph() &&
1016                                    firstpar->previous()->getDepth() == 0)
1017                         {
1018                                 // is it right to use defskip here too? (AS)
1019                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
1020                         }
1021                 }
1022
1023                 // the top margin
1024                 if (!row->par()->previous() && isTopLevel())
1025                         maxasc += PAPER_MARGIN;
1026
1027                 // add the vertical spaces, that the user added
1028                 maxasc += getLengthMarkerHeight(*bview, firstpar->params().spaceTop());
1029
1030                 // do not forget the DTP-lines!
1031                 // there height depends on the font of the nearest character
1032                 if (firstpar->params().lineTop())
1033
1034                         maxasc += 2 * font_metrics::ascent('x', getFont(bview->buffer(),
1035                                         firstpar, 0));
1036                 // and now the pagebreaks
1037                 if (firstpar->params().pagebreakTop())
1038                         maxasc += 3 * defaultRowHeight();
1039
1040                 // This is special code for the chapter, since the label of this
1041                 // layout is printed in an extra row
1042                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1043                         && bview->buffer()->params.secnumdepth >= 0)
1044                 {
1045                         float spacing_val = 1.0;
1046                         if (!row->par()->params().spacing().isDefault()) {
1047                                 spacing_val = row->par()->params().spacing().getValue();
1048                         } else {
1049                                 spacing_val = bview->buffer()->params.spacing.getValue();
1050                         }
1051
1052                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1053                                          layout->spacing.getValue() *
1054                                          spacing_val)
1055                                 + int(font_metrics::maxAscent(labelfont) *
1056                                       layout->spacing.getValue() *
1057                                       spacing_val);
1058                 }
1059
1060                 // special code for the top label
1061                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1062                      || layout->labeltype == LABEL_BIBLIO
1063                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1064                     && row->par()->isFirstInSequence()
1065                     && !row->par()->getLabelstring().empty())
1066                 {
1067                         float spacing_val = 1.0;
1068                         if (!row->par()->params().spacing().isDefault()) {
1069                                 spacing_val = row->par()->params().spacing().getValue();
1070                         } else {
1071                                 spacing_val = bview->buffer()->params.spacing.getValue();
1072                         }
1073
1074                         labeladdon = int(
1075                                 (font_metrics::maxAscent(labelfont) *
1076                                  layout->spacing.getValue() *
1077                                  spacing_val)
1078                                 +(font_metrics::maxDescent(labelfont) *
1079                                   layout->spacing.getValue() *
1080                                   spacing_val)
1081                                 + layout->topsep * defaultRowHeight()
1082                                 + layout->labelbottomsep * defaultRowHeight());
1083                 }
1084
1085                 // and now the layout spaces, for example before and after a section,
1086                 // or between the items of a itemize or enumerate environment
1087
1088                 if (!firstpar->params().pagebreakTop()) {
1089                         Paragraph * prev = row->par()->previous();
1090                         if (prev)
1091                                 prev = row->par()->depthHook(row->par()->getDepth());
1092                         if (prev && prev->layout() == firstpar->layout() &&
1093                                 prev->getDepth() == firstpar->getDepth() &&
1094                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1095                         {
1096                                 layoutasc = (layout->itemsep * defaultRowHeight());
1097                         } else if (row->previous()) {
1098                                 tmptop = layout->topsep;
1099
1100                                 if (row->previous()->par()->getDepth() >= row->par()->getDepth())
1101                                         tmptop -= row->previous()->par()->layout()->bottomsep;
1102
1103                                 if (tmptop > 0)
1104                                         layoutasc = (tmptop * defaultRowHeight());
1105                         } else if (row->par()->params().lineTop()) {
1106                                 tmptop = layout->topsep;
1107
1108                                 if (tmptop > 0)
1109                                         layoutasc = (tmptop * defaultRowHeight());
1110                         }
1111
1112                         prev = row->par()->outerHook();
1113                         if (prev)  {
1114                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1115                         } else {
1116                                 if (firstpar->previous() &&
1117                                         firstpar->previous()->getDepth() == 0 &&
1118                                         firstpar->previous()->layout() !=
1119                                         firstpar->layout())
1120                                 {
1121                                         // avoid parsep
1122                                 } else if (firstpar->previous()) {
1123                                         maxasc += int(layout->parsep * defaultRowHeight());
1124                                 }
1125                         }
1126                 }
1127         }
1128
1129         // is it a bottom line?
1130         if (row->par() == par
1131                 && (!row->next() || row->next()->par() != row->par())) {
1132                 // the bottom margin
1133                 if (!par->next() && isTopLevel())
1134                         maxdesc += PAPER_MARGIN;
1135
1136                 // add the vertical spaces, that the user added
1137                 maxdesc += getLengthMarkerHeight(*bview, firstpar->params().spaceBottom());
1138
1139                 // do not forget the DTP-lines!
1140                 // there height depends on the font of the nearest character
1141                 if (firstpar->params().lineBottom())
1142                         maxdesc += 2 * font_metrics::ascent('x',
1143                                                        getFont(bview->buffer(),
1144                                                                par,
1145                                                                max(pos_type(0), par->size() - 1)));
1146
1147                 // and now the pagebreaks
1148                 if (firstpar->params().pagebreakBottom())
1149                         maxdesc += 3 * defaultRowHeight();
1150
1151                 // and now the layout spaces, for example before and after
1152                 // a section, or between the items of a itemize or enumerate
1153                 // environment
1154                 if (!firstpar->params().pagebreakBottom()
1155                     && row->par()->next()) {
1156                         Paragraph * nextpar = row->par()->next();
1157                         Paragraph * comparepar = row->par();
1158                         float usual = 0;
1159                         float unusual = 0;
1160
1161                         if (comparepar->getDepth() > nextpar->getDepth()) {
1162                                 usual = (comparepar->layout()->bottomsep * defaultRowHeight());
1163                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1164                                 if (comparepar->layout()!= nextpar->layout()
1165                                         || nextpar->getLabelWidthString() !=
1166                                         comparepar->getLabelWidthString())
1167                                 {
1168                                         unusual = (comparepar->layout()->bottomsep * defaultRowHeight());
1169                                 }
1170                                 if (unusual > usual)
1171                                         layoutdesc = unusual;
1172                                 else
1173                                         layoutdesc = usual;
1174                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1175
1176                                 if (comparepar->layout() != nextpar->layout()
1177                                         || nextpar->getLabelWidthString() !=
1178                                         comparepar->getLabelWidthString())
1179                                         layoutdesc = int(comparepar->layout()->bottomsep * defaultRowHeight());
1180                         }
1181                 }
1182         }
1183
1184         // incalculate the layout spaces
1185         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1186         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1187
1188         // calculate the new height of the text
1189         height -= row->height();
1190
1191         row->height(maxasc + maxdesc + labeladdon);
1192         row->baseline(maxasc + labeladdon);
1193
1194         height += row->height();
1195
1196         row->top_of_text(row->baseline() - font_metrics::maxAscent(font));
1197
1198         float x = 0;
1199         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1200                 float dummy;
1201                 // this IS needed
1202                 row->width(maxwidth);
1203                 prepareToPrint(bview, row, x, dummy, dummy, dummy, false);
1204         }
1205         row->width(int(maxwidth + x));
1206         if (inset_owner) {
1207                 Row * r = firstrow;
1208                 width = max(0, workWidth(*bview));
1209                 while (r) {
1210                         if (r->width() > width)
1211                                 width = r->width();
1212                         r = r->next();
1213                 }
1214         }
1215 }
1216
1217
1218 // Appends the implicit specified paragraph before the specified row,
1219 // start at the implicit given position
1220 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1221 {
1222         pos_type const last = row->par()->size();
1223         bool done = false;
1224
1225         do {
1226                 pos_type z = rowBreakPoint(*bview, *row);
1227
1228                 Row * tmprow = row;
1229
1230                 if (z < last) {
1231                         ++z;
1232                         insertRow(row, row->par(), z);
1233                         row = row->next();
1234                         row->height(0);
1235                 } else {
1236                         done = true;
1237                 }
1238
1239                 // Set the dimensions of the row
1240                 // fixed fill setting now by calling inset->update() in
1241                 // SingleWidth when needed!
1242                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1243                 setHeightOfRow(bview, tmprow);
1244
1245         } while (!done);
1246 }
1247
1248
1249 // Do we even need this at all ? Code that uses  RowPainter *already*
1250 // sets need_break_row when it sees a CHANGED_IN_DRAW, though not
1251 // quite like this
1252 void LyXText::markChangeInDraw(BufferView * bv, Row * row, Row * prev)
1253 {
1254         if (prev && prev->par() == row->par()) {
1255                 breakAgainOneRow(bv, prev);
1256                 if (prev->next() != row) {
1257                         // breakAgainOneRow() has removed row_
1258                         need_break_row = prev;
1259                 } else {
1260                         need_break_row = row;
1261                 }
1262         } else if (!prev) {
1263                 need_break_row = firstrow;
1264         } else {
1265                 need_break_row = prev->next();
1266         }
1267         setCursor(bv, cursor.par(), cursor.pos());
1268         /* FIXME */
1269 }
1270
1271
1272 void LyXText::breakAgain(BufferView * bview, Row * row) const
1273 {
1274         bool not_ready = true;
1275
1276         do  {
1277                 pos_type z = rowBreakPoint(*bview, *row);
1278                 Row * tmprow = row;
1279
1280                 if (z < row->par()->size()) {
1281                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1282                                 // insert a new row
1283                                 ++z;
1284                                 insertRow(row, row->par(), z);
1285                                 row = row->next();
1286                                 row->height(0);
1287                         } else  {
1288                                 row = row->next();
1289                                 ++z;
1290                                 if (row->pos() == z)
1291                                         not_ready = false;     // the rest will not change
1292                                 else {
1293                                         row->pos(z);
1294                                 }
1295                         }
1296                 } else {
1297                         // if there are some rows too much, delete them
1298                         // only if you broke the whole paragraph!
1299                         Row * tmprow2 = row;
1300                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1301                                 tmprow2 = tmprow2->next();
1302                         }
1303                         while (tmprow2 != row) {
1304                                 tmprow2 = tmprow2->previous();
1305                                 removeRow(tmprow2->next());
1306                         }
1307                         not_ready = false;
1308                 }
1309
1310                 // set the dimensions of the row
1311                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1312                 setHeightOfRow(bview, tmprow);
1313         } while (not_ready);
1314 }
1315
1316
1317 // this is just a little changed version of break again
1318 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1319 {
1320         pos_type z = rowBreakPoint(*bview, *row);
1321         Row * tmprow = row;
1322
1323         if (z < row->par()->size()) {
1324                 if (!row->next()
1325                     || (row->next() && row->next()->par() != row->par())) {
1326                         // insert a new row
1327                         ++z;
1328                         insertRow(row, row->par(), z);
1329                         row = row->next();
1330                         row->height(0);
1331                 } else  {
1332                         row = row->next();
1333                         ++z;
1334                         if (row->pos() != z)
1335                                 row->pos(z);
1336                 }
1337         } else {
1338                 // if there are some rows too much, delete them
1339                 // only if you broke the whole paragraph!
1340                 Row * tmprow2 = row;
1341                 while (tmprow2->next()
1342                        && tmprow2->next()->par() == row->par()) {
1343                         tmprow2 = tmprow2->next();
1344                 }
1345                 while (tmprow2 != row) {
1346                         tmprow2 = tmprow2->previous();
1347                         removeRow(tmprow2->next());
1348                 }
1349         }
1350
1351         // set the dimensions of the row
1352         tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1353         setHeightOfRow(bview, tmprow);
1354 }
1355
1356
1357 void LyXText::breakParagraph(BufferView * bview,
1358                              ParagraphList & paragraphs, char keep_layout)
1359 {
1360         // allow only if at start or end, or all previous is new text
1361         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1362                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1363                 return;
1364
1365         LyXTextClass const & tclass =
1366                 bview->buffer()->params.getLyXTextClass();
1367         LyXLayout_ptr const & layout = cursor.par()->layout();
1368
1369         // this is only allowed, if the current paragraph is not empty or caption
1370         // and if it has not the keepempty flag aktive
1371         if (cursor.par()->empty()
1372            && layout->labeltype != LABEL_SENSITIVE
1373            && !layout->keepempty)
1374                 return;
1375
1376         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1377
1378         // Always break behind a space
1379         //
1380         // It is better to erase the space (Dekel)
1381         if (cursor.pos() < cursor.par()->size()
1382              && cursor.par()->isLineSeparator(cursor.pos()))
1383            cursor.par()->erase(cursor.pos());
1384         // cursor.pos(cursor.pos() + 1);
1385
1386         // break the paragraph
1387         if (keep_layout)
1388                 keep_layout = 2;
1389         else
1390                 keep_layout = layout->isEnvironment();
1391
1392         // we need to set this before we insert the paragraph. IMO the
1393         // breakParagraph call should return a bool if it inserts the
1394         // paragraph before or behind and we should react on that one
1395         // but we can fix this in 1.3.0 (Jug 20020509)
1396         bool const isempty = (layout->keepempty && cursor.par()->empty());
1397         ::breakParagraph(bview->buffer()->params, paragraphs, cursor.par(), cursor.pos(),
1398                        keep_layout);
1399
1400         // well this is the caption hack since one caption is really enough
1401         if (layout->labeltype == LABEL_SENSITIVE) {
1402                 if (!cursor.pos())
1403                         // set to standard-layout
1404                         cursor.par()->applyLayout(tclass.defaultLayout());
1405                 else
1406                         // set to standard-layout
1407                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1408         }
1409
1410         // if the cursor is at the beginning of a row without prior newline,
1411         // move one row up!
1412         // This touches only the screen-update. Otherwise we would may have
1413         // an empty row on the screen
1414         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1415                          && cursor.row()->pos() == cursor.pos())
1416         {
1417                 cursorLeft(bview);
1418         }
1419
1420         status(bview, LyXText::NEED_MORE_REFRESH);
1421         refresh_row = cursor.row();
1422         refresh_y = cursor.y() - cursor.row()->baseline();
1423
1424         // Do not forget the special right address boxes
1425         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1426                 while (refresh_row->previous() &&
1427                        refresh_row->previous()->par() == refresh_row->par())
1428                 {
1429                         refresh_row = refresh_row->previous();
1430                         refresh_y -= refresh_row->height();
1431                 }
1432         }
1433         removeParagraph(cursor.row());
1434
1435         // set the dimensions of the cursor row
1436         cursor.row()->fill(fill(*bview, *cursor.row(), workWidth(*bview)));
1437
1438         setHeightOfRow(bview, cursor.row());
1439
1440 #warning Trouble Point! (Lgb)
1441         // When ::breakParagraph is called from within an inset we must
1442         // ensure that the correct ParagraphList is used. Today that is not
1443         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1444         while (!cursor.par()->next()->empty()
1445           && cursor.par()->next()->isNewline(0))
1446            cursor.par()->next()->erase(0);
1447
1448         insertParagraph(bview, cursor.par()->next(), cursor.row());
1449
1450         updateCounters(bview);
1451
1452         // This check is necessary. Otherwise the new empty paragraph will
1453         // be deleted automatically. And it is more friendly for the user!
1454         if (cursor.pos() || isempty)
1455                 setCursor(bview, cursor.par()->next(), 0);
1456         else
1457                 setCursor(bview, cursor.par(), 0);
1458
1459         if (cursor.row()->next())
1460                 breakAgain(bview, cursor.row()->next());
1461
1462         need_break_row = 0;
1463 }
1464
1465
1466 // Just a macro to make some thing easier.
1467 void LyXText::redoParagraph(BufferView * bview) const
1468 {
1469         clearSelection();
1470         redoParagraphs(bview, cursor, cursor.par()->next());
1471         setCursorIntern(bview, cursor.par(), cursor.pos());
1472 }
1473
1474
1475 // insert a character, moves all the following breaks in the
1476 // same Paragraph one to the right and make a rebreak
1477 void LyXText::insertChar(BufferView * bview, char c)
1478 {
1479         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1480
1481         // When the free-spacing option is set for the current layout,
1482         // disable the double-space checking
1483
1484         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1485                 cursor.row()->par()->isFreeSpacing();
1486
1487         if (lyxrc.auto_number) {
1488                 static string const number_operators = "+-/*";
1489                 static string const number_unary_operators = "+-";
1490                 static string const number_seperators = ".,:";
1491
1492                 if (current_font.number() == LyXFont::ON) {
1493                         if (!IsDigit(c) && !contains(number_operators, c) &&
1494                             !(contains(number_seperators, c) &&
1495                               cursor.pos() >= 1 &&
1496                               cursor.pos() < cursor.par()->size() &&
1497                               getFont(bview->buffer(),
1498                                       cursor.par(),
1499                                       cursor.pos()).number() == LyXFont::ON &&
1500                               getFont(bview->buffer(),
1501                                       cursor.par(),
1502                                       cursor.pos() - 1).number() == LyXFont::ON)
1503                            )
1504                                 number(bview); // Set current_font.number to OFF
1505                 } else if (IsDigit(c) &&
1506                            real_current_font.isVisibleRightToLeft()) {
1507                         number(bview); // Set current_font.number to ON
1508
1509                         if (cursor.pos() > 0) {
1510                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1511                                 if (contains(number_unary_operators, c) &&
1512                                     (cursor.pos() == 1 ||
1513                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1514                                      cursor.par()->isNewline(cursor.pos() - 2))
1515                                   ) {
1516                                         setCharFont(bview->buffer(),
1517                                                     cursor.par(),
1518                                                     cursor.pos() - 1,
1519                                                     current_font);
1520                                 } else if (contains(number_seperators, c) &&
1521                                            cursor.pos() >= 2 &&
1522                                            getFont(bview->buffer(),
1523                                                    cursor.par(),
1524                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1525                                         setCharFont(bview->buffer(),
1526                                                     cursor.par(),
1527                                                     cursor.pos() - 1,
1528                                                     current_font);
1529                                 }
1530                         }
1531                 }
1532         }
1533
1534
1535         // First check, if there will be two blanks together or a blank at
1536         // the beginning of a paragraph.
1537         // I decided to handle blanks like normal characters, the main
1538         // difference are the special checks when calculating the row.fill
1539         // (blank does not count at the end of a row) and the check here
1540
1541         // The bug is triggered when we type in a description environment:
1542         // The current_font is not changed when we go from label to main text
1543         // and it should (along with realtmpfont) when we type the space.
1544         // CHECK There is a bug here! (Asger)
1545
1546         LyXFont realtmpfont = real_current_font;
1547         LyXFont rawtmpfont = current_font;
1548         // store the current font.  This is because of the use of cursor
1549         // movements. The moving cursor would refresh the current font
1550
1551         // Get the font that is used to calculate the baselineskip
1552         pos_type const lastpos = cursor.par()->size();
1553         LyXFont rawparfont =
1554                 cursor.par()->getFontSettings(bview->buffer()->params,
1555                                               lastpos - 1);
1556
1557         bool jumped_over_space = false;
1558
1559         if (!freeSpacing && IsLineSeparatorChar(c)) {
1560                 if ((cursor.pos() > 0
1561                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1562                     || (cursor.pos() > 0
1563                         && cursor.par()->isNewline(cursor.pos() - 1))
1564                     || (cursor.pos() == 0)) {
1565                         static bool sent_space_message = false;
1566                         if (!sent_space_message) {
1567                                 if (cursor.pos() == 0)
1568                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1569                                 else
1570                                         bview->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1571                                 sent_space_message = true;
1572                         }
1573                         charInserted();
1574                         return;
1575                 }
1576         } else if (IsNewlineChar(c)) {
1577                 if (cursor.pos() <= cursor.par()->beginningOfBody()) {
1578                         charInserted();
1579                         return;
1580                 }
1581                 // No newline at first position of a paragraph or behind labels.
1582                 // TeX does not allow that
1583
1584                 if (cursor.pos() < cursor.par()->size() &&
1585                     cursor.par()->isLineSeparator(cursor.pos()))
1586                         // newline always after a blank!
1587                         cursorRight(bview);
1588                 cursor.row()->fill(-1);        // to force a new break
1589         }
1590
1591         // the display inset stuff
1592         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1593                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1594                 if (inset && (inset->display() || inset->needFullRow())) {
1595                         // force a new break
1596                         cursor.row()->fill(-1); // to force a new break
1597                 }
1598         }
1599
1600         // get the cursor row fist
1601         Row * row = cursor.row();
1602         int y = cursor.y() - row->baseline();
1603         if (c != Paragraph::META_INSET) {
1604                 // Here case LyXText::InsertInset  already insertet the character
1605                 cursor.par()->insertChar(cursor.pos(), c);
1606         }
1607         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1608
1609         if (!jumped_over_space) {
1610                 // refresh the positions
1611                 Row * tmprow = row;
1612                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1613                         tmprow = tmprow->next();
1614                         tmprow->pos(tmprow->pos() + 1);
1615                 }
1616         }
1617
1618         // Is there a break one row above
1619         if (row->previous() && row->previous()->par() == row->par()
1620             && (cursor.par()->isLineSeparator(cursor.pos())
1621                 || cursor.par()->isNewline(cursor.pos())
1622                 || ((cursor.pos() < cursor.par()->size()) &&
1623                     cursor.par()->isInset(cursor.pos()+1))
1624                 || cursor.row()->fill() == -1))
1625         {
1626                 pos_type z = rowBreakPoint(*bview, *row->previous());
1627
1628                 if (z >= row->pos()) {
1629                         row->pos(z + 1);
1630
1631                         // set the dimensions of the row above
1632                         row->previous()->fill(fill(*bview,
1633                                                    *row->previous(),
1634                                                    workWidth(*bview)));
1635
1636                         setHeightOfRow(bview, row->previous());
1637
1638                         y -= row->previous()->height();
1639                         refresh_y = y;
1640                         refresh_row = row->previous();
1641                         status(bview, LyXText::NEED_MORE_REFRESH);
1642
1643                         breakAgainOneRow(bview, row);
1644
1645                         current_font = rawtmpfont;
1646                         real_current_font = realtmpfont;
1647                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1648                                   false, cursor.boundary());
1649                         // cursor MUST be in row now.
1650
1651                         if (row->next() && row->next()->par() == row->par())
1652                                 need_break_row = row->next();
1653                         else
1654                                 need_break_row = 0;
1655
1656                         // check, wether the last characters font has changed.
1657                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1658                             && rawparfont != rawtmpfont)
1659                                 redoHeightOfParagraph(bview, cursor);
1660
1661                         charInserted();
1662                         return;
1663                 }
1664         }
1665
1666         // recalculate the fill of the row
1667         if (row->fill() >= 0) {
1668                 // needed because a newline will set fill to -1. Otherwise
1669                 // we would not get a rebreak!
1670                 row->fill(fill(*bview, *row, workWidth(*bview)));
1671         }
1672
1673         if (c == Paragraph::META_INSET || row->fill() < 0) {
1674                 refresh_y = y;
1675                 refresh_row = row;
1676                 status(bview, LyXText::NEED_MORE_REFRESH);
1677                 breakAgainOneRow(bview, row);
1678                 // will the cursor be in another row now?
1679                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1680                         if (row->next() && row->next()->par() == row->par())
1681                                 // this should always be true
1682                                 row = row->next();
1683                         breakAgainOneRow(bview, row);
1684                 }
1685                 current_font = rawtmpfont;
1686                 real_current_font = realtmpfont;
1687
1688                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1689                           cursor.boundary());
1690                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1691                     != cursor.boundary())
1692                         setCursor(bview, cursor.par(), cursor.pos(), false,
1693                           !cursor.boundary());
1694                 if (row->next() && row->next()->par() == row->par())
1695                         need_break_row = row->next();
1696                 else
1697                         need_break_row = 0;
1698         } else {
1699                 refresh_y = y;
1700                 refresh_row = row;
1701
1702                 int const tmpheight = row->height();
1703                 setHeightOfRow(bview, row);
1704                 if (tmpheight == row->height())
1705                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1706                 else
1707                         status(bview, LyXText::NEED_MORE_REFRESH);
1708
1709                 current_font = rawtmpfont;
1710                 real_current_font = realtmpfont;
1711                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1712                           cursor.boundary());
1713         }
1714
1715         // check, wether the last characters font has changed.
1716         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1717             && rawparfont != rawtmpfont) {
1718                 redoHeightOfParagraph(bview, cursor);
1719         } else {
1720                 // now the special right address boxes
1721                 if (cursor.par()->layout()->margintype
1722                     == MARGIN_RIGHT_ADDRESS_BOX) {
1723                         redoDrawingOfParagraph(bview, cursor);
1724                 }
1725         }
1726
1727         charInserted();
1728 }
1729
1730
1731 void LyXText::charInserted()
1732 {
1733         // Here we could call FinishUndo for every 20 characters inserted.
1734         // This is from my experience how emacs does it.
1735         static unsigned int counter;
1736         if (counter < 20) {
1737                 ++counter;
1738         } else {
1739                 finishUndo();
1740                 counter = 0;
1741         }
1742 }
1743
1744
1745 void LyXText::prepareToPrint(BufferView * bview,
1746                              Row * row, float & x,
1747                              float & fill_separator,
1748                              float & fill_hfill,
1749                              float & fill_label_hfill,
1750                              bool bidi) const
1751 {
1752         float nlh;
1753         float ns;
1754
1755         float w = row->fill();
1756         fill_hfill = 0;
1757         fill_label_hfill = 0;
1758         fill_separator = 0;
1759         fill_label_hfill = 0;
1760
1761         bool const is_rtl =
1762                 row->par()->isRightToLeftPar(bview->buffer()->params);
1763         if (is_rtl) {
1764                 x = (workWidth(*bview) > 0)
1765                         ? rightMargin(*bview->buffer(), *row) : 0;
1766         } else
1767                 x = (workWidth(*bview) > 0)
1768                         ? leftMargin(bview, row) : 0;
1769
1770         // is there a manual margin with a manual label
1771         LyXLayout_ptr const & layout = row->par()->layout();
1772
1773         if (layout->margintype == MARGIN_MANUAL
1774             && layout->labeltype == LABEL_MANUAL) {
1775                 /// We might have real hfills in the label part
1776                 nlh = row->numberOfLabelHfills();
1777
1778                 // A manual label par (e.g. List) has an auto-hfill
1779                 // between the label text and the body of the
1780                 // paragraph too.
1781                 // But we don't want to do this auto hfill if the par
1782                 // is empty.
1783                 if (!row->par()->empty())
1784                         ++nlh;
1785                         
1786                 if (nlh && !row->par()->getLabelWidthString().empty()) {
1787                         fill_label_hfill = labelFill(*bview, *row) / nlh;
1788                 }
1789         }
1790
1791         // are there any hfills in the row?
1792         float const nh = row->numberOfHfills();
1793
1794         if (nh) {
1795                 if (w > 0)
1796                         fill_hfill = w / nh;
1797         // we don't have to look at the alignment if it is ALIGN_LEFT and
1798         // if the row is already larger then the permitted width as then
1799         // we force the LEFT_ALIGN'edness!
1800         } else if (static_cast<int>(row->width()) < workWidth(*bview)) {
1801                 // is it block, flushleft or flushright?
1802                 // set x how you need it
1803                 int align;
1804                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
1805                         align = layout->align;
1806                 } else {
1807                         align = row->par()->params().align();
1808                 }
1809
1810                 // center displayed insets
1811                 Inset * inset;
1812                 if (row->par()->isInset(row->pos())
1813                     && (inset=row->par()->getInset(row->pos()))
1814                     && (inset->display())) // || (inset->scroll() < 0)))
1815                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1816                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1817                 // ERT insets should always be LEFT ALIGNED on screen
1818                 inset = row->par()->inInset();
1819                 if (inset && inset->owner() &&
1820                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1821                 {
1822                         align = LYX_ALIGN_LEFT;
1823                 }
1824
1825                 switch (align) {
1826             case LYX_ALIGN_BLOCK:
1827                         ns = row->numberOfSeparators();
1828                         if (ns && row->next() && row->next()->par() == row->par() &&
1829                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
1830                             && !(row->next()->par()->isInset(row->next()->pos())
1831                                  && row->next()->par()->getInset(row->next()->pos())
1832                                  && row->next()->par()->getInset(row->next()->pos())->display())
1833                                 )
1834                         {
1835                                 fill_separator = w / ns;
1836                         } else if (is_rtl) {
1837                                 x += w;
1838                         }
1839                         break;
1840             case LYX_ALIGN_RIGHT:
1841                         x += w;
1842                         break;
1843             case LYX_ALIGN_CENTER:
1844                         x += w / 2;
1845                         break;
1846                 }
1847         }
1848         if (!bidi)
1849                 return;
1850
1851         computeBidiTables(bview->buffer(), row);
1852         if (is_rtl) {
1853                 pos_type body_pos = row->par()->beginningOfBody();
1854                 pos_type last = row->lastPos();
1855
1856                 if (body_pos > 0 &&
1857                     (body_pos - 1 > last ||
1858                      !row->par()->isLineSeparator(body_pos - 1))) {
1859                         x += font_metrics::width(layout->labelsep,
1860                                             getLabelFont(bview->buffer(), row->par()));
1861                         if (body_pos - 1 <= last)
1862                                 x += fill_label_hfill;
1863                 }
1864         }
1865 }
1866
1867
1868 // important for the screen
1869
1870
1871 // the cursor set functions have a special mechanism. When they
1872 // realize, that you left an empty paragraph, they will delete it.
1873 // They also delete the corresponding row
1874
1875 void LyXText::cursorRightOneWord(BufferView * bview) const
1876 {
1877         // treat floats, HFills and Insets as words
1878         LyXCursor tmpcursor = cursor;
1879         // CHECK See comment on top of text.C
1880
1881         if (tmpcursor.pos() == tmpcursor.par()->size()
1882             && tmpcursor.par()->next()) {
1883                         tmpcursor.par(tmpcursor.par()->next());
1884                         tmpcursor.pos(0);
1885         } else {
1886                 int steps = 0;
1887
1888                 // Skip through initial nonword stuff.
1889                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1890                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
1891                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
1892                         tmpcursor.pos(tmpcursor.pos() + 1);
1893                         ++steps;
1894                 }
1895                 // Advance through word.
1896                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1897                         tmpcursor.par()->isWord(tmpcursor.pos())) {
1898                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
1899                         tmpcursor.pos(tmpcursor.pos() + 1);
1900                         ++steps;
1901                 }
1902         }
1903         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1904 }
1905
1906
1907 void LyXText::cursorTab(BufferView * bview) const
1908 {
1909         LyXCursor tmpcursor = cursor;
1910         while (tmpcursor.pos() < tmpcursor.par()->size()
1911            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
1912         tmpcursor.pos(tmpcursor.pos() + 1);
1913
1914         if (tmpcursor.pos() == tmpcursor.par()->size()) {
1915                 if (tmpcursor.par()->next()) {
1916                         tmpcursor.par(tmpcursor.par()->next());
1917                         tmpcursor.pos(0);
1918                 }
1919         } else
1920                 tmpcursor.pos(tmpcursor.pos() + 1);
1921         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1922 }
1923
1924
1925 // Skip initial whitespace at end of word and move cursor to *start*
1926 // of prior word, not to end of next prior word.
1927 void LyXText::cursorLeftOneWord(BufferView * bview)  const
1928 {
1929         LyXCursor tmpcursor = cursor;
1930         cursorLeftOneWord(tmpcursor);
1931         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1932 }
1933
1934
1935 void LyXText::cursorLeftOneWord(LyXCursor & cur) const
1936 {
1937         // treat HFills, floats and Insets as words
1938         cur = cursor;
1939         while (cur.pos()
1940                && (cur.par()->isSeparator(cur.pos() - 1)
1941                    || cur.par()->isKomma(cur.pos() - 1))
1942                && !(cur.par()->isHfill(cur.pos() - 1)
1943                     || cur.par()->isInset(cur.pos() - 1)))
1944                 cur.pos(cur.pos() - 1);
1945
1946         if (cur.pos()
1947             && (cur.par()->isInset(cur.pos() - 1)
1948                 || cur.par()->isHfill(cur.pos() - 1))) {
1949                 cur.pos(cur.pos() - 1);
1950         } else if (!cur.pos()) {
1951                 if (cur.par()->previous()) {
1952                         cur.par(cur.par()->previous());
1953                         cur.pos(cur.par()->size());
1954                 }
1955         } else {                // Here, cur != 0
1956                 while (cur.pos() > 0 &&
1957                        cur.par()->isWord(cur.pos() - 1))
1958                         cur.pos(cur.pos() - 1);
1959         }
1960 }
1961
1962
1963 // Select current word. This depends on behaviour of
1964 // CursorLeftOneWord(), so it is patched as well.
1965 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
1966                       word_location const loc) const
1967 {
1968         // first put the cursor where we wana start to select the word
1969         from = cursor;
1970         switch (loc) {
1971         case WHOLE_WORD_STRICT:
1972                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
1973                     || cursor.par()->isSeparator(cursor.pos())
1974                     || cursor.par()->isKomma(cursor.pos())
1975                     || cursor.par()->isSeparator(cursor.pos() - 1)
1976                     || cursor.par()->isKomma(cursor.pos() - 1)) {
1977                         to = from;
1978                         return;
1979                 }
1980                 // no break here, we go to the next
1981
1982         case WHOLE_WORD:
1983                 // Move cursor to the beginning, when not already there.
1984                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
1985                     && !from.par()->isKomma(from.pos() - 1))
1986                         cursorLeftOneWord(from);
1987                 break;
1988         case PREVIOUS_WORD:
1989                 // always move the cursor to the beginning of previous word
1990                 cursorLeftOneWord(from);
1991                 break;
1992         case NEXT_WORD:
1993                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
1994                 break;
1995         case PARTIAL_WORD:
1996                 break;
1997         }
1998         to = from;
1999         while (to.pos() < to.par()->size()
2000                && !to.par()->isSeparator(to.pos())
2001                && !to.par()->isKomma(to.pos())
2002                && !to.par()->isHfill(to.pos())
2003                && !to.par()->isInset(to.pos()))
2004         {
2005                 to.pos(to.pos() + 1);
2006         }
2007 }
2008
2009
2010 void LyXText::selectWord(BufferView * bview, word_location const loc)
2011 {
2012         LyXCursor from;
2013         LyXCursor to;
2014         getWord(from, to, loc);
2015         if (cursor != from)
2016                 setCursor(bview, from.par(), from.pos());
2017         if (to == from)
2018                 return;
2019         selection.cursor = cursor;
2020         setCursor(bview, to.par(), to.pos());
2021         setSelection(bview);
2022 }
2023
2024
2025 // Select the word currently under the cursor when no
2026 // selection is currently set
2027 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2028                                         word_location const loc)
2029 {
2030         if (!selection.set()) {
2031                 selectWord(bview, loc);
2032                 return selection.set();
2033         }
2034         return false;
2035 }
2036
2037
2038 void LyXText::acceptChange(BufferView * bv)
2039 {
2040         if (!selection.set() && cursor.par()->size())
2041                 return;
2042
2043         bv->hideCursor();
2044
2045         if (selection.start.par() == selection.end.par()) {
2046                 LyXCursor & startc = selection.start;
2047                 LyXCursor & endc = selection.end;
2048                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2049                 startc.par()->acceptChange(startc.pos(), endc.pos());
2050                 finishUndo();
2051                 clearSelection();
2052                 redoParagraphs(bv, startc, startc.par()->next());
2053                 setCursorIntern(bv, startc.par(), 0);
2054         }
2055 #warning handle multi par selection
2056 }
2057
2058
2059 void LyXText::rejectChange(BufferView * bv)
2060 {
2061         if (!selection.set() && cursor.par()->size())
2062                 return;
2063
2064         bv->hideCursor();
2065
2066         if (selection.start.par() == selection.end.par()) {
2067                 LyXCursor & startc = selection.start;
2068                 LyXCursor & endc = selection.end;
2069                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2070                 startc.par()->rejectChange(startc.pos(), endc.pos());
2071                 finishUndo();
2072                 clearSelection();
2073                 redoParagraphs(bv, startc, startc.par()->next());
2074                 setCursorIntern(bv, startc.par(), 0);
2075         }
2076 #warning handle multi par selection
2077 }
2078
2079
2080 // This function is only used by the spellchecker for NextWord().
2081 // It doesn't handle LYX_ACCENTs and probably never will.
2082 WordLangTuple const
2083 LyXText::selectNextWordToSpellcheck(BufferView * bview, float & value) const
2084 {
2085         if (the_locking_inset) {
2086                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2087                 if (!word.word().empty()) {
2088                         value += float(cursor.y());
2089                         value /= float(height);
2090                         return word;
2091                 }
2092                 // we have to go on checking so move cursor to the next char
2093                 if (cursor.pos() == cursor.par()->size()) {
2094                         if (!cursor.par()->next())
2095                                 return word;
2096                         cursor.par(cursor.par()->next());
2097                         cursor.pos(0);
2098                 } else
2099                         cursor.pos(cursor.pos() + 1);
2100         }
2101         Paragraph * tmppar = cursor.par();
2102
2103         // If this is not the very first word, skip rest of
2104         // current word because we are probably in the middle
2105         // of a word if there is text here.
2106         if (cursor.pos() || cursor.par()->previous()) {
2107                 while (cursor.pos() < cursor.par()->size()
2108                        && cursor.par()->isLetter(cursor.pos()))
2109                         cursor.pos(cursor.pos() + 1);
2110         }
2111
2112         // Now, skip until we have real text (will jump paragraphs)
2113         while (1) {
2114                 Paragraph * cpar(cursor.par());
2115                 pos_type const cpos(cursor.pos());
2116
2117                 if (cpos == cpar->size()) {
2118                         if (cpar->next()) {
2119                                 cursor.par(cpar->next());
2120                                 cursor.pos(0);
2121                                 continue;
2122                         }
2123                         break;
2124                 }
2125
2126                 bool const is_bad_inset(cpar->isInset(cpos)
2127                         && !cpar->getInset(cpos)->allowSpellcheck());
2128
2129                 if (cpar->isLetter(cpos) && !isDeletedText(*cpar, cpos)
2130                         && !is_bad_inset)
2131                         break;
2132
2133                 cursor.pos(cpos + 1);
2134         }
2135
2136         // now check if we hit an inset so it has to be a inset containing text!
2137         if (cursor.pos() < cursor.par()->size() &&
2138             cursor.par()->isInset(cursor.pos())) {
2139                 // lock the inset!
2140                 cursor.par()->getInset(cursor.pos())->edit(bview);
2141                 // now call us again to do the above trick
2142                 // but obviously we have to start from down below ;)
2143                 return bview->text->selectNextWordToSpellcheck(bview, value);
2144         }
2145
2146         // Update the value if we changed paragraphs
2147         if (cursor.par() != tmppar) {
2148                 setCursor(bview, cursor.par(), cursor.pos());
2149                 value = float(cursor.y())/float(height);
2150         }
2151
2152         // Start the selection from here
2153         selection.cursor = cursor;
2154
2155         string lang_code(
2156                 getFont(bview->buffer(), cursor.par(), cursor.pos())
2157                         .language()->code());
2158         // and find the end of the word (insets like optional hyphens
2159         // and ligature break are part of a word)
2160         while (cursor.pos() < cursor.par()->size()
2161                && cursor.par()->isLetter(cursor.pos())
2162                && !isDeletedText(*cursor.par(), cursor.pos()))
2163                 cursor.pos(cursor.pos() + 1);
2164
2165         // Finally, we copy the word to a string and return it
2166         string str;
2167         if (selection.cursor.pos() < cursor.pos()) {
2168                 pos_type i;
2169                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2170                         if (!cursor.par()->isInset(i))
2171                                 str += cursor.par()->getChar(i);
2172                 }
2173         }
2174         return WordLangTuple(str, lang_code);
2175 }
2176
2177
2178 // This one is also only for the spellchecker
2179 void LyXText::selectSelectedWord(BufferView * bview)
2180 {
2181         if (the_locking_inset) {
2182                 the_locking_inset->selectSelectedWord(bview);
2183                 return;
2184         }
2185         // move cursor to the beginning
2186         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2187
2188         // set the sel cursor
2189         selection.cursor = cursor;
2190
2191         // now find the end of the word
2192         while (cursor.pos() < cursor.par()->size()
2193                && (cursor.par()->isLetter(cursor.pos())))
2194                 cursor.pos(cursor.pos() + 1);
2195
2196         setCursor(bview, cursor.par(), cursor.pos());
2197
2198         // finally set the selection
2199         setSelection(bview);
2200 }
2201
2202
2203 // Delete from cursor up to the end of the current or next word.
2204 void LyXText::deleteWordForward(BufferView * bview)
2205 {
2206         if (cursor.par()->empty())
2207                 cursorRight(bview);
2208         else {
2209                 LyXCursor tmpcursor = cursor;
2210                 tmpcursor.row(0); // ??
2211                 selection.set(true); // to avoid deletion
2212                 cursorRightOneWord(bview);
2213                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2214                 selection.cursor = cursor;
2215                 cursor = tmpcursor;
2216                 setSelection(bview);
2217
2218                 // Great, CutSelection() gets rid of multiple spaces.
2219                 cutSelection(bview, true, false);
2220         }
2221 }
2222
2223
2224 // Delete from cursor to start of current or prior word.
2225 void LyXText::deleteWordBackward(BufferView * bview)
2226 {
2227         if (cursor.par()->empty())
2228                 cursorLeft(bview);
2229         else {
2230                 LyXCursor tmpcursor = cursor;
2231                 tmpcursor.row(0); // ??
2232                 selection.set(true); // to avoid deletion
2233                 cursorLeftOneWord(bview);
2234                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2235                 selection.cursor = cursor;
2236                 cursor = tmpcursor;
2237                 setSelection(bview);
2238                 cutSelection(bview, true, false);
2239         }
2240 }
2241
2242
2243 // Kill to end of line.
2244 void LyXText::deleteLineForward(BufferView * bview)
2245 {
2246         if (cursor.par()->empty())
2247                 // Paragraph is empty, so we just go to the right
2248                 cursorRight(bview);
2249         else {
2250                 LyXCursor tmpcursor = cursor;
2251                 // We can't store the row over a regular setCursor
2252                 // so we set it to 0 and reset it afterwards.
2253                 tmpcursor.row(0); // ??
2254                 selection.set(true); // to avoid deletion
2255                 cursorEnd(bview);
2256                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2257                 selection.cursor = cursor;
2258                 cursor = tmpcursor;
2259                 setSelection(bview);
2260                 // What is this test for ??? (JMarc)
2261                 if (!selection.set()) {
2262                         deleteWordForward(bview);
2263                 } else {
2264                         cutSelection(bview, true, false);
2265                 }
2266         }
2267 }
2268
2269
2270 void LyXText::changeCase(BufferView & bview, LyXText::TextCase action)
2271 {
2272         LyXCursor from;
2273         LyXCursor to;
2274
2275         if (selection.set()) {
2276                 from = selection.start;
2277                 to = selection.end;
2278         } else {
2279                 getWord(from, to, PARTIAL_WORD);
2280                 setCursor(&bview, to.par(), to.pos() + 1);
2281         }
2282
2283         lyx::Assert(from <= to);
2284
2285         setUndo(&bview, Undo::FINISH, from.par(), to.par()->next());
2286
2287         pos_type pos = from.pos();
2288         Paragraph * par = from.par();
2289
2290         while (par && (pos != to.pos() || par != to.par())) {
2291                 if (pos == par->size()) {
2292                         par = par->next();
2293                         pos = 0;
2294                         continue;
2295                 }
2296                 unsigned char c = par->getChar(pos);
2297                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2298                         switch (action) {
2299                         case text_lowercase:
2300                                 c = lowercase(c);
2301                                 break;
2302                         case text_capitalization:
2303                                 c = uppercase(c);
2304                                 action = text_lowercase;
2305                                 break;
2306                         case text_uppercase:
2307                                 c = uppercase(c);
2308                                 break;
2309                         }
2310                 }
2311 #warning changes
2312                 par->setChar(pos, c);
2313                 checkParagraph(&bview, par, pos);
2314
2315                 ++pos;
2316         }
2317         if (to.row() != from.row()) {
2318                 refresh_y = from.y() - from.row()->baseline();
2319                 refresh_row = from.row();
2320                 status(&bview, LyXText::NEED_MORE_REFRESH);
2321         }
2322 }
2323
2324
2325 void LyXText::transposeChars(BufferView & bview)
2326 {
2327         Paragraph * tmppar = cursor.par();
2328
2329         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2330
2331         pos_type tmppos = cursor.pos();
2332
2333         // First decide if it is possible to transpose at all
2334
2335         if (tmppos == 0 || tmppos == tmppar->size())
2336                 return;
2337
2338         if (isDeletedText(*tmppar, tmppos - 1)
2339                 || isDeletedText(*tmppar, tmppos))
2340                 return;
2341
2342         unsigned char c1 = tmppar->getChar(tmppos);
2343         unsigned char c2 = tmppar->getChar(tmppos - 1);
2344
2345         // We should have an implementation that handles insets
2346         // as well, but that will have to come later. (Lgb)
2347         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET)
2348                 return;
2349
2350         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2351         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2352
2353         tmppar->insertChar(ipos, c1);
2354         tmppar->insertChar(ipos + 1, c2);
2355
2356         checkParagraph(&bview, tmppar, tmppos);
2357 }
2358
2359
2360 void LyXText::Delete(BufferView * bview)
2361 {
2362         // this is a very easy implementation
2363
2364         LyXCursor old_cursor = cursor;
2365         int const old_cur_par_id = old_cursor.par()->id();
2366         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2367                 old_cursor.par()->previous()->id() : -1;
2368
2369         // just move to the right
2370         cursorRight(bview);
2371
2372         // CHECK Look at the comment here.
2373         // This check is not very good...
2374         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2375         // and that can very well delete the par or par->previous in
2376         // old_cursor. Will a solution where we compare paragraph id's
2377         //work better?
2378         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2379             == old_cur_par_prev_id
2380             && cursor.par()->id() != old_cur_par_id) {
2381                 // delete-empty-paragraph-mechanism has done it
2382                 return;
2383         }
2384
2385         // if you had success make a backspace
2386         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2387                 LyXCursor tmpcursor = cursor;
2388                 // to make sure undo gets the right cursor position
2389                 cursor = old_cursor;
2390                 setUndo(bview, Undo::DELETE,
2391                         cursor.par(), cursor.par()->next());
2392                 cursor = tmpcursor;
2393                 backspace(bview);
2394         }
2395 }
2396
2397
2398 void LyXText::backspace(BufferView * bview)
2399 {
2400         // Get the font that is used to calculate the baselineskip
2401         pos_type lastpos = cursor.par()->size();
2402         LyXFont rawparfont =
2403                 cursor.par()->getFontSettings(bview->buffer()->params,
2404                                               lastpos - 1);
2405
2406         if (cursor.pos() == 0) {
2407                 // The cursor is at the beginning of a paragraph,
2408                 // so the the backspace will collapse two paragraphs into one.
2409
2410                 // but it's not allowed unless it's new
2411                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2412                         return;
2413
2414                 // we may paste some paragraphs
2415
2416                 // is it an empty paragraph?
2417
2418                 if ((lastpos == 0
2419                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2420                         // This is an empty paragraph and we delete it just by moving the cursor one step
2421                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2422                         // of the paragraph.
2423
2424                         if (cursor.par()->previous()) {
2425                                 Paragraph * tmppar = cursor.par()->previous();
2426                                 if (cursor.par()->layout() == tmppar->layout()
2427                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2428                                         // Inherit bottom DTD from the paragraph below.
2429                                         // (the one we are deleting)
2430                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2431                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2432                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2433                                 }
2434
2435                                 cursorLeft(bview);
2436
2437                                 // the layout things can change the height of a row !
2438                                 int const tmpheight = cursor.row()->height();
2439                                 setHeightOfRow(bview, cursor.row());
2440                                 if (cursor.row()->height() != tmpheight) {
2441                                         refresh_y = cursor.y() - cursor.row()->baseline();
2442                                         refresh_row = cursor.row();
2443                                         status(bview, LyXText::NEED_MORE_REFRESH);
2444                                 }
2445                                 return;
2446                         }
2447                 }
2448
2449                 if (cursor.par()->previous()) {
2450                         setUndo(bview, Undo::DELETE,
2451                                 cursor.par()->previous(), cursor.par()->next());
2452                 }
2453
2454                 Paragraph * tmppar = cursor.par();
2455                 Row * tmprow = cursor.row();
2456
2457                 // We used to do cursorLeftIntern() here, but it is
2458                 // not a good idea since it triggers the auto-delete
2459                 // mechanism. So we do a cursorLeftIntern()-lite,
2460                 // without the dreaded mechanism. (JMarc)
2461                 if (cursor.par()->previous()) {
2462                         // steps into the above paragraph.
2463                         setCursorIntern(bview, cursor.par()->previous(),
2464                                         cursor.par()->previous()->size(),
2465                                         false);
2466                 }
2467
2468                 // Pasting is not allowed, if the paragraphs have different
2469                 // layout. I think it is a real bug of all other
2470                 // word processors to allow it. It confuses the user.
2471                 // Even so with a footnote paragraph and a non-footnote
2472                 // paragraph. I will not allow pasting in this case,
2473                 // because the user would be confused if the footnote behaves
2474                 // different wether it is open or closed.
2475
2476                 //      Correction: Pasting is always allowed with standard-layout
2477                 LyXTextClass const & tclass =
2478                         bview->buffer()->params.getLyXTextClass();
2479
2480                 if (cursor.par() != tmppar
2481                     && (cursor.par()->layout() == tmppar->layout()
2482                         || tmppar->layout() == tclass.defaultLayout())
2483                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2484                         removeParagraph(tmprow);
2485                         removeRow(tmprow);
2486                         mergeParagraph(bview->buffer()->params, bview->buffer()->paragraphs, cursor.par());
2487
2488                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2489                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2490                         // strangely enough it seems that commenting out the line above removes
2491                         // most or all of the segfaults. I will however also try to move the
2492                         // two Remove... lines in front of the PasteParagraph too.
2493                         else
2494                                 if (cursor.pos())
2495                                         cursor.pos(cursor.pos() - 1);
2496
2497                         status(bview, LyXText::NEED_MORE_REFRESH);
2498                         refresh_row = cursor.row();
2499                         refresh_y = cursor.y() - cursor.row()->baseline();
2500
2501                         // remove the lost paragraph
2502                         // This one is not safe, since the paragraph that the tmprow and the
2503                         // following rows belong to has been deleted by the PasteParagraph
2504                         // above. The question is... could this be moved in front of the
2505                         // PasteParagraph?
2506                         //RemoveParagraph(tmprow);
2507                         //RemoveRow(tmprow);
2508
2509                         // This rebuilds the rows.
2510                         appendParagraph(bview, cursor.row());
2511                         updateCounters(bview);
2512
2513                         // the row may have changed, block, hfills etc.
2514                         setCursor(bview, cursor.par(), cursor.pos(), false);
2515                 }
2516         } else {
2517                 // this is the code for a normal backspace, not pasting
2518                 // any paragraphs
2519                 setUndo(bview, Undo::DELETE,
2520                         cursor.par(), cursor.par()->next());
2521                 // We used to do cursorLeftIntern() here, but it is
2522                 // not a good idea since it triggers the auto-delete
2523                 // mechanism. So we do a cursorLeftIntern()-lite,
2524                 // without the dreaded mechanism. (JMarc)
2525                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2526                                 false, cursor.boundary());
2527
2528                 if (cursor.par()->isInset(cursor.pos())) {
2529                         // force complete redo when erasing display insets
2530                         // this is a cruel method but safe..... Matthias
2531                         if (cursor.par()->getInset(cursor.pos())->display() ||
2532                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2533                                 cursor.par()->erase(cursor.pos());
2534                                 redoParagraph(bview);
2535                                 return;
2536                         }
2537                 }
2538
2539                 Row * row = cursor.row();
2540                 int y = cursor.y() - row->baseline();
2541                 pos_type z;
2542                 // remember that a space at the end of a row doesnt count
2543                 // when calculating the fill
2544                 if (cursor.pos() < row->lastPos() ||
2545                     !cursor.par()->isLineSeparator(cursor.pos())) {
2546                         row->fill(row->fill() + singleWidth(bview,
2547                                                             cursor.par(),
2548                                                             cursor.pos()));
2549                 }
2550
2551                 // some special code when deleting a newline. This is similar
2552                 // to the behavior when pasting paragraphs
2553                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2554                         cursor.par()->erase(cursor.pos());
2555                         // refresh the positions
2556                         Row * tmprow = row;
2557                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2558                                 tmprow = tmprow->next();
2559                                 tmprow->pos(tmprow->pos() - 1);
2560                         }
2561                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2562                                 cursor.pos(cursor.pos() - 1);
2563
2564                         if (cursor.pos() < cursor.par()->size()
2565                             && !cursor.par()->isSeparator(cursor.pos())) {
2566                                 cursor.par()->insertChar(cursor.pos(), ' ');
2567                                 setCharFont(bview->buffer(), cursor.par(),
2568                                             cursor.pos(), current_font);
2569                                 // refresh the positions
2570                                 tmprow = row;
2571                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2572                                         tmprow = tmprow->next();
2573                                         tmprow->pos(tmprow->pos() + 1);
2574                                 }
2575                         }
2576                 } else {
2577                         cursor.par()->erase(cursor.pos());
2578
2579                         // refresh the positions
2580                         Row * tmprow = row;
2581                         while (tmprow->next()
2582                                && tmprow->next()->par() == row->par()) {
2583                                 tmprow = tmprow->next();
2584                                 tmprow->pos(tmprow->pos() - 1);
2585                         }
2586
2587                         // delete newlines at the beginning of paragraphs
2588                         while (!cursor.par()->empty() &&
2589                                cursor.par()->isNewline(cursor.pos()) &&
2590                                cursor.pos() == cursor.par()->beginningOfBody()) {
2591                                 cursor.par()->erase(cursor.pos());
2592                                 // refresh the positions
2593                                 tmprow = row;
2594                                 while (tmprow->next() &&
2595                                        tmprow->next()->par() == row->par()) {
2596                                         tmprow = tmprow->next();
2597                                         tmprow->pos(tmprow->pos() - 1);
2598                                 }
2599                         }
2600                 }
2601
2602                 // is there a break one row above
2603                 if (row->previous() && row->previous()->par() == row->par()) {
2604                         z = rowBreakPoint(*bview, *row->previous());
2605                         if (z >= row->pos()) {
2606                                 row->pos(z + 1);
2607
2608                                 Row * tmprow = row->previous();
2609
2610                                 // maybe the current row is now empty
2611                                 if (row->pos() >= row->par()->size()) {
2612                                         // remove it
2613                                         removeRow(row);
2614                                         need_break_row = 0;
2615                                 } else {
2616                                         breakAgainOneRow(bview, row);
2617                                         if (row->next() && row->next()->par() == row->par())
2618                                                 need_break_row = row->next();
2619                                         else
2620                                                 need_break_row = 0;
2621                                 }
2622
2623                                 // set the dimensions of the row above
2624                                 y -= tmprow->height();
2625                                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
2626                                 setHeightOfRow(bview, tmprow);
2627
2628                                 refresh_y = y;
2629                                 refresh_row = tmprow;
2630                                 status(bview, LyXText::NEED_MORE_REFRESH);
2631                                 setCursor(bview, cursor.par(), cursor.pos(),
2632                                           false, cursor.boundary());
2633                                 //current_font = rawtmpfont;
2634                                 //real_current_font = realtmpfont;
2635                                 // check, whether the last character's font has changed.
2636                                 if (rawparfont !=
2637                                     cursor.par()->getFontSettings(bview->buffer()->params,
2638                                                                   cursor.par()->size() - 1))
2639                                         redoHeightOfParagraph(bview, cursor);
2640                                 return;
2641                         }
2642                 }
2643
2644                 // break the cursor row again
2645                 if (row->next() && row->next()->par() == row->par() &&
2646                     (row->lastPos() == row->par()->size() - 1 ||
2647                      rowBreakPoint(*bview, *row) != row->lastPos())) {
2648
2649                         // it can happen that a paragraph loses one row
2650                         // without a real breakup. This is when a word
2651                         // is to long to be broken. Well, I don t care this
2652                         // hack ;-)
2653                         if (row->lastPos() == row->par()->size() - 1)
2654                                 removeRow(row->next());
2655
2656                         refresh_y = y;
2657                         refresh_row = row;
2658                         status(bview, LyXText::NEED_MORE_REFRESH);
2659
2660                         breakAgainOneRow(bview, row);
2661                         // will the cursor be in another row now?
2662                         if (row->next() && row->next()->par() == row->par() &&
2663                             row->lastPos() <= cursor.pos()) {
2664                                 row = row->next();
2665                                 breakAgainOneRow(bview, row);
2666                         }
2667
2668                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2669
2670                         if (row->next() && row->next()->par() == row->par())
2671                                 need_break_row = row->next();
2672                         else
2673                                 need_break_row = 0;
2674                 } else  {
2675                         // set the dimensions of the row
2676                         row->fill(fill(*bview, *row, workWidth(*bview)));
2677                         int const tmpheight = row->height();
2678                         setHeightOfRow(bview, row);
2679                         if (tmpheight == row->height())
2680                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2681                         else
2682                                 status(bview, LyXText::NEED_MORE_REFRESH);
2683                         refresh_y = y;
2684                         refresh_row = row;
2685                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2686                 }
2687         }
2688
2689         // current_font = rawtmpfont;
2690         // real_current_font = realtmpfont;
2691
2692         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2693             != cursor.boundary())
2694                 setCursor(bview, cursor.par(), cursor.pos(), false,
2695                           !cursor.boundary());
2696
2697         lastpos = cursor.par()->size();
2698         if (cursor.pos() == lastpos)
2699                 setCurrentFont(bview);
2700
2701         // check, whether the last characters font has changed.
2702         if (rawparfont !=
2703             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2704                 redoHeightOfParagraph(bview, cursor);
2705         } else {
2706                 // now the special right address boxes
2707                 if (cursor.par()->layout()->margintype
2708                     == MARGIN_RIGHT_ADDRESS_BOX) {
2709                         redoDrawingOfParagraph(bview, cursor);
2710                 }
2711         }
2712 }
2713
2714
2715 // returns the column near the specified x-coordinate of the row
2716 // x is set to the real beginning of this column
2717 pos_type
2718 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
2719                         bool & boundary) const
2720 {
2721         float tmpx = 0.0;
2722         float fill_separator;
2723         float fill_hfill;
2724         float fill_label_hfill;
2725
2726         prepareToPrint(bview, row, tmpx, fill_separator,
2727                        fill_hfill, fill_label_hfill);
2728
2729         pos_type vc = row->pos();
2730         pos_type last = row->lastPrintablePos();
2731         pos_type c = 0;
2732
2733         LyXLayout_ptr const & layout = row->par()->layout();
2734
2735         bool left_side = false;
2736
2737         pos_type body_pos = row->par()->beginningOfBody();
2738         float last_tmpx = tmpx;
2739
2740         if (body_pos > 0 &&
2741             (body_pos - 1 > last ||
2742              !row->par()->isLineSeparator(body_pos - 1)))
2743                 body_pos = 0;
2744
2745         // check for empty row
2746         if (!row->par()->size()) {
2747                 x = int(tmpx);
2748                 return 0;
2749         }
2750
2751         while (vc <= last && tmpx <= x) {
2752                 c = vis2log(vc);
2753                 last_tmpx = tmpx;
2754                 if (body_pos > 0 && c == body_pos-1) {
2755                         tmpx += fill_label_hfill +
2756                                 font_metrics::width(layout->labelsep,
2757                                                getLabelFont(bview->buffer(), row->par()));
2758                         if (row->par()->isLineSeparator(body_pos - 1))
2759                                 tmpx -= singleWidth(bview, row->par(), body_pos-1);
2760                 }
2761
2762                 if (row->hfillExpansion(c)) {
2763                         tmpx += singleWidth(bview, row->par(), c);
2764                         if (c >= body_pos)
2765                                 tmpx += fill_hfill;
2766                         else
2767                                 tmpx += fill_label_hfill;
2768                 } else if (row->par()->isSeparator(c)) {
2769                         tmpx += singleWidth(bview, row->par(), c);
2770                         if (c >= body_pos)
2771                                 tmpx+= fill_separator;
2772                 } else {
2773                         tmpx += singleWidth(bview, row->par(), c);
2774                 }
2775                 ++vc;
2776         }
2777
2778         if ((tmpx + last_tmpx) / 2 > x) {
2779                 tmpx = last_tmpx;
2780                 left_side = true;
2781         }
2782
2783         if (vc > last + 1)  // This shouldn't happen.
2784                 vc = last + 1;
2785
2786         boundary = false;
2787         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
2788                                          // some speedup if rtl_support=false
2789                 && (!row->next() || row->next()->par() != row->par());
2790         bool const rtl = (lastrow)
2791                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
2792                 : false; // If lastrow is false, we don't need to compute
2793                          // the value of rtl.
2794
2795         if (lastrow &&
2796                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
2797                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
2798                 c = last + 1;
2799         else if (vc == row->pos()) {
2800                 c = vis2log(vc);
2801                 if (bidi_level(c) % 2 == 1)
2802                         ++c;
2803         } else {
2804                 c = vis2log(vc - 1);
2805                 bool const rtl = (bidi_level(c) % 2 == 1);
2806                 if (left_side == rtl) {
2807                         ++c;
2808                         boundary = isBoundary(bview->buffer(), row->par(), c);
2809                 }
2810         }
2811
2812         if (row->pos() <= last && c > last
2813             && row->par()->isNewline(last)) {
2814                 if (bidi_level(last) % 2 == 0)
2815                         tmpx -= singleWidth(bview, row->par(), last);
2816                 else
2817                         tmpx += singleWidth(bview, row->par(), last);
2818                 c = last;
2819         }
2820
2821         c -= row->pos();
2822         x = int(tmpx);
2823         return c;
2824 }
2825
2826
2827 // returns pointer to a specified row
2828 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
2829 {
2830         if (!firstrow)
2831                 return 0;
2832
2833         Row * tmprow = firstrow;
2834         y = 0;
2835
2836         // find the first row of the specified paragraph
2837         while (tmprow->next() && tmprow->par() != par) {
2838                 y += tmprow->height();
2839                 tmprow = tmprow->next();
2840         }
2841
2842         // now find the wanted row
2843         while (tmprow->pos() < pos
2844                && tmprow->next()
2845                && tmprow->next()->par() == par
2846                && tmprow->next()->pos() <= pos) {
2847                 y += tmprow->height();
2848                 tmprow = tmprow->next();
2849         }
2850
2851         return tmprow;
2852 }
2853
2854
2855 Row * LyXText::getRowNearY(int & y) const
2856 {
2857 #if 1
2858         // If possible we should optimize this method. (Lgb)
2859         Row * tmprow = firstrow;
2860         int tmpy = 0;
2861
2862         while (tmprow->next() && tmpy + tmprow->height() <= y) {
2863                 tmpy += tmprow->height();
2864                 tmprow = tmprow->next();
2865         }
2866
2867         y = tmpy;   // return the real y
2868
2869         //lyxerr << "returned y = " << y << endl;
2870
2871         return tmprow;
2872 #else
2873         // Search from the current cursor position.
2874
2875         Row * tmprow = cursor.row();
2876         int tmpy = cursor.y() - tmprow->baseline();
2877
2878         lyxerr << "cursor.y() = " << tmpy << endl;
2879         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
2880         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
2881         lyxerr << "first = " << first << endl;
2882         lyxerr << "y = " << y << endl;
2883
2884         if (y < tmpy) {
2885                 lyxerr << "up" << endl;
2886                 do {
2887                         tmpy -= tmprow->height();
2888                         tmprow = tmprow->previous();
2889                 } while (tmprow && tmpy - tmprow->height() >= y);
2890         } else if (y > tmpy) {
2891                 lyxerr << "down" << endl;
2892
2893                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
2894                         tmpy += tmprow->height();
2895                         tmprow = tmprow->next();
2896                 }
2897         } else {
2898                 lyxerr << "equal" << endl;
2899         }
2900
2901         y = tmpy; // return the real y
2902
2903         lyxerr << "returned y = " << y << endl;
2904
2905         return tmprow;
2906
2907 #endif
2908 }
2909
2910
2911 int LyXText::getDepth() const
2912 {
2913         return cursor.par()->getDepth();
2914 }