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