]> git.lyx.org Git - lyx.git/blob - src/text.C
5a92855c3f06483609cbe1bf0fcfbf11186e0c68
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "buffer.h"
22 #include "bufferparams.h"
23 #include "BufferView.h"
24 #include "debug.h"
25 #include "encoding.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "language.h"
29 #include "LColor.h"
30 #include "lyxlength.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lyxrow_funcs.h"
34 #include "metricsinfo.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "rowpainter.h"
39 #include "text_funcs.h"
40 #include "undo.h"
41 #include "vspace.h"
42 #include "WordLangTuple.h"
43
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46
47 #include "insets/insettext.h"
48
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
51
52 using bv_funcs::number;
53
54 using lyx::pos_type;
55 using lyx::word_location;
56
57 using lyx::support::contains;
58 using lyx::support::lowercase;
59 using lyx::support::uppercase;
60
61 using std::max;
62 using std::endl;
63 using std::string;
64
65
66 /// top, right, bottom pixel margin
67 extern int const PAPER_MARGIN = 20;
68 /// margin for changebar
69 extern int const CHANGEBAR_MARGIN = 10;
70 /// left margin
71 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
72
73
74
75 int bibitemMaxWidth(BufferView *, LyXFont const &);
76
77
78 namespace {
79
80 unsigned int maxParagraphWidth(ParagraphList const & plist)
81 {
82         unsigned int width = 0;
83         ParagraphList::const_iterator pit = plist.begin();
84         ParagraphList::const_iterator end = plist.end();
85                 for (; pit != end; ++pit)
86                         width = std::max(width, pit->width);
87         return width;
88 }
89
90 } // namespace anon
91
92
93 BufferView * LyXText::bv()
94 {
95         BOOST_ASSERT(bv_owner != 0);
96         return bv_owner;
97 }
98
99
100 BufferView * LyXText::bv() const
101 {
102         BOOST_ASSERT(bv_owner != 0);
103         return bv_owner;
104 }
105
106
107 void LyXText::updateRowPositions()
108 {
109         ParagraphList::iterator pit = ownerParagraphs().begin();
110         ParagraphList::iterator end = ownerParagraphs().end();
111         for (height = 0; pit != end; ++pit) {
112                 pit->y = height;
113                 height += pit->height;
114         }
115 }
116
117
118 int LyXText::workWidth() const
119 {
120         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
121 }
122
123
124 int LyXText::getRealCursorX() const
125 {
126         int x = cursor.x();
127         if (the_locking_inset && the_locking_inset->getLyXText(bv()) != this)
128                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
129         return x;
130 }
131
132
133 #warning FIXME  This function seems to belong outside of LyxText.
134 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
135                                      pos_type pos) const
136 {
137         if (!Encodings::is_arabic(c))
138                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
139                         return c + (0xb0 - '0');
140                 else
141                         return c;
142
143         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
144         unsigned char next_char = ' ';
145
146         pos_type const par_size = par.size();
147
148         for (pos_type i = pos + 1; i < par_size; ++i) {
149                 unsigned char const par_char = par.getChar(i);
150                 if (!Encodings::IsComposeChar_arabic(par_char)) {
151                         next_char = par_char;
152                         break;
153                 }
154         }
155
156         if (Encodings::is_arabic(next_char)) {
157                 if (Encodings::is_arabic(prev_char) &&
158                         !Encodings::is_arabic_special(prev_char))
159                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
160                 else
161                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
162         } else {
163                 if (Encodings::is_arabic(prev_char) &&
164                         !Encodings::is_arabic_special(prev_char))
165                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
166                 else
167                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
168         }
169 }
170
171 // This is the comments that some of the warnings below refers to.
172 // There are some issues in this file and I don't think they are
173 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
174 // this is a problem that has been here almost from day one and that a
175 // larger userbase with different access patters triggers the bad
176 // behaviour. (segfaults.) What I think happen is: In several places
177 // we store the paragraph in the current cursor and then moves the
178 // cursor. This movement of the cursor will delete paragraph at the
179 // old position if it is now empty. This will make the temporary
180 // pointer to the old cursor paragraph invalid and dangerous to use.
181 // And is some cases this will trigger a segfault. I have marked some
182 // of the cases where this happens with a warning, but I am sure there
183 // are others in this file and in text2.C. There is also a note in
184 // Delete() that you should read. In Delete I store the paragraph->id
185 // instead of a pointer to the paragraph. I am pretty sure this faulty
186 // use of temporary pointers to paragraphs that might have gotten
187 // invalidated (through a cursor movement) before they are used, are
188 // the cause of the strange crashes we get reported often.
189 //
190 // It is very tiresom to change this code, especially when it is as
191 // hard to read as it is. Help to fix all the cases where this is done
192 // would be greately appreciated.
193 //
194 // Lgb
195
196 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
197 {
198         if (pos >= pit->size())
199                 return 0;
200
201         char const c = pit->getChar(pos);
202         LyXFont const & font = getFont(pit, pos);
203         return singleWidth(pit, pos, c, font);
204 }
205
206
207 int LyXText::singleWidth(ParagraphList::iterator pit,
208                          pos_type pos, char c, LyXFont const & font) const
209 {
210         if (pos >= pit->size()) {
211                 lyxerr << "in singleWidth(), pos: " << pos << endl;
212                 BOOST_ASSERT(false);
213                 return 0;
214         }
215
216
217         // The most common case is handled first (Asger)
218         if (IsPrintable(c)) {
219                 if (!font.language()->RightToLeft()) {
220                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
221                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
222                             && font.language()->lang() == "arabic") {
223                                 if (Encodings::IsComposeChar_arabic(c))
224                                         return 0;
225                                 else
226                                         c = transformChar(c, *pit, pos);
227                         } else if (font.language()->lang() == "hebrew" &&
228                                  Encodings::IsComposeChar_hebrew(c))
229                                 return 0;
230                 }
231                 return font_metrics::width(c, font);
232         }
233
234         if (c == Paragraph::META_INSET) {
235                 InsetOld * tmpinset = pit->getInset(pos);
236                 BOOST_ASSERT(tmpinset);
237                 if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
238                         // Because of the representation as vertical lines
239                         return 3;
240                 }
241                 return tmpinset->width();
242         }
243
244         if (IsSeparatorChar(c))
245                 c = ' ';
246         return font_metrics::width(c, font);
247 }
248
249
250 int LyXText::leftMargin(ParagraphList::iterator pit, Row const & row) const
251 {
252         LyXTextClass const & tclass =
253                 bv()->buffer()->params().getLyXTextClass();
254         LyXLayout_ptr const & layout = pit->layout();
255
256         string parindent = layout->parindent;
257
258         int x = LEFT_MARGIN;
259
260         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
261
262         // this is the way, LyX handles the LaTeX-Environments.
263         // I have had this idea very late, so it seems to be a
264         // later added hack and this is true
265         if (!pit->getDepth()) {
266                 if (pit->layout() == tclass.defaultLayout()) {
267                         // find the previous same level paragraph
268                         if (pit != ownerParagraphs().begin()) {
269                                 ParagraphList::iterator newpit =
270                                         depthHook(pit, ownerParagraphs(),
271                                                   pit->getDepth());
272                                 if (newpit == pit &&
273                                     newpit->layout()->nextnoindent)
274                                         parindent.erase();
275                         }
276                 }
277         } else {
278                 // find the next level paragraph
279
280                 ParagraphList::iterator newpar = outerHook(pit,
281                                                            ownerParagraphs());
282
283                 // make a corresponding row. Needed to call leftMargin()
284
285                 // check wether it is a sufficent paragraph
286                 if (newpar != ownerParagraphs().end() &&
287                     newpar->layout()->isEnvironment()) {
288                         x = leftMargin(newpar, Row(newpar->size()));
289                 }
290
291                 if (newpar != ownerParagraphs().end() &&
292                     pit->layout() == tclass.defaultLayout()) {
293                         if (newpar->params().noindent())
294                                 parindent.erase();
295                         else {
296                                 parindent = newpar->layout()->parindent;
297                         }
298
299                 }
300         }
301
302         LyXFont const labelfont = getLabelFont(pit);
303         switch (layout->margintype) {
304         case MARGIN_DYNAMIC:
305                 if (!layout->leftmargin.empty()) {
306                         x += font_metrics::signedWidth(layout->leftmargin,
307                                                   tclass.defaultfont());
308                 }
309                 if (!pit->getLabelstring().empty()) {
310                         x += font_metrics::signedWidth(layout->labelindent,
311                                                   labelfont);
312                         x += font_metrics::width(pit->getLabelstring(),
313                                             labelfont);
314                         x += font_metrics::width(layout->labelsep, labelfont);
315                 }
316                 break;
317         case MARGIN_MANUAL:
318                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
319                 // The width of an empty par, even with manual label, should be 0
320                 if (!pit->empty() && row.pos() >= pit->beginningOfBody()) {
321                         if (!pit->getLabelWidthString().empty()) {
322                                 x += font_metrics::width(pit->getLabelWidthString(),
323                                                labelfont);
324                                 x += font_metrics::width(layout->labelsep, labelfont);
325                         }
326                 }
327                 break;
328         case MARGIN_STATIC:
329                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
330                         / (pit->getDepth() + 4);
331                 break;
332         case MARGIN_FIRST_DYNAMIC:
333                 if (layout->labeltype == LABEL_MANUAL) {
334                         if (row.pos() >= pit->beginningOfBody()) {
335                                 x += font_metrics::signedWidth(layout->leftmargin,
336                                                           labelfont);
337                         } else {
338                                 x += font_metrics::signedWidth(layout->labelindent,
339                                                           labelfont);
340                         }
341                 } else if (row.pos()
342                            // Special case to fix problems with
343                            // theorems (JMarc)
344                            || (layout->labeltype == LABEL_STATIC
345                                && layout->latextype == LATEX_ENVIRONMENT
346                                && !isFirstInSequence(pit, ownerParagraphs()))) {
347                         x += font_metrics::signedWidth(layout->leftmargin,
348                                                   labelfont);
349                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
350                            && layout->labeltype != LABEL_BIBLIO
351                            && layout->labeltype !=
352                            LABEL_CENTERED_TOP_ENVIRONMENT) {
353                         x += font_metrics::signedWidth(layout->labelindent,
354                                                   labelfont);
355                         x += font_metrics::width(layout->labelsep, labelfont);
356                         x += font_metrics::width(pit->getLabelstring(),
357                                             labelfont);
358                 }
359                 break;
360
361         case MARGIN_RIGHT_ADDRESS_BOX:
362         {
363                 // ok, a terrible hack. The left margin depends on the widest
364                 // row in this paragraph.
365                 RowList::iterator rit = pit->rows.begin();
366                 RowList::iterator end = pit->rows.end();
367 #warning This is wrong.
368                 int minfill = workWidth() / 2;
369                 for ( ; rit != end; ++rit)
370                         if (rit->fill() < minfill)
371                                 minfill = rit->fill();
372                 x += font_metrics::signedWidth(layout->leftmargin,
373                         tclass.defaultfont());
374                 x += minfill;
375         }
376         break;
377         }
378
379         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
380                 LyXLength const len = pit->params().leftIndent();
381                 int const tw = inset_owner ?
382                         inset_owner->latexTextWidth(bv()) : workWidth();
383                 x += len.inPixels(tw);
384         }
385
386         LyXAlignment align;
387
388         if (pit->params().align() == LYX_ALIGN_LAYOUT)
389                 align = layout->align;
390         else
391                 align = pit->params().align();
392
393         // set the correct parindent
394         if (row.pos() == 0) {
395                 if ((layout->labeltype == LABEL_NO_LABEL
396                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
397                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
398                      || (layout->labeltype == LABEL_STATIC
399                          && layout->latextype == LATEX_ENVIRONMENT
400                          && !isFirstInSequence(pit, ownerParagraphs())))
401                     && align == LYX_ALIGN_BLOCK
402                     && !pit->params().noindent()
403                         // in tabulars and ert paragraphs are never indented!
404                         && (!pit->inInset() || !pit->inInset()->owner() ||
405                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
406                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
407                     && (pit->layout() != tclass.defaultLayout() ||
408                         bv()->buffer()->params().paragraph_separation ==
409                         BufferParams::PARSEP_INDENT)) {
410                         x += font_metrics::signedWidth(parindent,
411                                                   tclass.defaultfont());
412                 } else if (layout->labeltype == LABEL_BIBLIO) {
413                         // ale970405 Right width for bibitems
414                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
415                 }
416         }
417
418         return x;
419 }
420
421
422 int LyXText::rightMargin(Paragraph const & par,
423         Buffer const & buf, Row const &) const
424 {
425         LyXTextClass const & tclass = buf.params().getLyXTextClass();
426         LyXLayout_ptr const & layout = par.layout();
427
428         return PAPER_MARGIN
429                 + font_metrics::signedWidth(tclass.rightmargin(),
430                                        tclass.defaultfont())
431                 + font_metrics::signedWidth(layout->rightmargin,
432                                        tclass.defaultfont())
433                 * 4 / (par.getDepth() + 4);
434 }
435
436
437 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
438 {
439         if (pit->layout()->margintype == MARGIN_MANUAL) {
440                 Row tmprow = row;
441                 tmprow.pos(pit->size());
442                 // return the beginning of the body
443                 return leftMargin(pit, tmprow);
444         }
445
446         // LabelEnd is only needed if the layout
447         // fills a flushleft label.
448         return 0;
449 }
450
451
452 namespace {
453
454 // this needs special handling - only newlines count as a break point
455 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
456 {
457         pos_type const end = par.size();
458         
459         for (; i < end; ++i)
460                 if (par.isNewline(i))
461                         return i + 1;
462
463         return end;
464 }
465
466 };
467
468
469 void LyXText::rowBreakPoint(ParagraphList::iterator pit, Row & row) const
470 {
471         pos_type const end = pit->size();
472         pos_type const pos = row.pos();
473         if (pos == end) {
474                 row.endpos(end);
475                 return;
476         }
477         
478         // maximum pixel width of a row.
479         int width = workWidth()
480                 - rightMargin(*pit, *bv()->buffer(), row);
481 //              - leftMargin(pit, row);
482
483         // inset->textWidth() returns -1 via workWidth(),
484         // but why ?
485         if (width < 0) {
486                 row.endpos(end);
487                 return;
488         }
489
490         LyXLayout_ptr const & layout = pit->layout();
491
492         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
493                 row.endpos(addressBreakPoint(pos, *pit));
494                 return;
495         }
496
497         pos_type const body_pos = pit->beginningOfBody();
498
499
500         // Now we iterate through until we reach the right margin
501         // or the end of the par, then choose the possible break
502         // nearest that.
503
504         int const left = leftMargin(pit, row);
505         int x = left;
506
507         // pixel width since last breakpoint
508         int chunkwidth = 0;
509
510         // We re-use the font resolution for the entire font span when possible
511         LyXFont font = getFont(pit, pos);
512         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(pos);
513
514         pos_type point = end;
515         pos_type i = pos;
516         for ( ; i < end; ++i) {
517                 if (pit->isNewline(i)) {
518                         point = i + 1;
519                         break;
520                 }
521                 // Break before...      
522                 if (i + 1 < end) {
523                         InsetOld * in = pit->getInset(i + 1);
524                         if (in && in->display()) {
525                                 point = i + 1;
526                                 break;
527                         }
528                         // ...and after.
529                         in = pit->getInset(i);
530                         if (in && in->display()) {
531                                 point = i + 1;
532                                 break;
533                         }
534                 }
535
536                 char const c = pit->getChar(i);
537                 if (i > endPosOfFontSpan) {
538                         font = getFont(pit, i);
539                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
540                 }
541                 
542                 {
543                         int thiswidth = singleWidth(pit, i, c, font);
544
545                         // add the auto-hfill from label end to the body
546                         if (body_pos && i == body_pos) {
547                                 int add = font_metrics::width(layout->labelsep, getLabelFont(pit));
548                                 if (pit->isLineSeparator(i - 1))
549                                         add -= singleWidth(pit, i - 1);
550
551                                 add = std::max(add, labelEnd(pit, row) - x);
552                                 thiswidth += add;
553                         }
554
555                         x += thiswidth;
556                         //lyxerr << "i: " << i << " x: "
557                         //<< x << " width: " << width << endl;
558                         chunkwidth += thiswidth;
559                 }
560                 
561
562                 // break before a character that will fall off
563                 // the right of the row
564                 if (x >= width) {
565                         // if no break before, break here
566                         if (point == end || chunkwidth >= width - left) {
567                                 if (i > pos) {
568                                         point = i;
569                                         break;  
570                                 }
571                         }
572                         // exit on last registered breakpoint:
573                         if (i + 1 < end)
574                                 break;  
575                 }
576
577                 InsetOld * in = pit->getInset(i);
578                 if (!in || in->isChar()) {
579                         // some insets are line separators too
580                         if (pit->isLineSeparator(i)) {
581                                 // register breakpoint:
582                                 point = i + 1; 
583                                 chunkwidth = 0;
584                         }
585                 }
586         }
587
588         if (point == end && i != end && x >= width) {
589                 // didn't find one, break at the point we reached the edge
590                 point = i + 1;
591         } else if (i == end && x < width) {
592                 // maybe found one, but the par is short enough.
593                 point = end;
594         }
595
596         // manual labels cannot be broken in LaTeX. But we
597         // want to make our on-screen rendering of footnotes
598         // etc. still break
599         if (body_pos && point < body_pos)
600                 point = body_pos;
601
602         row.endpos(point);
603 }
604
605
606 // returns the minimum space a row needs on the screen in pixel
607 void LyXText::fill(ParagraphList::iterator pit, Row & row, int paper_width) const
608 {
609         int w;
610         // get the pure distance
611         pos_type const last = lastPos(*pit, row);
612
613         LyXLayout_ptr const & layout = pit->layout();
614
615         // special handling of the right address boxes
616         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
617                 int const tmpfill = row.fill();
618                 row.fill(0); // the minfill in leftMargin()
619                 w = leftMargin(pit, row);
620                 row.fill(tmpfill);
621         } else {
622                 w = leftMargin(pit, row);
623         }
624
625         pos_type const body_pos = pit->beginningOfBody();
626         pos_type i = row.pos();
627
628         if (! pit->empty() && i <= last) {
629                 // We re-use the font resolution for the entire span when possible
630                 LyXFont font = getFont(pit, i);
631                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
632                 while (i <= last) {
633                         if (body_pos > 0 && i == body_pos) {
634                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
635                                 if (pit->isLineSeparator(i - 1))
636                                         w -= singleWidth(pit, i - 1);
637                                 int left_margin = labelEnd(pit, row);
638                                 if (w < left_margin)
639                                         w = left_margin;
640                         }
641                         char const c = pit->getChar(i);
642                         if (IsPrintable(c) && i > endPosOfFontSpan) {
643                                 // We need to get the next font
644                                 font = getFont(pit, i);
645                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
646                         }
647                         w += singleWidth(pit, i, c, font);
648                         ++i;
649                 }
650         }
651         if (body_pos > 0 && body_pos > last) {
652                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
653                 if (last >= 0 && pit->isLineSeparator(last))
654                         w -= singleWidth(pit, last);
655                 int const left_margin = labelEnd(pit, row);
656                 if (w < left_margin)
657                         w = left_margin;
658         }
659
660         int const fill = paper_width - w - rightMargin(*pit, *bv()->buffer(), row);
661         row.fill(fill);
662         row.width(paper_width - fill);
663 }
664
665
666 // returns the minimum space a manual label needs on the screen in pixel
667 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
668 {
669         pos_type last = pit->beginningOfBody();
670
671         BOOST_ASSERT(last > 0);
672
673         // -1 because a label ends with a space that is in the label
674         --last;
675
676         // a separator at this end does not count
677         if (pit->isLineSeparator(last))
678                 --last;
679
680         int w = 0;
681         for (pos_type i = row.pos(); i <= last; ++i)
682                 w += singleWidth(pit, i);
683
684         int fill = 0;
685         string const & labwidstr = pit->params().labelWidthString();
686         if (!labwidstr.empty()) {
687                 LyXFont const labfont = getLabelFont(pit);
688                 int const labwidth = font_metrics::width(labwidstr, labfont);
689                 fill = max(labwidth - w, 0);
690         }
691
692         return fill;
693 }
694
695
696 LColor_color LyXText::backgroundColor() const
697 {
698         if (inset_owner)
699                 return inset_owner->backgroundColor();
700         else
701                 return LColor::background;
702 }
703
704
705 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
706 {
707         // get the maximum ascent and the maximum descent
708         double layoutasc = 0;
709         double layoutdesc = 0;
710         double tmptop = 0;
711
712         // ok, let us initialize the maxasc and maxdesc value.
713         // Only the fontsize count. The other properties
714         // are taken from the layoutfont. Nicer on the screen :)
715         LyXLayout_ptr const & layout = pit->layout();
716
717         // as max get the first character of this row then it can increase but not
718         // decrease the height. Just some point to start with so we don't have to
719         // do the assignment below too often.
720         LyXFont font = getFont(pit, row.pos());
721         LyXFont::FONT_SIZE const tmpsize = font.size();
722         font = getLayoutFont(pit);
723         LyXFont::FONT_SIZE const size = font.size();
724         font.setSize(tmpsize);
725
726         LyXFont labelfont = getLabelFont(pit);
727
728         double spacing_val = 1.0;
729         if (!pit->params().spacing().isDefault())
730                 spacing_val = pit->params().spacing().getValue();
731         else
732                 spacing_val = bv()->buffer()->params().spacing().getValue();
733         //lyxerr << "spacing_val = " << spacing_val << endl;
734
735         // these are minimum values
736         int maxasc  = int(font_metrics::maxAscent(font) *
737                           layout->spacing.getValue() * spacing_val);
738         int maxdesc = int(font_metrics::maxDescent(font) *
739                           layout->spacing.getValue() * spacing_val);
740
741         // insets may be taller
742         InsetList::iterator ii = pit->insetlist.begin();
743         InsetList::iterator iend = pit->insetlist.end();
744         for ( ; ii != iend; ++ii) {
745                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
746                         maxasc = max(maxasc, ii->inset->ascent());
747                         maxdesc = max(maxdesc, ii->inset->descent());
748                 }
749         }
750
751         // Check if any custom fonts are larger (Asger)
752         // This is not completely correct, but we can live with the small,
753         // cosmetic error for now.
754         int labeladdon = 0;
755         pos_type const pos_end = lastPos(*pit, row);
756
757         LyXFont::FONT_SIZE maxsize =
758                 pit->highestFontInRange(row.pos(), pos_end, size);
759         if (maxsize > font.size()) {
760                 font.setSize(maxsize);
761                 maxasc = max(maxasc, font_metrics::maxAscent(font));
762                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
763         }
764
765         // This is nicer with box insets:
766         ++maxasc;
767         ++maxdesc;
768
769         row.ascent_of_text(maxasc);
770
771         // is it a top line?
772         if (!row.pos()) {
773                 BufferParams const & bufparams = bv()->buffer()->params();
774                 // some parksips VERY EASY IMPLEMENTATION
775                 if (bv()->buffer()->params().paragraph_separation ==
776                         BufferParams::PARSEP_SKIP)
777                 {
778                         if (layout->isParagraph()
779                                 && pit->getDepth() == 0
780                                 && pit != ownerParagraphs().begin())
781                         {
782                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
783                         } else if (pit != ownerParagraphs().begin() &&
784                                    boost::prior(pit)->layout()->isParagraph() &&
785                                    boost::prior(pit)->getDepth() == 0)
786                         {
787                                 // is it right to use defskip here too? (AS)
788                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
789                         }
790                 }
791
792                 // the top margin
793                 if (pit == ownerParagraphs().begin() && !isInInset())
794                         maxasc += PAPER_MARGIN;
795
796                 // add the vertical spaces, that the user added
797                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
798
799                 // do not forget the DTP-lines!
800                 // there height depends on the font of the nearest character
801                 if (pit->params().lineTop())
802
803                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
804                 // and now the pagebreaks
805                 if (pit->params().pagebreakTop())
806                         maxasc += 3 * defaultRowHeight();
807
808                 if (pit->params().startOfAppendix())
809                         maxasc += 3 * defaultRowHeight();
810
811                 // This is special code for the chapter, since the label of this
812                 // layout is printed in an extra row
813                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
814                         float spacing_val = 1.0;
815                         if (!pit->params().spacing().isDefault()) {
816                                 spacing_val = pit->params().spacing().getValue();
817                         } else {
818                                 spacing_val = bufparams.spacing().getValue();
819                         }
820
821                         labeladdon = int(font_metrics::maxDescent(labelfont) *
822                                          layout->spacing.getValue() *
823                                          spacing_val)
824                                 + int(font_metrics::maxAscent(labelfont) *
825                                       layout->spacing.getValue() *
826                                       spacing_val);
827                 }
828
829                 // special code for the top label
830                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
831                      || layout->labeltype == LABEL_BIBLIO
832                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
833                     && isFirstInSequence(pit, ownerParagraphs())
834                     && !pit->getLabelstring().empty())
835                 {
836                         float spacing_val = 1.0;
837                         if (!pit->params().spacing().isDefault()) {
838                                 spacing_val = pit->params().spacing().getValue();
839                         } else {
840                                 spacing_val = bufparams.spacing().getValue();
841                         }
842
843                         labeladdon = int(
844                                 (font_metrics::maxAscent(labelfont) +
845                                  font_metrics::maxDescent(labelfont)) *
846                                   layout->spacing.getValue() *
847                                   spacing_val
848                                 + layout->topsep * defaultRowHeight()
849                                 + layout->labelbottomsep * defaultRowHeight());
850                 }
851
852                 // And now the layout spaces, for example before and after
853                 // a section, or between the items of a itemize or enumerate
854                 // environment.
855
856                 if (!pit->params().pagebreakTop()) {
857                         ParagraphList::iterator prev =
858                                 depthHook(pit, ownerParagraphs(),
859                                           pit->getDepth());
860                         if (prev != pit && prev->layout() == layout &&
861                                 prev->getDepth() == pit->getDepth() &&
862                                 prev->getLabelWidthString() == pit->getLabelWidthString())
863                         {
864                                 layoutasc = (layout->itemsep * defaultRowHeight());
865                         } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
866                                 tmptop = layout->topsep;
867
868                                 if (tmptop > 0)
869                                         layoutasc = (tmptop * defaultRowHeight());
870                         } else if (pit->params().lineTop()) {
871                                 tmptop = layout->topsep;
872
873                                 if (tmptop > 0)
874                                         layoutasc = (tmptop * defaultRowHeight());
875                         }
876
877                         prev = outerHook(pit, ownerParagraphs());
878                         if (prev != ownerParagraphs().end())  {
879                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
880                         } else if (pit != ownerParagraphs().begin()) {
881                                 ParagraphList::iterator prior_pit = boost::prior(pit);
882                                 if (prior_pit->getDepth() != 0 ||
883                                     prior_pit->layout() == layout) {
884                                         maxasc += int(layout->parsep * defaultRowHeight());
885                                 }
886                         }
887                 }
888         }
889
890         // is it a bottom line?
891         if (row.endpos() >= pit->size()) {
892                 // the bottom margin
893                 ParagraphList::iterator nextpit = boost::next(pit);
894                 if (nextpit == ownerParagraphs().end() && !isInInset())
895                         maxdesc += PAPER_MARGIN;
896
897                 // add the vertical spaces, that the user added
898                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
899
900                 // do not forget the DTP-lines!
901                 // there height depends on the font of the nearest character
902                 if (pit->params().lineBottom())
903                         maxdesc += 2 * font_metrics::ascent('x',
904                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
905
906                 // and now the pagebreaks
907                 if (pit->params().pagebreakBottom())
908                         maxdesc += 3 * defaultRowHeight();
909
910                 // and now the layout spaces, for example before and after
911                 // a section, or between the items of a itemize or enumerate
912                 // environment
913                 if (!pit->params().pagebreakBottom()
914                     && nextpit != ownerParagraphs().end()) {
915                         ParagraphList::iterator comparepit = pit;
916                         float usual = 0;
917                         float unusual = 0;
918
919                         if (comparepit->getDepth() > nextpit->getDepth()) {
920                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
921                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
922                                 if (comparepit->layout()!= nextpit->layout()
923                                         || nextpit->getLabelWidthString() !=
924                                         comparepit->getLabelWidthString())
925                                 {
926                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
927                                 }
928                                 if (unusual > usual)
929                                         layoutdesc = unusual;
930                                 else
931                                         layoutdesc = usual;
932                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
933
934                                 if (comparepit->layout() != nextpit->layout()
935                                         || nextpit->getLabelWidthString() !=
936                                         comparepit->getLabelWidthString())
937                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
938                         }
939                 }
940         }
941
942         // incalculate the layout spaces
943         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
944         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
945
946         row.height(maxasc + maxdesc + labeladdon);
947         row.baseline(maxasc + labeladdon);
948         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
949 }
950
951
952 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
953 {
954         // allow only if at start or end, or all previous is new text
955         ParagraphList::iterator cpit = cursorPar();
956         if (cursor.pos() && cursor.pos() != cpit->size()
957             && cpit->isChangeEdited(0, cursor.pos()))
958                 return;
959
960         LyXTextClass const & tclass =
961                 bv()->buffer()->params().getLyXTextClass();
962         LyXLayout_ptr const & layout = cpit->layout();
963
964         // this is only allowed, if the current paragraph is not empty or caption
965         // and if it has not the keepempty flag active
966         if (cpit->empty() && !cpit->allowEmpty()
967            && layout->labeltype != LABEL_SENSITIVE)
968                 return;
969
970         recUndo(cursor.par());
971
972         // Always break behind a space
973         //
974         // It is better to erase the space (Dekel)
975         if (cursor.pos() < cpit->size() && cpit->isLineSeparator(cursor.pos()))
976            cpit->erase(cursor.pos());
977
978         // break the paragraph
979         if (keep_layout)
980                 keep_layout = 2;
981         else
982                 keep_layout = layout->isEnvironment();
983
984         // we need to set this before we insert the paragraph. IMO the
985         // breakParagraph call should return a bool if it inserts the
986         // paragraph before or behind and we should react on that one
987         // but we can fix this in 1.3.0 (Jug 20020509)
988         bool const isempty = cpit->allowEmpty() && cpit->empty();
989         ::breakParagraph(bv()->buffer()->params(), paragraphs, cpit,
990                          cursor.pos(), keep_layout);
991
992 #warning Trouble Point! (Lgb)
993         // When ::breakParagraph is called from within an inset we must
994         // ensure that the correct ParagraphList is used. Today that is not
995         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
996         cpit = cursorPar();
997         ParagraphList::iterator next_par = boost::next(cpit);
998
999         // well this is the caption hack since one caption is really enough
1000         if (layout->labeltype == LABEL_SENSITIVE) {
1001                 if (!cursor.pos())
1002                         // set to standard-layout
1003                         cpit->applyLayout(tclass.defaultLayout());
1004                 else
1005                         // set to standard-layout
1006                         next_par->applyLayout(tclass.defaultLayout());
1007         }
1008
1009         // if the cursor is at the beginning of a row without prior newline,
1010         // move one row up!
1011         // This touches only the screen-update. Otherwise we would may have
1012         // an empty row on the screen
1013         RowList::iterator crit = cpit->getRow(cursor.pos());
1014         if (cursor.pos() && crit->pos() == cursor.pos()
1015             && !cpit->isNewline(cursor.pos() - 1))
1016         {
1017                 cursorLeft(bv());
1018         }
1019
1020         while (!next_par->empty() && next_par->isNewline(0))
1021                 next_par->erase(0);
1022
1023         updateCounters();
1024         redoParagraph(cpit);
1025         redoParagraph(next_par);
1026
1027         // This check is necessary. Otherwise the new empty paragraph will
1028         // be deleted automatically. And it is more friendly for the user!
1029         if (cursor.pos() || isempty)
1030                 setCursor(next_par, 0);
1031         else
1032                 setCursor(cpit, 0);
1033 }
1034
1035
1036 // convenience function
1037 void LyXText::redoParagraph()
1038 {
1039         clearSelection();
1040         redoParagraph(cursorPar());
1041         setCursorIntern(cursor.par(), cursor.pos());
1042 }
1043
1044
1045 // insert a character, moves all the following breaks in the
1046 // same Paragraph one to the right and make a rebreak
1047 void LyXText::insertChar(char c)
1048 {
1049         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
1050
1051         // When the free-spacing option is set for the current layout,
1052         // disable the double-space checking
1053
1054         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
1055                 cursorPar()->isFreeSpacing();
1056
1057         if (lyxrc.auto_number) {
1058                 static string const number_operators = "+-/*";
1059                 static string const number_unary_operators = "+-";
1060                 static string const number_seperators = ".,:";
1061
1062                 if (current_font.number() == LyXFont::ON) {
1063                         if (!IsDigit(c) && !contains(number_operators, c) &&
1064                             !(contains(number_seperators, c) &&
1065                               cursor.pos() >= 1 &&
1066                               cursor.pos() < cursorPar()->size() &&
1067                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
1068                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
1069                            )
1070                                 number(bv()); // Set current_font.number to OFF
1071                 } else if (IsDigit(c) &&
1072                            real_current_font.isVisibleRightToLeft()) {
1073                         number(bv()); // Set current_font.number to ON
1074
1075                         if (cursor.pos() > 0) {
1076                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
1077                                 if (contains(number_unary_operators, c) &&
1078                                     (cursor.pos() == 1 ||
1079                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
1080                                      cursorPar()->isNewline(cursor.pos() - 2))
1081                                   ) {
1082                                         setCharFont(
1083                                                     cursorPar(),
1084                                                     cursor.pos() - 1,
1085                                                     current_font);
1086                                 } else if (contains(number_seperators, c) &&
1087                                            cursor.pos() >= 2 &&
1088                                            getFont(
1089                                                    cursorPar(),
1090                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1091                                         setCharFont(
1092                                                     cursorPar(),
1093                                                     cursor.pos() - 1,
1094                                                     current_font);
1095                                 }
1096                         }
1097                 }
1098         }
1099
1100
1101         // First check, if there will be two blanks together or a blank at
1102         // the beginning of a paragraph.
1103         // I decided to handle blanks like normal characters, the main
1104         // difference are the special checks when calculating the row.fill
1105         // (blank does not count at the end of a row) and the check here
1106
1107         // The bug is triggered when we type in a description environment:
1108         // The current_font is not changed when we go from label to main text
1109         // and it should (along with realtmpfont) when we type the space.
1110         // CHECK There is a bug here! (Asger)
1111
1112         // store the current font.  This is because of the use of cursor
1113         // movements. The moving cursor would refresh the current font
1114         LyXFont realtmpfont = real_current_font;
1115         LyXFont rawtmpfont = current_font;
1116
1117         if (!freeSpacing && IsLineSeparatorChar(c)) {
1118                 if ((cursor.pos() > 0
1119                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
1120                     || (cursor.pos() > 0
1121                         && cursorPar()->isNewline(cursor.pos() - 1))
1122                     || (cursor.pos() == 0)) {
1123                         static bool sent_space_message = false;
1124                         if (!sent_space_message) {
1125                                 if (cursor.pos() == 0)
1126                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1127                                 else
1128                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1129                                 sent_space_message = true;
1130                         }
1131                         charInserted();
1132                         return;
1133                 }
1134         }
1135
1136         // Here case LyXText::InsertInset already inserted the character
1137         if (c != Paragraph::META_INSET)
1138                 cursorPar()->insertChar(cursor.pos(), c);
1139
1140         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1141
1142         current_font = rawtmpfont;
1143         real_current_font = realtmpfont;
1144         redoParagraph(cursorPar());
1145         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1146
1147         charInserted();
1148 }
1149
1150
1151 void LyXText::charInserted()
1152 {
1153         // Here we could call finishUndo for every 20 characters inserted.
1154         // This is from my experience how emacs does it. (Lgb)
1155         static unsigned int counter;
1156         if (counter < 20) {
1157                 ++counter;
1158         } else {
1159                 finishUndo();
1160                 counter = 0;
1161         }
1162 }
1163
1164
1165 void LyXText::prepareToPrint(ParagraphList::iterator pit, Row & row) const
1166 {
1167         double w = row.fill();
1168         double fill_hfill = 0;
1169         double fill_label_hfill = 0;
1170         double fill_separator = 0;
1171         double x = 0;
1172
1173         bool const is_rtl =
1174                 pit->isRightToLeftPar(bv()->buffer()->params());
1175         if (is_rtl)
1176                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer(), row) : 0;
1177         else
1178                 x = workWidth() > 0 ? leftMargin(pit, row) : 0;
1179
1180         // is there a manual margin with a manual label
1181         LyXLayout_ptr const & layout = pit->layout();
1182
1183         if (layout->margintype == MARGIN_MANUAL
1184             && layout->labeltype == LABEL_MANUAL) {
1185                 /// We might have real hfills in the label part
1186                 int nlh = numberOfLabelHfills(*pit, row);
1187
1188                 // A manual label par (e.g. List) has an auto-hfill
1189                 // between the label text and the body of the
1190                 // paragraph too.
1191                 // But we don't want to do this auto hfill if the par
1192                 // is empty.
1193                 if (!pit->empty())
1194                         ++nlh;
1195
1196                 if (nlh && !pit->getLabelWidthString().empty()) {
1197                         fill_label_hfill = labelFill(pit, row) / double(nlh);
1198                 }
1199         }
1200
1201         // are there any hfills in the row?
1202         int const nh = numberOfHfills(*pit, row);
1203
1204         if (nh) {
1205                 if (w > 0)
1206                         fill_hfill = w / nh;
1207         // we don't have to look at the alignment if it is ALIGN_LEFT and
1208         // if the row is already larger then the permitted width as then
1209         // we force the LEFT_ALIGN'edness!
1210         } else if (int(row.width()) < workWidth()) {
1211                 // is it block, flushleft or flushright?
1212                 // set x how you need it
1213                 int align;
1214                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1215                         align = layout->align;
1216                 } else {
1217                         align = pit->params().align();
1218                 }
1219                 // ERT insets should always be LEFT ALIGNED on screen
1220                 InsetOld * inset = pit->inInset();
1221                 if (inset && inset->owner() &&
1222                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1223                 {
1224                         align = LYX_ALIGN_LEFT;
1225                 }
1226
1227                 // Display-style insets should always be on a centred row
1228                 // The test on pit->size() is to catch zero-size pars, which
1229                 // would trigger the assert in Paragraph::getInset().
1230                 //inset = pit->size() ? pit->getInset(row.pos()) : 0;
1231                 if (!pit->empty()
1232                     && pit->isInset(row.pos())
1233                     && pit->getInset(row.pos())->display())
1234                 {
1235                         align = LYX_ALIGN_CENTER;
1236                 }
1237                 
1238                 switch (align) {
1239             case LYX_ALIGN_BLOCK:
1240                 {
1241                         int const ns = numberOfSeparators(*pit, row);
1242                         bool disp_inset = false;
1243                         if (row.endpos() < pit->size()) {
1244                                 InsetOld * in = pit->getInset(row.endpos());
1245                                 if (in)
1246                                         disp_inset = in->display();
1247                         }
1248                         // If we have separators, this is not the last row of a
1249                         // par, does not end in newline, and is not row above a
1250                         // display inset... then stretch it
1251                         if (ns
1252                                 && row.endpos() < pit->size()
1253                                 && !pit->isNewline(row.endpos() - 1)
1254                                 && !disp_inset
1255                                 ) {
1256                                         fill_separator = w / ns;
1257                         } else if (is_rtl) {
1258                                 x += w;
1259                         }
1260                         break;
1261             }
1262             case LYX_ALIGN_RIGHT:
1263                         x += w;
1264                         break;
1265             case LYX_ALIGN_CENTER:
1266                         x += w / 2;
1267                         break;
1268                 }
1269         }
1270
1271         bidi.computeTables(*pit, *bv()->buffer(), row);
1272         if (is_rtl) {
1273                 pos_type body_pos = pit->beginningOfBody();
1274                 pos_type last = lastPos(*pit, row);
1275
1276                 if (body_pos > 0 &&
1277                                 (body_pos - 1 > last ||
1278                                  !pit->isLineSeparator(body_pos - 1))) {
1279                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1280                         if (body_pos - 1 <= last)
1281                                 x += fill_label_hfill;
1282                 }
1283         }
1284
1285         row.fill_hfill(fill_hfill);
1286         row.fill_label_hfill(fill_label_hfill);
1287         row.fill_separator(fill_separator);
1288         row.x(x);
1289 }
1290
1291
1292 // important for the screen
1293
1294
1295 // the cursor set functions have a special mechanism. When they
1296 // realize, that you left an empty paragraph, they will delete it.
1297 // They also delete the corresponding row
1298
1299 void LyXText::cursorRightOneWord()
1300 {
1301         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1302         setCursor(cursorPar(), cursor.pos());
1303 }
1304
1305
1306 // Skip initial whitespace at end of word and move cursor to *start*
1307 // of prior word, not to end of next prior word.
1308 void LyXText::cursorLeftOneWord()
1309 {
1310         LyXCursor tmpcursor = cursor;
1311         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1312         setCursor(getPar(tmpcursor), tmpcursor.pos());
1313 }
1314
1315
1316 void LyXText::selectWord(word_location loc)
1317 {
1318         LyXCursor from = cursor;
1319         LyXCursor to = cursor;
1320         ::getWord(*this, from, to, loc, ownerParagraphs());
1321         if (cursor != from)
1322                 setCursor(from.par(), from.pos());
1323         if (to == from)
1324                 return;
1325         selection.cursor = cursor;
1326         setCursor(to.par(), to.pos());
1327         setSelection();
1328 }
1329
1330
1331 // Select the word currently under the cursor when no
1332 // selection is currently set
1333 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1334 {
1335         if (!selection.set()) {
1336                 selectWord(loc);
1337                 return selection.set();
1338         }
1339         return false;
1340 }
1341
1342
1343 void LyXText::acceptChange()
1344 {
1345         if (!selection.set() && cursorPar()->size())
1346                 return;
1347
1348         if (selection.start.par() == selection.end.par()) {
1349                 LyXCursor & startc = selection.start;
1350                 LyXCursor & endc = selection.end;
1351                 recordUndo(Undo::INSERT, this, startc.par());
1352                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1353                 finishUndo();
1354                 clearSelection();
1355                 redoParagraph(getPar(startc));
1356                 setCursorIntern(startc.par(), 0);
1357         }
1358 #warning handle multi par selection
1359 }
1360
1361
1362 void LyXText::rejectChange()
1363 {
1364         if (!selection.set() && cursorPar()->size())
1365                 return;
1366
1367         if (selection.start.par() == selection.end.par()) {
1368                 LyXCursor & startc = selection.start;
1369                 LyXCursor & endc = selection.end;
1370                 recordUndo(Undo::INSERT, this, startc.par());
1371                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1372                 finishUndo();
1373                 clearSelection();
1374                 redoParagraph(getPar(startc));
1375                 setCursorIntern(startc.par(), 0);
1376         }
1377 #warning handle multi par selection
1378 }
1379
1380
1381 // This function is only used by the spellchecker for NextWord().
1382 // It doesn't handle LYX_ACCENTs and probably never will.
1383 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1384 {
1385         if (the_locking_inset) {
1386                 WordLangTuple word =
1387                         the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1388                 if (!word.word().empty()) {
1389                         value += float(cursor.y());
1390                         value /= float(height);
1391                         return word;
1392                 }
1393                 // we have to go on checking so move cursor to the next char
1394                 if (cursor.pos() == cursorPar()->size()) {
1395                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1396                                 return word;
1397                         cursor.par(cursor.par() + 1);
1398                         cursor.pos(0);
1399                 } else {
1400                         cursor.pos(cursor.pos() + 1);
1401                 }
1402         }
1403         int const tmppar = cursor.par();
1404
1405         // If this is not the very first word, skip rest of
1406         // current word because we are probably in the middle
1407         // of a word if there is text here.
1408         if (cursor.pos() || cursor.par() != 0) {
1409                 while (cursor.pos() < cursorPar()->size()
1410                        && cursorPar()->isLetter(cursor.pos()))
1411                         cursor.pos(cursor.pos() + 1);
1412         }
1413
1414         // Now, skip until we have real text (will jump paragraphs)
1415         while (true) {
1416                 ParagraphList::iterator cpit = cursorPar();
1417                 pos_type const cpos = cursor.pos();
1418
1419                 if (cpos == cpit->size()) {
1420                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1421                                 cursor.par(cursor.par() + 1);
1422                                 cursor.pos(0);
1423                                 continue;
1424                         }
1425                         break;
1426                 }
1427
1428                 bool const is_good_inset = cpit->isInset(cpos)
1429                         && cpit->getInset(cpos)->allowSpellcheck();
1430
1431                 if (!isDeletedText(*cpit, cpos)
1432                     && (is_good_inset || cpit->isLetter(cpos)))
1433                         break;
1434
1435                 cursor.pos(cpos + 1);
1436         }
1437
1438         // now check if we hit an inset so it has to be a inset containing text!
1439         if (cursor.pos() < cursorPar()->size() &&
1440             cursorPar()->isInset(cursor.pos())) {
1441                 // lock the inset!
1442                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1443                 cursorPar()->getInset(cursor.pos())->dispatch(cmd);
1444                 // now call us again to do the above trick
1445                 // but obviously we have to start from down below ;)
1446                 return bv()->text->selectNextWordToSpellcheck(value);
1447         }
1448
1449         // Update the value if we changed paragraphs
1450         if (cursor.par() != tmppar) {
1451                 setCursor(cursor.par(), cursor.pos());
1452                 value = float(cursor.y())/float(height);
1453         }
1454
1455         // Start the selection from here
1456         selection.cursor = cursor;
1457
1458         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1459         // and find the end of the word (insets like optional hyphens
1460         // and ligature break are part of a word)
1461         while (cursor.pos() < cursorPar()->size()
1462                && cursorPar()->isLetter(cursor.pos())
1463                && !isDeletedText(*cursorPar(), cursor.pos()))
1464                 cursor.pos(cursor.pos() + 1);
1465
1466         // Finally, we copy the word to a string and return it
1467         string str;
1468         if (selection.cursor.pos() < cursor.pos()) {
1469                 for (pos_type i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1470                         if (!cursorPar()->isInset(i))
1471                                 str += cursorPar()->getChar(i);
1472                 }
1473         }
1474         return WordLangTuple(str, lang_code);
1475 }
1476
1477
1478 // This one is also only for the spellchecker
1479 void LyXText::selectSelectedWord()
1480 {
1481         if (the_locking_inset) {
1482                 the_locking_inset->selectSelectedWord(bv());
1483                 return;
1484         }
1485         // move cursor to the beginning
1486         setCursor(selection.cursor.par(), selection.cursor.pos());
1487
1488         // set the sel cursor
1489         selection.cursor = cursor;
1490
1491         // now find the end of the word
1492         while (cursor.pos() < cursorPar()->size()
1493                && cursorPar()->isLetter(cursor.pos()))
1494                 cursor.pos(cursor.pos() + 1);
1495
1496         setCursor(cursorPar(), cursor.pos());
1497
1498         // finally set the selection
1499         setSelection();
1500 }
1501
1502
1503 // Delete from cursor up to the end of the current or next word.
1504 void LyXText::deleteWordForward()
1505 {
1506         if (cursorPar()->empty())
1507                 cursorRight(bv());
1508         else {
1509                 LyXCursor tmpcursor = cursor;
1510                 selection.set(true); // to avoid deletion
1511                 cursorRightOneWord();
1512                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1513                 selection.cursor = cursor;
1514                 cursor = tmpcursor;
1515                 setSelection();
1516                 cutSelection(true, false);
1517         }
1518 }
1519
1520
1521 // Delete from cursor to start of current or prior word.
1522 void LyXText::deleteWordBackward()
1523 {
1524         if (cursorPar()->empty())
1525                 cursorLeft(bv());
1526         else {
1527                 LyXCursor tmpcursor = cursor;
1528                 selection.set(true); // to avoid deletion
1529                 cursorLeftOneWord();
1530                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1531                 selection.cursor = cursor;
1532                 cursor = tmpcursor;
1533                 setSelection();
1534                 cutSelection(true, false);
1535         }
1536 }
1537
1538
1539 // Kill to end of line.
1540 void LyXText::deleteLineForward()
1541 {
1542         if (cursorPar()->empty())
1543                 // Paragraph is empty, so we just go to the right
1544                 cursorRight(bv());
1545         else {
1546                 LyXCursor tmpcursor = cursor;
1547                 // We can't store the row over a regular setCursor
1548                 // so we set it to 0 and reset it afterwards.
1549                 selection.set(true); // to avoid deletion
1550                 cursorEnd();
1551                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1552                 selection.cursor = cursor;
1553                 cursor = tmpcursor;
1554                 setSelection();
1555                 // What is this test for ??? (JMarc)
1556                 if (!selection.set()) {
1557                         deleteWordForward();
1558                 } else {
1559                         cutSelection(true, false);
1560                 }
1561         }
1562 }
1563
1564
1565 void LyXText::changeCase(LyXText::TextCase action)
1566 {
1567         LyXCursor from;
1568         LyXCursor to;
1569
1570         if (selection.set()) {
1571                 from = selection.start;
1572                 to = selection.end;
1573         } else {
1574                 from = cursor;
1575                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1576                 setCursor(to.par(), to.pos() + 1);
1577         }
1578
1579         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1580
1581         pos_type pos = from.pos();
1582         int par = from.par();
1583
1584         while (par != int(ownerParagraphs().size()) &&
1585                (pos != to.pos() || par != to.par())) {
1586                 ParagraphList::iterator pit = getPar(par);
1587                 if (pos == pit->size()) {
1588                         ++par;
1589                         pos = 0;
1590                         continue;
1591                 }
1592                 unsigned char c = pit->getChar(pos);
1593                 if (c != Paragraph::META_INSET) {
1594                         switch (action) {
1595                         case text_lowercase:
1596                                 c = lowercase(c);
1597                                 break;
1598                         case text_capitalization:
1599                                 c = uppercase(c);
1600                                 action = text_lowercase;
1601                                 break;
1602                         case text_uppercase:
1603                                 c = uppercase(c);
1604                                 break;
1605                         }
1606                 }
1607 #warning changes
1608                 pit->setChar(pos, c);
1609                 ++pos;
1610         }
1611 }
1612
1613
1614 void LyXText::Delete()
1615 {
1616         // this is a very easy implementation
1617
1618         LyXCursor old_cursor = cursor;
1619         int const old_cur_par_id = cursorPar()->id();
1620         int const old_cur_par_prev_id =
1621                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1622
1623         // just move to the right
1624         cursorRight(bv());
1625
1626         // CHECK Look at the comment here.
1627         // This check is not very good...
1628         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1629         // and that can very well delete the par or par->previous in
1630         // old_cursor. Will a solution where we compare paragraph id's
1631         //work better?
1632         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1633         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1634                 // delete-empty-paragraph-mechanism has done it
1635                 return;
1636         }
1637
1638         // if you had success make a backspace
1639         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1640                 recordUndo(Undo::DELETE, this, old_cursor.par());
1641                 backspace();
1642         }
1643 }
1644
1645
1646 void LyXText::backspace()
1647 {
1648         // Get the font that is used to calculate the baselineskip
1649         ParagraphList::iterator pit = cursorPar();
1650         pos_type lastpos = pit->size();
1651
1652         if (cursor.pos() == 0) {
1653                 // The cursor is at the beginning of a paragraph,
1654                 // so the the backspace will collapse two paragraphs into one.
1655
1656                 // but it's not allowed unless it's new
1657                 if (pit->isChangeEdited(0, pit->size()))
1658                         return;
1659
1660                 // we may paste some paragraphs
1661
1662                 // is it an empty paragraph?
1663
1664                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1665                         // This is an empty paragraph and we delete it just
1666                         // by moving the cursor one step
1667                         // left and let the DeleteEmptyParagraphMechanism
1668                         // handle the actual deletion of the paragraph.
1669
1670                         if (cursor.par()) {
1671                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1672                                 if (cursorPar()->layout() == tmppit->layout()
1673                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1674                                         // Inherit bottom DTD from the paragraph below.
1675                                         // (the one we are deleting)
1676                                         tmppit->params().lineBottom(cursorPar()->params().lineBottom());
1677                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1678                                         tmppit->params().pagebreakBottom(cursorPar()->params().pagebreakBottom());
1679                                 }
1680
1681                                 cursorLeft(bv());
1682
1683                                 // the layout things can change the height of a row !
1684                                 redoParagraph();
1685                                 return;
1686                         }
1687                 }
1688
1689                 if (cursor.par() != 0)
1690                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1691
1692                 ParagraphList::iterator tmppit = cursorPar();
1693                 // We used to do cursorLeftIntern() here, but it is
1694                 // not a good idea since it triggers the auto-delete
1695                 // mechanism. So we do a cursorLeftIntern()-lite,
1696                 // without the dreaded mechanism. (JMarc)
1697                 if (cursor.par() != 0) {
1698                         // steps into the above paragraph.
1699                         setCursorIntern(cursor.par() - 1,
1700                                         getPar(cursor.par() - 1)->size(),
1701                                         false);
1702                 }
1703
1704                 // Pasting is not allowed, if the paragraphs have different
1705                 // layout. I think it is a real bug of all other
1706                 // word processors to allow it. It confuses the user.
1707                 // Correction: Pasting is always allowed with standard-layout
1708                 Buffer & buf = *bv()->buffer();
1709                 BufferParams const & bufparams = buf.params();
1710                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1711
1712                 if (cursorPar() != tmppit
1713                     && (cursorPar()->layout() == tmppit->layout()
1714                         || tmppit->layout() == tclass.defaultLayout())
1715                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1716                         mergeParagraph(bufparams,
1717                                        buf.paragraphs(), cursorPar());
1718
1719                         if (cursor.pos() && cursorPar()->isSeparator(cursor.pos() - 1))
1720                                 cursor.pos(cursor.pos() - 1);
1721
1722                         // the row may have changed, block, hfills etc.
1723                         updateCounters();
1724                         setCursor(cursor.par(), cursor.pos(), false);
1725                 }
1726         } else {
1727                 // this is the code for a normal backspace, not pasting
1728                 // any paragraphs
1729                 recordUndo(Undo::DELETE, this, cursor.par());
1730                 // We used to do cursorLeftIntern() here, but it is
1731                 // not a good idea since it triggers the auto-delete
1732                 // mechanism. So we do a cursorLeftIntern()-lite,
1733                 // without the dreaded mechanism. (JMarc)
1734                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1735                                 false, cursor.boundary());
1736                 cursorPar()->erase(cursor.pos());
1737         }
1738
1739         lastpos = cursorPar()->size();
1740         if (cursor.pos() == lastpos)
1741                 setCurrentFont();
1742
1743         redoParagraph();
1744         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1745 }
1746
1747
1748 ParagraphList::iterator LyXText::cursorPar() const
1749 {
1750         return getPar(cursor.par());
1751 }
1752
1753
1754 RowList::iterator LyXText::cursorRow() const
1755 {
1756         return cursorPar()->getRow(cursor.pos());
1757 }
1758
1759
1760 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1761 {
1762         return getPar(cur.par());
1763 }
1764
1765
1766 ParagraphList::iterator LyXText::getPar(int par) const
1767 {
1768         BOOST_ASSERT(par >= 0);
1769         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1770         ParagraphList::iterator pit = ownerParagraphs().begin();
1771         std::advance(pit, par);
1772         return pit;
1773 }
1774
1775
1776 RowList::iterator
1777 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1778 {
1779         //lyxerr << "getRowNearY: y " << y << endl;
1780
1781         pit = boost::prior(ownerParagraphs().end());
1782
1783         RowList::iterator rit = lastRow();
1784         RowList::iterator rbegin = firstRow();
1785
1786         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1787                 previousRow(pit, rit);
1788
1789         return rit;
1790 }
1791
1792
1793 int LyXText::getDepth() const
1794 {
1795         return cursorPar()->getDepth();
1796 }
1797
1798
1799 RowList::iterator LyXText::firstRow() const
1800 {
1801         return ownerParagraphs().front().rows.begin();
1802 }
1803
1804
1805 RowList::iterator LyXText::lastRow() const
1806 {
1807         return boost::prior(endRow());
1808 }
1809
1810
1811 RowList::iterator LyXText::endRow() const
1812 {
1813         return ownerParagraphs().back().rows.end();
1814 }
1815
1816
1817 void LyXText::nextRow(ParagraphList::iterator & pit,
1818         RowList::iterator & rit) const
1819 {
1820         ++rit;
1821         if (rit == pit->rows.end()) {
1822                 ++pit;
1823                 if (pit == ownerParagraphs().end())
1824                         --pit;
1825                 else
1826                         rit = pit->rows.begin();
1827         }
1828 }
1829
1830
1831 void LyXText::previousRow(ParagraphList::iterator & pit,
1832         RowList::iterator & rit) const
1833 {
1834         if (rit != pit->rows.begin())
1835                 --rit;
1836         else {
1837                 BOOST_ASSERT(pit != ownerParagraphs().begin());
1838                 --pit;
1839                 rit = boost::prior(pit->rows.end());
1840         }
1841 }
1842
1843
1844 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1845 {
1846         if (!selection.set())
1847                 return string();
1848
1849         // should be const ...
1850         ParagraphList::iterator startpit = getPar(selection.start);
1851         ParagraphList::iterator endpit = getPar(selection.end);
1852         size_t const startpos = selection.start.pos();
1853         size_t const endpos = selection.end.pos();
1854
1855         if (startpit == endpit)
1856                 return startpit->asString(buffer, startpos, endpos, label);
1857
1858         // First paragraph in selection
1859         string result =
1860                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1861
1862         // The paragraphs in between (if any)
1863         ParagraphList::iterator pit = startpit;
1864         for (++pit; pit != endpit; ++pit)
1865                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1866
1867         // Last paragraph in selection
1868         result += endpit->asString(buffer, 0, endpos, label);
1869
1870         return result;
1871 }
1872
1873
1874 int LyXText::parOffset(ParagraphList::iterator pit) const
1875 {
1876         return std::distance(ownerParagraphs().begin(), pit);
1877 }
1878
1879
1880 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1881 {
1882         // remove rows of paragraph, keep track of height changes
1883         height -= pit->height;
1884
1885         // clear old data
1886         pit->rows.clear();
1887         pit->height = 0;
1888         pit->width = 0;
1889
1890         // redo insets
1891         InsetList::iterator ii = pit->insetlist.begin();
1892         InsetList::iterator iend = pit->insetlist.end();
1893         for (; ii != iend; ++ii) {
1894                 Dimension dim;
1895                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
1896                 ii->inset->metrics(mi, dim);
1897         }
1898
1899         // rebreak the paragraph
1900         int const ww = workWidth();
1901         pos_type z = 0;
1902         do {
1903                 Row row(z);
1904                 rowBreakPoint(pit, row);
1905                 z = row.endpos();
1906                 fill(pit, row, ww);
1907                 prepareToPrint(pit, row);
1908                 setHeightOfRow(pit, row);
1909                 row.y_offset(pit->height);
1910                 pit->rows.push_back(row);
1911                 pit->width = std::max(pit->width, row.width());
1912                 pit->height += row.height();
1913         } while (z < pit->size());
1914
1915         height += pit->height;
1916         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1917 }
1918
1919
1920 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1921   ParagraphList::iterator end)
1922 {
1923         for ( ; pit != end; ++pit)
1924                 redoParagraphInternal(pit);
1925         updateRowPositions();
1926 }
1927
1928
1929 void LyXText::redoParagraph(ParagraphList::iterator pit)
1930 {
1931         redoParagraphInternal(pit);
1932         updateRowPositions();
1933 }
1934
1935
1936 void LyXText::fullRebreak()
1937 {
1938         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1939         redoCursor();
1940         selection.cursor = cursor;
1941 }
1942
1943
1944 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1945 {
1946         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1947         //      << " workWidth: " << workWidth() << "\nfont: " << mi.base.font << endl;
1948         //BOOST_ASSERT(mi.base.textwidth);
1949         //anchor_y_ = 0;
1950
1951         // rebuild row cache. This recomputes height as well.
1952         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1953
1954         width = maxParagraphWidth(ownerParagraphs());
1955
1956         // final dimension
1957         dim.asc = firstRow()->ascent_of_text();
1958         dim.des = height - dim.asc;
1959         dim.wid = std::max(mi.base.textwidth, int(width));
1960 }
1961
1962
1963 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
1964 {
1965         return row.endpos() >= pit->size()
1966                && boost::next(pit) == ownerParagraphs().end();
1967 }
1968
1969
1970 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
1971 {
1972         return row.pos() == 0 && pit == ownerParagraphs().begin();
1973 }