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