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