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