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