]> git.lyx.org Git - lyx.git/blob - src/text2.C
bug 778
[lyx.git] / src / text2.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "LString.h"
15 #include "paragraph.h"
16 #include "frontends/LyXView.h"
17 #include "undo_funcs.h"
18 #include "buffer.h"
19 #include "bufferparams.h"
20 #include "gettext.h"
21 #include "BufferView.h"
22 #include "CutAndPaste.h"
23 #include "frontends/Painter.h"
24 #include "frontends/font_metrics.h"
25 #include "debug.h"
26 #include "lyxrc.h"
27 #include "lyxrow.h"
28 #include "FloatList.h"
29 #include "language.h"
30 #include "ParagraphParameters.h"
31 #include "counters.h"
32 #include "lyxrow_funcs.h"
33 #include "paragraph_funcs.h"
34
35 #include "insets/insetbibitem.h"
36 #include "insets/insetfloat.h"
37
38 #include "support/LAssert.h"
39 #include "support/textutils.h"
40 #include "support/lstrings.h"
41
42 #include "support/BoostFormat.h"
43
44 using std::vector;
45 using std::copy;
46 using std::endl;
47 using std::find;
48 using std::pair;
49 using lyx::pos_type;
50
51
52 LyXText::LyXText(BufferView * bv)
53         : height(0), width(0), anchor_row_offset_(0),
54           inset_owner(0), the_locking_inset(0), bv_owner(bv)
55 {
56         anchor_row_ = rows().end();
57         need_break_row = rows().end();
58         refresh_row = rows().end();
59
60         clearPaint();
61 }
62
63
64 LyXText::LyXText(BufferView * bv, InsetText * inset)
65         : height(0), width(0), anchor_row_offset_(0),
66           inset_owner(inset), the_locking_inset(0), bv_owner(bv)
67 {
68         anchor_row_ = rows().end();
69         need_break_row = rows().end();
70         refresh_row = rows().end();
71
72         clearPaint();
73 }
74
75
76 void LyXText::init(BufferView * bview, bool reinit)
77 {
78         if (reinit) {
79                 rowlist_.clear();
80                 need_break_row = rows().end();
81                 width = height = 0;
82                 top_y(0);
83                 clearPaint();
84         } else if (!rowlist_.empty())
85                 return;
86
87         ParagraphList::iterator pit = ownerParagraphs().begin();
88         ParagraphList::iterator end = ownerParagraphs().end();
89
90         current_font = getFont(bview->buffer(), pit, 0);
91
92         for (; pit != end; ++pit) {
93                 insertParagraph(pit, rowlist_.end());
94         }
95         setCursorIntern(rowlist_.begin()->par(), 0);
96         selection.cursor = cursor;
97
98         updateCounters();
99 }
100
101
102 // Gets the fully instantiated font at a given position in a paragraph
103 // Basically the same routine as Paragraph::getFont() in paragraph.C.
104 // The difference is that this one is used for displaying, and thus we
105 // are allowed to make cosmetic improvements. For instance make footnotes
106 // smaller. (Asger)
107 // If position is -1, we get the layout font of the paragraph.
108 // If position is -2, we get the font of the manual label of the paragraph.
109 LyXFont const LyXText::getFont(Buffer const * buf, ParagraphList::iterator pit,
110                                pos_type pos) const
111 {
112         lyx::Assert(pos >= 0);
113
114         LyXLayout_ptr const & layout = pit->layout();
115
116         // We specialize the 95% common case:
117         if (!pit->getDepth()) {
118                 if (layout->labeltype == LABEL_MANUAL
119                     && pos < pit->beginningOfBody()) {
120                         // 1% goes here
121                         LyXFont f = pit->getFontSettings(buf->params, pos);
122                         if (pit->inInset())
123                                 pit->inInset()->getDrawFont(f);
124                         return f.realize(layout->reslabelfont);
125                 } else {
126                         LyXFont f = pit->getFontSettings(buf->params, pos);
127                         if (pit->inInset())
128                                 pit->inInset()->getDrawFont(f);
129                         return f.realize(layout->resfont);
130                 }
131         }
132
133         // The uncommon case need not be optimized as much
134
135         LyXFont layoutfont;
136
137         if (pos < pit->beginningOfBody()) {
138                 // 1% goes here
139                 layoutfont = layout->labelfont;
140         } else {
141                 // 99% goes here
142                 layoutfont = layout->font;
143         }
144
145         LyXFont tmpfont = pit->getFontSettings(buf->params, pos);
146         tmpfont.realize(layoutfont);
147
148         if (pit->inInset())
149                 pit->inInset()->getDrawFont(tmpfont);
150
151         // Realize with the fonts of lesser depth.
152         tmpfont.realize(outerFont(pit, ownerParagraphs()));
153
154         return realizeFont(tmpfont, buf->params);
155 }
156
157
158 LyXFont const LyXText::getLayoutFont(Buffer const * buf,
159                                      ParagraphList::iterator pit) const
160 {
161         LyXLayout_ptr const & layout = pit->layout();
162
163         if (!pit->getDepth()) {
164                 return layout->resfont;
165         }
166
167         LyXFont font(layout->font);
168         // Realize with the fonts of lesser depth.
169         font.realize(outerFont(pit, ownerParagraphs()));
170
171         return realizeFont(font, buf->params);
172 }
173
174
175 LyXFont const LyXText::getLabelFont(Buffer const * buf,
176                                     ParagraphList::iterator pit) const
177 {
178         LyXLayout_ptr const & layout = pit->layout();
179
180         if (!pit->getDepth()) {
181                 return layout->reslabelfont;
182         }
183
184         LyXFont font(layout->labelfont);
185         // Realize with the fonts of lesser depth.
186         font.realize(outerFont(pit, ownerParagraphs()));
187
188         return realizeFont(layout->labelfont, buf->params);
189 }
190
191
192 void LyXText::setCharFont(ParagraphList::iterator pit,
193                           pos_type pos, LyXFont const & fnt,
194                           bool toggleall)
195 {
196         Buffer const * buf = bv()->buffer();
197         LyXFont font = getFont(buf, pit, pos);
198         font.update(fnt, buf->params.language, toggleall);
199         // Let the insets convert their font
200         if (pit->isInset(pos)) {
201                 Inset * inset = pit->getInset(pos);
202                 if (isEditableInset(inset)) {
203                         UpdatableInset * uinset =
204                                 static_cast<UpdatableInset *>(inset);
205                         uinset->setFont(bv(), fnt, toggleall, true);
206                 }
207         }
208
209         // Plug thru to version below:
210         setCharFont(buf, pit, pos, font);
211 }
212
213
214 void LyXText::setCharFont(Buffer const * buf, ParagraphList::iterator pit,
215                           pos_type pos, LyXFont const & fnt)
216 {
217         LyXFont font(fnt);
218
219         LyXTextClass const & tclass = buf->params.getLyXTextClass();
220         LyXLayout_ptr const & layout = pit->layout();
221
222         // Get concrete layout font to reduce against
223         LyXFont layoutfont;
224
225         if (pos < pit->beginningOfBody())
226                 layoutfont = layout->labelfont;
227         else
228                 layoutfont = layout->font;
229
230         // Realize against environment font information
231         if (pit->getDepth()) {
232                 ParagraphList::iterator tp = pit;
233                 while (!layoutfont.resolved() &&
234                        tp != ownerParagraphs().end() &&
235                        tp->getDepth()) {
236                         tp = outerHook(tp, ownerParagraphs());
237                         if (tp != ownerParagraphs().end())
238                                 layoutfont.realize(tp->layout()->font);
239                 }
240         }
241
242         layoutfont.realize(tclass.defaultfont());
243
244         // Now, reduce font against full layout font
245         font.reduce(layoutfont);
246
247         pit->setFont(pos, font);
248 }
249
250
251 // removes the row and reset the touched counters
252 void LyXText::removeRow(RowList::iterator rit)
253 {
254         /* FIXME: when we cache the bview, this should just
255          * become a postPaint(), I think */
256         if (refresh_row == rit) {
257                 if (rit == rows().begin())
258                         refresh_row = boost::next(rit);
259                 else
260                         refresh_row = boost::prior(rit);
261
262                 // what about refresh_y
263         }
264
265         if (anchor_row_ == rit) {
266                 if (rit != rows().begin()) {
267                         anchor_row_ = boost::prior(rit);
268                         anchor_row_offset_ += anchor_row_->height();
269                 } else {
270                         anchor_row_ = boost::next(rit);
271                         anchor_row_offset_ -= rit->height();
272                 }
273         }
274
275         // the text becomes smaller
276         height -= rit->height();
277
278         rowlist_.erase(rit);
279 }
280
281
282 // remove all following rows of the paragraph of the specified row.
283 void LyXText::removeParagraph(RowList::iterator rit)
284 {
285         ParagraphList::iterator tmppit = rit->par();
286         ++rit;
287
288         while (rit != rows().end() && rit->par() == tmppit) {
289                 RowList::iterator tmprit = boost::next(rit);
290                 removeRow(rit);
291                 rit = tmprit;
292         }
293 }
294
295
296 void LyXText::insertParagraph(ParagraphList::iterator pit,
297                               RowList::iterator rowit)
298 {
299         // insert a new row, starting at position 0
300         Row newrow(pit, 0);
301         RowList::iterator rit = rowlist_.insert(rowit, newrow);
302
303         // and now append the whole paragraph before the new row
304         appendParagraph(rit);
305 }
306
307
308 Inset * LyXText::getInset() const
309 {
310         ParagraphList::iterator pit = cursor.par();
311         pos_type const pos = cursor.pos();
312
313         if (pos < pit->size() && pit->isInset(pos)) {
314                 return pit->getInset(pos);
315         }
316         return 0;
317 }
318
319
320 void LyXText::toggleInset()
321 {
322         Inset * inset = getInset();
323         // is there an editable inset at cursor position?
324         if (!isEditableInset(inset)) {
325                 // No, try to see if we are inside a collapsable inset
326                 if (inset_owner && inset_owner->owner()
327                     && inset_owner->owner()->isOpen()) {
328                         bv()->unlockInset(static_cast<UpdatableInset *>(inset_owner->owner()));
329                         inset_owner->owner()->close(bv());
330                         bv()->getLyXText()->cursorRight(bv());
331                 }
332                 return;
333         }
334         //bv()->owner()->message(inset->editMessage());
335
336         // do we want to keep this?? (JMarc)
337         if (!isHighlyEditableInset(inset))
338                 setCursorParUndo(bv());
339
340         if (inset->isOpen()) {
341                 inset->close(bv());
342         } else {
343                 inset->open(bv());
344         }
345
346         bv()->updateInset(inset);
347 }
348
349
350 /* used in setlayout */
351 // Asger is not sure we want to do this...
352 void LyXText::makeFontEntriesLayoutSpecific(Buffer const & buf,
353                                             Paragraph & par)
354 {
355         LyXLayout_ptr const & layout = par.layout();
356         pos_type const psize = par.size();
357
358         LyXFont layoutfont;
359         for (pos_type pos = 0; pos < psize; ++pos) {
360                 if (pos < par.beginningOfBody())
361                         layoutfont = layout->labelfont;
362                 else
363                         layoutfont = layout->font;
364
365                 LyXFont tmpfont = par.getFontSettings(buf.params, pos);
366                 tmpfont.reduce(layoutfont);
367                 par.setFont(pos, tmpfont);
368         }
369 }
370
371
372 ParagraphList::iterator
373 LyXText::setLayout(LyXCursor & cur, LyXCursor & sstart_cur,
374                    LyXCursor & send_cur,
375                    string const & layout)
376 {
377         ParagraphList::iterator endpit = boost::next(send_cur.par());
378         ParagraphList::iterator undoendpit = endpit;
379         ParagraphList::iterator pars_end = ownerParagraphs().end();
380
381         if (endpit != pars_end && endpit->getDepth()) {
382                 while (endpit != pars_end && endpit->getDepth()) {
383                         ++endpit;
384                         undoendpit = endpit;
385                 }
386         } else if (endpit != pars_end) {
387                 // because of parindents etc.
388                 ++endpit;
389         }
390
391         setUndo(bv(), Undo::EDIT, &*sstart_cur.par(), &*undoendpit);
392
393         // ok we have a selection. This is always between sstart_cur
394         // and sel_end cursor
395         cur = sstart_cur;
396         ParagraphList::iterator pit = sstart_cur.par();
397         ParagraphList::iterator epit = boost::next(send_cur.par());
398
399         LyXLayout_ptr const & lyxlayout =
400                 bv()->buffer()->params.getLyXTextClass()[layout];
401
402         do {
403                 pit->applyLayout(lyxlayout);
404                 makeFontEntriesLayoutSpecific(*bv()->buffer(), *pit);
405                 ParagraphList::iterator fppit = pit;
406                 fppit->params().spaceTop(lyxlayout->fill_top ?
407                                          VSpace(VSpace::VFILL)
408                                          : VSpace(VSpace::NONE));
409                 fppit->params().spaceBottom(lyxlayout->fill_bottom ?
410                                             VSpace(VSpace::VFILL)
411                                             : VSpace(VSpace::NONE));
412                 if (lyxlayout->margintype == MARGIN_MANUAL)
413                         pit->setLabelWidthString(lyxlayout->labelstring());
414                 cur.par(pit);
415                 ++pit;
416         } while (pit != epit);
417
418         return endpit;
419 }
420
421
422 // set layout over selection and make a total rebreak of those paragraphs
423 void LyXText::setLayout(string const & layout)
424 {
425         LyXCursor tmpcursor = cursor;  /* store the current cursor  */
426
427         // if there is no selection just set the layout
428         // of the current paragraph  */
429         if (!selection.set()) {
430                 selection.start = cursor;  // dummy selection
431                 selection.end = cursor;
432         }
433         ParagraphList::iterator endpit = setLayout(cursor, selection.start,
434                                                    selection.end, layout);
435         redoParagraphs(selection.start, endpit);
436
437         // we have to reset the selection, because the
438         // geometry could have changed
439         setCursor(selection.start.par(),
440                   selection.start.pos(), false);
441         selection.cursor = cursor;
442         setCursor(selection.end.par(), selection.end.pos(), false);
443         updateCounters();
444         clearSelection();
445         setSelection();
446         setCursor(tmpcursor.par(), tmpcursor.pos(), true);
447 }
448
449
450 bool LyXText::changeDepth(bv_funcs::DEPTH_CHANGE type, bool test_only)
451 {
452         ParagraphList::iterator pit(cursor.par());
453         ParagraphList::iterator end(cursor.par());
454         ParagraphList::iterator start = pit;
455
456         if (selection.set()) {
457                 pit = selection.start.par();
458                 end = selection.end.par();
459                 start = pit;
460         }
461
462         ParagraphList::iterator pastend = boost::next(end);
463
464         if (!test_only)
465                 setUndo(bv(), Undo::EDIT, &(*start), &(*pastend));
466
467         bool changed = false;
468
469         int prev_after_depth = 0;
470 #warning parlist ... could be nicer ?
471         if (start != ownerParagraphs().begin()) {
472                 prev_after_depth = boost::prior(start)->getMaxDepthAfter();
473         }
474
475         while (true) {
476                 int const depth = pit->params().depth();
477                 if (type == bv_funcs::INC_DEPTH) {
478                         if (depth < prev_after_depth
479                             && pit->layout()->labeltype != LABEL_BIBLIO) {
480                                 changed = true;
481                                 if (!test_only) {
482                                         pit->params().depth(depth + 1);
483                                 }
484
485                         }
486                 } else if (depth) {
487                         changed = true;
488                         if (!test_only)
489                                 pit->params().depth(depth - 1);
490                 }
491
492                 prev_after_depth = pit->getMaxDepthAfter();
493
494                 if (pit == end) {
495                         break;
496                 }
497
498                 ++pit;
499         }
500
501         if (test_only)
502                 return changed;
503
504         // Wow, redoParagraphs is stupid.
505         LyXCursor tmpcursor;
506         setCursor(tmpcursor, &(*start), 0);
507
508         //redoParagraphs(tmpcursor, &(*pastend));
509         redoParagraphs(tmpcursor, &(*pastend));
510
511         // We need to actually move the text->cursor. I don't
512         // understand why ...
513         tmpcursor = cursor;
514
515         // we have to reset the visual selection because the
516         // geometry could have changed
517         if (selection.set()) {
518                 setCursor(selection.start.par(), selection.start.pos());
519                 selection.cursor = cursor;
520                 setCursor(selection.end.par(), selection.end.pos());
521         }
522
523         // this handles the counter labels, and also fixes up
524         // depth values for follow-on (child) paragraphs
525         updateCounters();
526
527         setSelection();
528         setCursor(tmpcursor.par(), tmpcursor.pos());
529
530         return changed;
531 }
532
533
534 // set font over selection and make a total rebreak of those paragraphs
535 void LyXText::setFont(LyXFont const & font, bool toggleall)
536 {
537         // if there is no selection just set the current_font
538         if (!selection.set()) {
539                 // Determine basis font
540                 LyXFont layoutfont;
541                 if (cursor.pos() < cursor.par()->beginningOfBody()) {
542                         layoutfont = getLabelFont(bv()->buffer(),
543                                                   cursor.par());
544                 } else {
545                         layoutfont = getLayoutFont(bv()->buffer(),
546                                                    cursor.par());
547                 }
548                 // Update current font
549                 real_current_font.update(font,
550                                          bv()->buffer()->params.language,
551                                          toggleall);
552
553                 // Reduce to implicit settings
554                 current_font = real_current_font;
555                 current_font.reduce(layoutfont);
556                 // And resolve it completely
557                 real_current_font.realize(layoutfont);
558
559                 return;
560         }
561
562         LyXCursor tmpcursor = cursor; // store the current cursor
563
564         // ok we have a selection. This is always between sel_start_cursor
565         // and sel_end cursor
566
567         setUndo(bv(), Undo::EDIT,
568                 &*selection.start.par(), &*boost::next(selection.end.par()));
569         freezeUndo();
570         cursor = selection.start;
571         while (cursor.par() != selection.end.par() ||
572                cursor.pos() < selection.end.pos())
573         {
574                 if (cursor.pos() < cursor.par()->size()) {
575                         // an open footnote should behave like a closed one
576                         setCharFont(cursor.par(), cursor.pos(),
577                                     font, toggleall);
578                         cursor.pos(cursor.pos() + 1);
579                 } else {
580                         cursor.pos(0);
581                         cursor.par(boost::next(cursor.par()));
582                 }
583         }
584         unFreezeUndo();
585
586         redoParagraphs(selection.start, boost::next(selection.end.par()));
587
588         // we have to reset the selection, because the
589         // geometry could have changed, but we keep
590         // it for user convenience
591         setCursor(selection.start.par(), selection.start.pos());
592         selection.cursor = cursor;
593         setCursor(selection.end.par(), selection.end.pos());
594         setSelection();
595         setCursor(tmpcursor.par(), tmpcursor.pos(), true,
596                   tmpcursor.boundary());
597 }
598
599
600 void LyXText::redoHeightOfParagraph()
601 {
602         RowList::iterator tmprow = cursor.row();
603         int y = cursor.y() - tmprow->baseline();
604
605         setHeightOfRow(tmprow);
606
607         while (tmprow != rows().begin()
608                && boost::prior(tmprow)->par() == tmprow->par()) {
609                 --tmprow;
610                 y -= tmprow->height();
611                 setHeightOfRow(tmprow);
612         }
613
614         postPaint(y);
615
616         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
617 }
618
619
620 void LyXText::redoDrawingOfParagraph(LyXCursor const & cur)
621 {
622         RowList::iterator tmprow = cur.row();
623
624         int y = cur.y() - tmprow->baseline();
625         setHeightOfRow(tmprow);
626
627         while (tmprow != rows().begin()
628                && boost::prior(tmprow)->par() == tmprow->par())  {
629                 --tmprow;
630                 y -= tmprow->height();
631         }
632
633         postPaint(y);
634         setCursor(cur.par(), cur.pos());
635 }
636
637
638 // deletes and inserts again all paragaphs between the cursor
639 // and the specified par
640 // This function is needed after SetLayout and SetFont etc.
641 void LyXText::redoParagraphs(LyXCursor const & cur,
642                              ParagraphList::iterator endpit)
643 {
644         RowList::iterator tmprit = cur.row();
645         int y = cur.y() - tmprit->baseline();
646
647         ParagraphList::iterator first_phys_pit;
648         RowList::iterator prevrit;
649         if (tmprit == rows().begin()) {
650                 // A trick/hack for UNDO.
651                 // This is needed because in an UNDO/REDO we could have
652                 // changed the ownerParagrah() so the paragraph inside
653                 // the row is NOT my really first par anymore.
654                 // Got it Lars ;) (Jug 20011206)
655                 first_phys_pit = ownerParagraphs().begin();
656                 prevrit = rows().end();
657         } else {
658                 first_phys_pit = tmprit->par();
659                 while (tmprit != rows().begin()
660                        && boost::prior(tmprit)->par() == first_phys_pit)
661                 {
662                         --tmprit;
663                         y -= tmprit->height();
664                 }
665                 prevrit = boost::prior(tmprit);
666         }
667
668         // remove it
669         while (tmprit != rows().end() && tmprit->par() != endpit) {
670                 RowList::iterator tmprit2 = tmprit++;
671                 removeRow(tmprit2);
672         }
673
674         // Reinsert the paragraphs.
675         ParagraphList::iterator tmppit = first_phys_pit;
676
677         while (tmppit != ownerParagraphs().end()) {
678                 insertParagraph(tmppit, tmprit);
679                 while (tmprit != rows().end()
680                        && tmprit->par() == tmppit) {
681                         ++tmprit;
682                 }
683                 ++tmppit;
684                 if (tmppit == endpit)
685                         break;
686         }
687         if (prevrit != rows().end()) {
688                 setHeightOfRow(prevrit);
689                 const_cast<LyXText *>(this)->postPaint(y - prevrit->height());
690         } else {
691                 setHeightOfRow(rows().begin());
692                 const_cast<LyXText *>(this)->postPaint(0);
693         }
694         if (tmprit != rows().end())
695                 setHeightOfRow(tmprit);
696
697         updateCounters();
698 }
699
700
701 void LyXText::fullRebreak()
702 {
703         if (rows().empty()) {
704                 init(bv());
705                 return;
706         }
707
708         RowList::iterator rows_end = rows().end();
709
710         if (need_break_row != rows_end) {
711                 breakAgain(need_break_row);
712                 need_break_row = rows_end;
713                 return;
714         }
715 }
716
717
718 // important for the screen
719
720
721 // the cursor set functions have a special mechanism. When they
722 // realize, that you left an empty paragraph, they will delete it.
723 // They also delete the corresponding row
724
725 // need the selection cursor:
726 void LyXText::setSelection()
727 {
728         bool const lsel = selection.set();
729
730         if (!selection.set()) {
731                 last_sel_cursor = selection.cursor;
732                 selection.start = selection.cursor;
733                 selection.end = selection.cursor;
734         }
735
736         selection.set(true);
737
738         // first the toggling area
739         if (cursor.y() < last_sel_cursor.y()
740             || (cursor.y() == last_sel_cursor.y()
741                 && cursor.x() < last_sel_cursor.x())) {
742                 toggle_end_cursor = last_sel_cursor;
743                 toggle_cursor = cursor;
744         } else {
745                 toggle_end_cursor = cursor;
746                 toggle_cursor = last_sel_cursor;
747         }
748
749         last_sel_cursor = cursor;
750
751         // and now the whole selection
752
753         if (selection.cursor.par() == cursor.par())
754                 if (selection.cursor.pos() < cursor.pos()) {
755                         selection.end = cursor;
756                         selection.start = selection.cursor;
757                 } else {
758                         selection.end = selection.cursor;
759                         selection.start = cursor;
760                 }
761         else if (selection.cursor.y() < cursor.y() ||
762                  (selection.cursor.y() == cursor.y()
763                   && selection.cursor.x() < cursor.x())) {
764                 selection.end = cursor;
765                 selection.start = selection.cursor;
766         }
767         else {
768                 selection.end = selection.cursor;
769                 selection.start = cursor;
770         }
771
772         // a selection with no contents is not a selection
773         if (selection.start.par() == selection.end.par() &&
774             selection.start.pos() == selection.end.pos())
775                 selection.set(false);
776
777         if (inset_owner && (selection.set() || lsel))
778                 inset_owner->setUpdateStatus(bv(), InsetText::SELECTION);
779 }
780
781
782 string const LyXText::selectionAsString(Buffer const * buffer,
783                                         bool label) const
784 {
785         if (!selection.set()) return string();
786
787         // should be const ...
788         ParagraphList::iterator startpit = selection.start.par();
789         ParagraphList::iterator endpit = selection.end.par();
790         pos_type const startpos(selection.start.pos());
791         pos_type const endpos(selection.end.pos());
792
793         if (startpit == endpit) {
794                 return startpit->asString(buffer, startpos, endpos, label);
795         }
796
797         string result;
798
799         // First paragraph in selection
800         result += startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
801
802         // The paragraphs in between (if any)
803         ParagraphList::iterator pit = boost::next(startpit);
804         for (; pit != endpit; ++pit) {
805                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
806         }
807
808         // Last paragraph in selection
809         result += endpit->asString(buffer, 0, endpos, label);
810
811         return result;
812 }
813
814
815 void LyXText::clearSelection()
816 {
817         selection.set(false);
818         selection.mark(false);
819         last_sel_cursor = selection.end = selection.start = selection.cursor = cursor;
820         // reset this in the bv_owner!
821         if (bv_owner && bv_owner->text)
822                 bv_owner->text->xsel_cache.set(false);
823 }
824
825
826 void LyXText::cursorHome()
827 {
828         setCursor(cursor.par(), cursor.row()->pos());
829 }
830
831
832 void LyXText::cursorEnd()
833 {
834         if (cursor.par()->empty())
835                 return;
836
837         RowList::iterator rit = cursor.row();
838         RowList::iterator next_rit = boost::next(rit);
839         ParagraphList::iterator pit = rit->par();
840         pos_type last_pos = lastPos(*this, rit);
841
842         if (next_rit == rows().end() || next_rit->par() != pit) {
843                 ++last_pos;
844         } else {
845                 if (pit->empty() ||
846                     (pit->getChar(last_pos) != ' ' && !pit->isNewline(last_pos))) {
847                         ++last_pos;
848                 }
849         }
850
851         setCursor(pit, last_pos);
852 }
853
854
855 void LyXText::cursorTop()
856 {
857         setCursor(ownerParagraphs().begin(), 0);
858 }
859
860
861 void LyXText::cursorBottom()
862 {
863 #warning FIXME
864         // This is how it should be:
865         // ParagraphList::iterator lastpit = boost::prior(ownerParagraphs().end());
866         ParagraphList::iterator lastpit = &ownerParagraphs().back();
867         int pos = lastpit->size();
868         setCursor(lastpit, pos);
869 }
870
871
872 void LyXText::toggleFree(LyXFont const & font, bool toggleall)
873 {
874         // If the mask is completely neutral, tell user
875         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
876                 // Could only happen with user style
877                 bv()->owner()->message(_("No font change defined. Use Character under the Layout menu to define font change."));
878                 return;
879         }
880
881         // Try implicit word selection
882         // If there is a change in the language the implicit word selection
883         // is disabled.
884         LyXCursor resetCursor = cursor;
885         bool implicitSelection = (font.language() == ignore_language
886                                   && font.number() == LyXFont::IGNORE)
887                 ? selectWordWhenUnderCursor(WHOLE_WORD_STRICT) : false;
888
889         // Set font
890         setFont(font, toggleall);
891
892         // Implicit selections are cleared afterwards
893         //and cursor is set to the original position.
894         if (implicitSelection) {
895                 clearSelection();
896                 cursor = resetCursor;
897                 setCursor(cursor.par(), cursor.pos());
898                 selection.cursor = cursor;
899         }
900         if (inset_owner)
901                 inset_owner->setUpdateStatus(bv(), InsetText::CURSOR_PAR);
902 }
903
904
905 string LyXText::getStringToIndex()
906 {
907         // Try implicit word selection
908         // If there is a change in the language the implicit word selection
909         // is disabled.
910         LyXCursor const reset_cursor = cursor;
911         bool const implicitSelection = selectWordWhenUnderCursor(PREVIOUS_WORD);
912
913         string idxstring;
914         if (!selection.set())
915                 bv()->owner()->message(_("Nothing to index!"));
916         else if (selection.start.par() != selection.end.par())
917                 bv()->owner()->message(_("Cannot index more than one paragraph!"));
918         else
919                 idxstring = selectionAsString(bv()->buffer(), false);
920
921         // Reset cursors to their original position.
922         cursor = reset_cursor;
923         setCursor(cursor.par(), cursor.pos());
924         selection.cursor = cursor;
925
926         // Clear the implicit selection.
927         if (implicitSelection)
928                 clearSelection();
929
930         return idxstring;
931 }
932
933
934 // the DTP switches for paragraphs. LyX will store them in the first
935 // physicla paragraph. When a paragraph is broken, the top settings rest,
936 // the bottom settings are given to the new one. So I can make shure,
937 // they do not duplicate themself and you cannnot make dirty things with
938 // them!
939
940 void LyXText::setParagraph(bool line_top, bool line_bottom,
941                            bool pagebreak_top, bool pagebreak_bottom,
942                            VSpace const & space_top,
943                            VSpace const & space_bottom,
944                            Spacing const & spacing,
945                            LyXAlignment align,
946                            string const & labelwidthstring,
947                            bool noindent)
948 {
949         LyXCursor tmpcursor = cursor;
950         if (!selection.set()) {
951                 selection.start = cursor;
952                 selection.end = cursor;
953         }
954
955         // make sure that the depth behind the selection are restored, too
956         ParagraphList::iterator endpit = boost::next(selection.end.par());
957         ParagraphList::iterator undoendpit = endpit;
958         ParagraphList::iterator pars_end = ownerParagraphs().end();
959
960         if (endpit != pars_end && endpit->getDepth()) {
961                 while (endpit != pars_end && endpit->getDepth()) {
962                         ++endpit;
963                         undoendpit = endpit;
964                 }
965         } else if (endpit!= pars_end) {
966                 // because of parindents etc.
967                 ++endpit;
968         }
969
970         setUndo(bv(), Undo::EDIT, &*selection.start.par(), &*undoendpit);
971
972
973         ParagraphList::iterator tmppit = selection.end.par();
974
975         while (tmppit != boost::prior(selection.start.par())) {
976                 setCursor(tmppit, 0);
977                 postPaint(cursor.y() - cursor.row()->baseline());
978
979                 ParagraphList::iterator pit = cursor.par();
980                 ParagraphParameters & params = pit->params();
981
982                 params.lineTop(line_top);
983                 params.lineBottom(line_bottom);
984                 params.pagebreakTop(pagebreak_top);
985                 params.pagebreakBottom(pagebreak_bottom);
986                 params.spaceTop(space_top);
987                 params.spaceBottom(space_bottom);
988                 params.spacing(spacing);
989                 // does the layout allow the new alignment?
990                 LyXLayout_ptr const & layout = pit->layout();
991
992                 if (align == LYX_ALIGN_LAYOUT)
993                         align = layout->align;
994                 if (align & layout->alignpossible) {
995                         if (align == layout->align)
996                                 params.align(LYX_ALIGN_LAYOUT);
997                         else
998                                 params.align(align);
999                 }
1000                 pit->setLabelWidthString(labelwidthstring);
1001                 params.noindent(noindent);
1002                 tmppit = boost::prior(pit);
1003         }
1004
1005         redoParagraphs(selection.start, endpit);
1006
1007         clearSelection();
1008         setCursor(selection.start.par(), selection.start.pos());
1009         selection.cursor = cursor;
1010         setCursor(selection.end.par(), selection.end.pos());
1011         setSelection();
1012         setCursor(tmpcursor.par(), tmpcursor.pos());
1013         if (inset_owner)
1014                 bv()->updateInset(inset_owner);
1015 }
1016
1017
1018 // set the counter of a paragraph. This includes the labels
1019 void LyXText::setCounter(Buffer const * buf, ParagraphList::iterator pit)
1020 {
1021         LyXTextClass const & textclass = buf->params.getLyXTextClass();
1022         LyXLayout_ptr const & layout = pit->layout();
1023
1024         if (pit != ownerParagraphs().begin()) {
1025
1026                 pit->params().appendix(boost::prior(pit)->params().appendix());
1027                 if (!pit->params().appendix() &&
1028                     pit->params().startOfAppendix()) {
1029                         pit->params().appendix(true);
1030                         textclass.counters().reset();
1031                 }
1032                 pit->enumdepth = boost::prior(pit)->enumdepth;
1033                 pit->itemdepth = boost::prior(pit)->itemdepth;
1034         } else {
1035                 pit->params().appendix(pit->params().startOfAppendix());
1036                 pit->enumdepth = 0;
1037                 pit->itemdepth = 0;
1038         }
1039
1040         /* Maybe we have to increment the enumeration depth.
1041          * BUT, enumeration in a footnote is considered in isolation from its
1042          *      surrounding paragraph so don't increment if this is the
1043          *      first line of the footnote
1044          * AND, bibliographies can't have their depth changed ie. they
1045          *      are always of depth 0
1046          */
1047         if (pit != ownerParagraphs().begin()
1048             && boost::prior(pit)->getDepth() < pit->getDepth()
1049             && boost::prior(pit)->layout()->labeltype == LABEL_COUNTER_ENUMI
1050             && pit->enumdepth < 3
1051             && layout->labeltype != LABEL_BIBLIO) {
1052                 pit->enumdepth++;
1053         }
1054
1055         // Maybe we have to decrement the enumeration depth, see note above
1056         if (pit != ownerParagraphs().begin()
1057             && boost::prior(pit)->getDepth() > pit->getDepth()
1058             && layout->labeltype != LABEL_BIBLIO) {
1059                 pit->enumdepth = depthHook(pit, ownerParagraphs(),
1060                                            pit->getDepth())->enumdepth;
1061         }
1062
1063         if (!pit->params().labelString().empty()) {
1064                 pit->params().labelString(string());
1065         }
1066
1067         if (layout->margintype == MARGIN_MANUAL) {
1068                 if (pit->params().labelWidthString().empty()) {
1069                         pit->setLabelWidthString(layout->labelstring());
1070                 }
1071         } else {
1072                 pit->setLabelWidthString(string());
1073         }
1074
1075         // is it a layout that has an automatic label?
1076         if (layout->labeltype >= LABEL_COUNTER_CHAPTER) {
1077                 int const i = layout->labeltype - LABEL_COUNTER_CHAPTER;
1078
1079                 ostringstream s;
1080
1081                 if (i >= 0 && i <= buf->params.secnumdepth) {
1082                         string numbertype;
1083                         string langtype;
1084
1085                         textclass.counters().step(layout->latexname());
1086
1087                         // Is there a label? Useful for Chapter layout
1088                         if (!pit->params().appendix()) {
1089                                 s << layout->labelstring();
1090                         } else {
1091                                 s << layout->labelstring_appendix();
1092                         }
1093
1094                         // Use of an integer is here less than elegant. For now.
1095                         int head = textclass.maxcounter() - LABEL_COUNTER_CHAPTER;
1096                         if (!pit->params().appendix()) {
1097                                 numbertype = "sectioning";
1098                         } else {
1099                                 numbertype = "appendix";
1100                                 if (pit->isRightToLeftPar(buf->params))
1101                                         langtype = "hebrew";
1102                                 else
1103                                         langtype = "latin";
1104                         }
1105
1106                         s << textclass.counters()
1107                                 .numberLabel(layout->latexname(),
1108                                              numbertype, langtype, head);
1109
1110                         pit->params().labelString(STRCONV(s.str()));
1111
1112                         // reset enum counters
1113                         textclass.counters().reset("enum");
1114                 } else if (layout->labeltype < LABEL_COUNTER_ENUMI) {
1115                         textclass.counters().reset("enum");
1116                 } else if (layout->labeltype == LABEL_COUNTER_ENUMI) {
1117                         // FIXME
1118                         // Yes I know this is a really, really! bad solution
1119                         // (Lgb)
1120                         string enumcounter("enum");
1121
1122                         switch (pit->enumdepth) {
1123                         case 2:
1124                                 enumcounter += 'i';
1125                         case 1:
1126                                 enumcounter += 'i';
1127                         case 0:
1128                                 enumcounter += 'i';
1129                                 break;
1130                         case 3:
1131                                 enumcounter += "iv";
1132                                 break;
1133                         default:
1134                                 // not a valid enumdepth...
1135                                 break;
1136                         }
1137
1138                         textclass.counters().step(enumcounter);
1139
1140                         s << textclass.counters()
1141                                 .numberLabel(enumcounter, "enumeration");
1142                         pit->params().labelString(STRCONV(s.str()));
1143                 }
1144         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
1145                 textclass.counters().step("bibitem");
1146                 int number = textclass.counters().value("bibitem");
1147                 if (pit->bibitem()) {
1148                         pit->bibitem()->setCounter(number);
1149                         pit->params().labelString(layout->labelstring());
1150                 }
1151                 // In biblio should't be following counters but...
1152         } else {
1153                 string s = layout->labelstring();
1154
1155                 // the caption hack:
1156                 if (layout->labeltype == LABEL_SENSITIVE) {
1157                         ParagraphList::iterator tmppit = pit;
1158                         Inset * in = 0;
1159                         bool isOK = false;
1160                         while (tmppit != ownerParagraphs().end() &&
1161                                tmppit->inInset()
1162                                // the single '=' is intended below
1163                                && (in = tmppit->inInset()->owner())) {
1164                                 if (in->lyxCode() == Inset::FLOAT_CODE ||
1165                                     in->lyxCode() == Inset::WRAP_CODE) {
1166                                         isOK = true;
1167                                         break;
1168                                 } else {
1169                                         tmppit = in->parOwner();
1170                                 }
1171                         }
1172
1173                         if (isOK) {
1174                                 Floating const & fl
1175                                         = textclass.floats().getType(static_cast<InsetFloat*>(in)->type());
1176
1177                                 textclass.counters().step(fl.type());
1178
1179                                 // Doesn't work... yet.
1180 #if USE_BOOST_FORMAT
1181                                 s = boost::io::str(boost::format(_("%1$s #:")) % fl.name());
1182                                 // s << boost::format(_("%1$s %1$d:")
1183                                 //        % fl.name()
1184                                 //        % buf->counters().value(fl.name());
1185 #else
1186                                 ostringstream o;
1187                                 //o << fl.name() << ' ' << buf->counters().value(fl.name()) << ":";
1188                                 o << fl.name() << " #:";
1189                                 s = STRCONV(o.str());
1190 #endif
1191                         } else {
1192                                 // par->SetLayout(0);
1193                                 // s = layout->labelstring;
1194                                 s = _("Senseless: ");
1195                         }
1196                 }
1197                 pit->params().labelString(s);
1198
1199                 // reset the enumeration counter. They are always reset
1200                 // when there is any other layout between
1201                 // Just fall-through between the cases so that all
1202                 // enum counters deeper than enumdepth is also reset.
1203                 switch (pit->enumdepth) {
1204                 case 0:
1205                         textclass.counters().reset("enumi");
1206                 case 1:
1207                         textclass.counters().reset("enumii");
1208                 case 2:
1209                         textclass.counters().reset("enumiii");
1210                 case 3:
1211                         textclass.counters().reset("enumiv");
1212                 }
1213         }
1214 }
1215
1216
1217 // Updates all counters. Paragraphs with changed label string will be rebroken
1218 void LyXText::updateCounters()
1219 {
1220         RowList::iterator rowit = rows().begin();
1221         ParagraphList::iterator pit = rowit->par();
1222
1223         // CHECK if this is really needed. (Lgb)
1224         bv()->buffer()->params.getLyXTextClass().counters().reset();
1225
1226         for (; pit != ownerParagraphs().end(); ++pit) {
1227                 while (rowit->par() != pit)
1228                         ++rowit;
1229
1230                 string const oldLabel = pit->params().labelString();
1231
1232                 int maxdepth = 0;
1233                 if (pit != ownerParagraphs().begin())
1234                         maxdepth = boost::prior(pit)->getMaxDepthAfter();
1235
1236                 if (pit->params().depth() > maxdepth)
1237                         pit->params().depth(maxdepth);
1238
1239                 // setCounter can potentially change the labelString.
1240                 setCounter(bv()->buffer(), pit);
1241
1242                 string const & newLabel = pit->params().labelString();
1243
1244                 if (oldLabel.empty() && !newLabel.empty()) {
1245                         removeParagraph(rowit);
1246                         appendParagraph(rowit);
1247                 }
1248         }
1249 }
1250
1251
1252 void LyXText::insertInset(Inset * inset)
1253 {
1254         if (!cursor.par()->insetAllowed(inset->lyxCode()))
1255                 return;
1256         setUndo(bv(), Undo::FINISH, &*cursor.par(),
1257                 &*boost::next(cursor.par()));
1258         freezeUndo();
1259         cursor.par()->insertInset(cursor.pos(), inset);
1260         // Just to rebreak and refresh correctly.
1261         // The character will not be inserted a second time
1262         insertChar(Paragraph::META_INSET);
1263         // If we enter a highly editable inset the cursor should be to before
1264         // the inset. This couldn't happen before as Undo was not handled inside
1265         // inset now after the Undo LyX tries to call inset->Edit(...) again
1266         // and cannot do this as the cursor is behind the inset and GetInset
1267         // does not return the inset!
1268         if (isHighlyEditableInset(inset)) {
1269                 cursorLeft(true);
1270         }
1271         unFreezeUndo();
1272 }
1273
1274
1275 void LyXText::cutSelection(bool doclear, bool realcut)
1276 {
1277         // Stuff what we got on the clipboard. Even if there is no selection.
1278
1279         // There is a problem with having the stuffing here in that the
1280         // larger the selection the slower LyX will get. This can be
1281         // solved by running the line below only when the selection has
1282         // finished. The solution used currently just works, to make it
1283         // faster we need to be more clever and probably also have more
1284         // calls to stuffClipboard. (Lgb)
1285         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1286
1287         // This doesn't make sense, if there is no selection
1288         if (!selection.set())
1289                 return;
1290
1291         // OK, we have a selection. This is always between selection.start
1292         // and selection.end
1293
1294         // make sure that the depth behind the selection are restored, too
1295         ParagraphList::iterator endpit = boost::next(selection.end.par());
1296         ParagraphList::iterator undoendpit = endpit;
1297         ParagraphList::iterator pars_end = ownerParagraphs().end();
1298
1299         if (endpit != pars_end && endpit->getDepth()) {
1300                 while (endpit != pars_end && endpit->getDepth()) {
1301                         ++endpit;
1302                         undoendpit = endpit;
1303                 }
1304         } else if (endpit != pars_end) {
1305                 // because of parindents etc.
1306                 ++endpit;
1307         }
1308
1309         setUndo(bv(), Undo::DELETE, &*selection.start.par(), &*undoendpit);
1310
1311         // there are two cases: cut only within one paragraph or
1312         // more than one paragraph
1313         if (selection.start.par() == selection.end.par()) {
1314                 // only within one paragraph
1315                 endpit = selection.end.par();
1316                 int pos = selection.end.pos();
1317                 CutAndPaste::cutSelection(&*selection.start.par(), &*endpit,
1318                                           selection.start.pos(), pos,
1319                                           bv()->buffer()->params.textclass,
1320                                           doclear, realcut);
1321                 selection.end.pos(pos);
1322         } else {
1323                 endpit = selection.end.par();
1324                 int pos = selection.end.pos();
1325                 CutAndPaste::cutSelection(&*selection.start.par(), &*endpit,
1326                                           selection.start.pos(), pos,
1327                                           bv()->buffer()->params.textclass,
1328                                           doclear, realcut);
1329                 cursor.par(endpit);
1330                 selection.end.par(endpit);
1331                 selection.end.pos(pos);
1332                 cursor.pos(selection.end.pos());
1333         }
1334         ++endpit;
1335
1336         // sometimes necessary
1337         if (doclear)
1338                 selection.start.par()->stripLeadingSpaces();
1339
1340         redoParagraphs(selection.start, endpit);
1341
1342         // cutSelection can invalidate the cursor so we need to set
1343         // it anew. (Lgb)
1344         // we prefer the end for when tracking changes
1345         cursor = selection.end;
1346
1347         // need a valid cursor. (Lgb)
1348         clearSelection();
1349
1350         setCursor(cursor.par(), cursor.pos());
1351         selection.cursor = cursor;
1352         updateCounters();
1353 }
1354
1355
1356 void LyXText::copySelection()
1357 {
1358         // stuff the selection onto the X clipboard, from an explicit copy request
1359         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1360
1361         // this doesnt make sense, if there is no selection
1362         if (!selection.set())
1363                 return;
1364
1365         // ok we have a selection. This is always between selection.start
1366         // and sel_end cursor
1367
1368         // copy behind a space if there is one
1369         while (selection.start.par()->size() > selection.start.pos()
1370                && selection.start.par()->isLineSeparator(selection.start.pos())
1371                && (selection.start.par() != selection.end.par()
1372                    || selection.start.pos() < selection.end.pos()))
1373                 selection.start.pos(selection.start.pos() + 1);
1374
1375         CutAndPaste::copySelection(&*selection.start.par(),
1376                                    &*selection.end.par(),
1377                                    selection.start.pos(), selection.end.pos(),
1378                                    bv()->buffer()->params.textclass);
1379 }
1380
1381
1382 void LyXText::pasteSelection()
1383 {
1384         // this does not make sense, if there is nothing to paste
1385         if (!CutAndPaste::checkPastePossible())
1386                 return;
1387
1388         setUndo(bv(), Undo::INSERT,
1389                 &*cursor.par(), &*boost::next(cursor.par()));
1390
1391         Paragraph * endpar;
1392         ParagraphList::iterator actpit = cursor.par();
1393         int pos = cursor.pos();
1394
1395         Paragraph * actpar = &*actpit;
1396         CutAndPaste::pasteSelection(&actpar, &endpar, pos,
1397                                     bv()->buffer()->params.textclass);
1398
1399         redoParagraphs(cursor, endpar);
1400
1401         setCursor(cursor.par(), cursor.pos());
1402         clearSelection();
1403
1404         selection.cursor = cursor;
1405         setCursor(actpit, pos);
1406         setSelection();
1407         updateCounters();
1408 }
1409
1410
1411 void LyXText::setSelectionRange(lyx::pos_type length)
1412 {
1413         if (!length)
1414                 return;
1415
1416         selection.cursor = cursor;
1417         while (length--)
1418                 cursorRight(bv());
1419         setSelection();
1420 }
1421
1422
1423 // simple replacing. The font of the first selected character is used
1424 void LyXText::replaceSelectionWithString(string const & str)
1425 {
1426         setCursorParUndo(bv());
1427         freezeUndo();
1428
1429         if (!selection.set()) { // create a dummy selection
1430                 selection.end = cursor;
1431                 selection.start = cursor;
1432         }
1433
1434         // Get font setting before we cut
1435         pos_type pos = selection.end.pos();
1436         LyXFont const font = selection.start.par()
1437                 ->getFontSettings(bv()->buffer()->params,
1438                                   selection.start.pos());
1439
1440         // Insert the new string
1441         for (string::const_iterator cit = str.begin(); cit != str.end(); ++cit) {
1442                 selection.end.par()->insertChar(pos, (*cit), font);
1443                 ++pos;
1444         }
1445
1446         // Cut the selection
1447         cutSelection(true, false);
1448
1449         unFreezeUndo();
1450 }
1451
1452
1453 // needed to insert the selection
1454 void LyXText::insertStringAsLines(string const & str)
1455 {
1456         ParagraphList::iterator pit = cursor.par();
1457         pos_type pos = cursor.pos();
1458         ParagraphList::iterator endpit = boost::next(cursor.par());
1459
1460         setCursorParUndo(bv());
1461
1462         // only to be sure, should not be neccessary
1463         clearSelection();
1464
1465         bv()->buffer()->insertStringAsLines(pit, pos, current_font, str);
1466
1467         redoParagraphs(cursor, endpit);
1468         setCursor(cursor.par(), cursor.pos());
1469         selection.cursor = cursor;
1470         setCursor(pit, pos);
1471         setSelection();
1472 }
1473
1474
1475 // turns double-CR to single CR, others where converted into one
1476 // blank. Then InsertStringAsLines is called
1477 void LyXText::insertStringAsParagraphs(string const & str)
1478 {
1479         string linestr(str);
1480         bool newline_inserted = false;
1481         for (string::size_type i = 0; i < linestr.length(); ++i) {
1482                 if (linestr[i] == '\n') {
1483                         if (newline_inserted) {
1484                                 // we know that \r will be ignored by
1485                                 // InsertStringA. Of course, it is a dirty
1486                                 // trick, but it works...
1487                                 linestr[i - 1] = '\r';
1488                                 linestr[i] = '\n';
1489                         } else {
1490                                 linestr[i] = ' ';
1491                                 newline_inserted = true;
1492                         }
1493                 } else if (IsPrintable(linestr[i])) {
1494                         newline_inserted = false;
1495                 }
1496         }
1497         insertStringAsLines(linestr);
1498 }
1499
1500
1501 void LyXText::checkParagraph(ParagraphList::iterator pit, pos_type pos)
1502 {
1503         LyXCursor tmpcursor;
1504
1505         int y = 0;
1506         pos_type z;
1507         RowList::iterator row = getRow(pit, pos, y);
1508         RowList::iterator beg = rows().begin();
1509
1510         // is there a break one row above
1511         if (row != beg
1512             && boost::prior(row)->par() == row->par()) {
1513                 z = rowBreakPoint(*boost::prior(row));
1514                 if (z >= row->pos()) {
1515                         // set the dimensions of the row above
1516                         y -= boost::prior(row)->height();
1517                         postPaint(y);
1518
1519                         breakAgain(boost::prior(row));
1520
1521                         // set the cursor again. Otherwise
1522                         // dangling pointers are possible
1523                         setCursor(cursor.par(), cursor.pos(),
1524                                   false, cursor.boundary());
1525                         selection.cursor = cursor;
1526                         return;
1527                 }
1528         }
1529
1530         int const tmpheight = row->height();
1531         pos_type const tmplast = lastPos(*this, row);
1532
1533         breakAgain(row);
1534         if (row->height() == tmpheight && lastPos(*this, row) == tmplast) {
1535                 postRowPaint(row, y);
1536         } else {
1537                 postPaint(y);
1538         }
1539
1540         // check the special right address boxes
1541         if (pit->layout()->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1542                 tmpcursor.par(pit);
1543                 tmpcursor.row(row);
1544                 tmpcursor.y(y);
1545                 tmpcursor.x(0);
1546                 tmpcursor.x_fix(0);
1547                 tmpcursor.pos(pos);
1548                 redoDrawingOfParagraph(tmpcursor);
1549         }
1550
1551         // set the cursor again. Otherwise dangling pointers are possible
1552         // also set the selection
1553
1554         if (selection.set()) {
1555                 tmpcursor = cursor;
1556                 setCursorIntern(selection.cursor.par(), selection.cursor.pos(),
1557                                 false, selection.cursor.boundary());
1558                 selection.cursor = cursor;
1559                 setCursorIntern(selection.start.par(),
1560                                 selection.start.pos(),
1561                                 false, selection.start.boundary());
1562                 selection.start = cursor;
1563                 setCursorIntern(selection.end.par(),
1564                                 selection.end.pos(),
1565                                 false, selection.end.boundary());
1566                 selection.end = cursor;
1567                 setCursorIntern(last_sel_cursor.par(),
1568                                 last_sel_cursor.pos(),
1569                                 false, last_sel_cursor.boundary());
1570                 last_sel_cursor = cursor;
1571                 cursor = tmpcursor;
1572         }
1573         setCursorIntern(cursor.par(), cursor.pos(),
1574                         false, cursor.boundary());
1575 }
1576
1577
1578 // returns false if inset wasn't found
1579 bool LyXText::updateInset(Inset * inset)
1580 {
1581         // first check the current paragraph
1582         int pos = cursor.par()->getPositionOfInset(inset);
1583         if (pos != -1) {
1584                 checkParagraph(cursor.par(), pos);
1585                 return true;
1586         }
1587
1588         // check every paragraph
1589
1590         ParagraphList::iterator par = ownerParagraphs().begin();
1591         ParagraphList::iterator end = ownerParagraphs().end();
1592         for (; par != end; ++par) {
1593                 pos = par->getPositionOfInset(inset);
1594                 if (pos != -1) {
1595                         checkParagraph(par, pos);
1596                         return true;
1597                 }
1598         };
1599
1600         return false;
1601 }
1602
1603
1604 bool LyXText::setCursor(ParagraphList::iterator pit,
1605                         pos_type pos,
1606                         bool setfont, bool boundary)
1607 {
1608         LyXCursor old_cursor = cursor;
1609         setCursorIntern(pit, pos, setfont, boundary);
1610         return deleteEmptyParagraphMechanism(old_cursor);
1611 }
1612
1613
1614 void LyXText::setCursor(LyXCursor & cur, ParagraphList::iterator pit,
1615                         pos_type pos, bool boundary)
1616 {
1617         lyx::Assert(pit != ownerParagraphs().end());
1618
1619         cur.par(pit);
1620         cur.pos(pos);
1621         cur.boundary(boundary);
1622
1623         // get the cursor y position in text
1624         int y = 0;
1625         RowList::iterator row = getRow(pit, pos, y);
1626         RowList::iterator beg = rows().begin();
1627
1628         RowList::iterator old_row = row;
1629         cur.irow(row);
1630         // if we are before the first char of this row and are still in the
1631         // same paragraph and there is a previous row then put the cursor on
1632         // the end of the previous row
1633         cur.iy(y + row->baseline());
1634         Inset * ins;
1635         if (row != beg && pos &&
1636                 boost::prior(row)->par() == row->par() &&
1637             pos < pit->size() &&
1638                 pit->getChar(pos) == Paragraph::META_INSET &&
1639                 (ins = pit->getInset(pos)) && (ins->needFullRow() || ins->display()))
1640         {
1641                 --row;
1642                 y -= row->height();
1643         }
1644
1645         cur.row(row);
1646         // y is now the beginning of the cursor row
1647         y += row->baseline();
1648         // y is now the cursor baseline
1649         cur.y(y);
1650
1651         pos_type last = lastPrintablePos(*this, old_row);
1652
1653         // None of these should happen, but we're scaredy-cats
1654         if (pos > pit->size()) {
1655                 lyxerr << "dont like 1 please report" << endl;
1656                 pos = 0;
1657                 cur.pos(0);
1658         } else if (pos > last + 1) {
1659                 lyxerr << "dont like 2 please report" << endl;
1660                 // This shouldn't happen.
1661                 pos = last + 1;
1662                 cur.pos(pos);
1663         } else if (pos < row->pos()) {
1664                 lyxerr << "dont like 3 please report" << endl;
1665                 pos = row->pos();
1666                 cur.pos(pos);
1667         }
1668
1669         // now get the cursors x position
1670         float x = getCursorX(row, pos, last, boundary);
1671         cur.x(int(x));
1672         cur.x_fix(cur.x());
1673         if (old_row != row) {
1674                 x = getCursorX(old_row, pos, last, boundary);
1675                 cur.ix(int(x));
1676         } else
1677                 cur.ix(cur.x());
1678 /* We take out this for the time being because 1) the redraw code is not
1679    prepared to this yet and 2) because some good policy has yet to be decided
1680    while editting: for instance how to act on rows being created/deleted
1681    because of DEPM.
1682 */
1683 #if 0
1684         //if the cursor is in a visible row, anchor to it
1685         int topy = top_y();
1686         if (topy < y && y < topy + bv()->workHeight())
1687                 anchor_row(row);
1688 #endif
1689 }
1690
1691
1692 float LyXText::getCursorX(RowList::iterator rit,
1693                           pos_type pos, pos_type last, bool boundary) const
1694 {
1695         pos_type cursor_vpos = 0;
1696         float x;
1697         float fill_separator;
1698         float fill_hfill;
1699         float fill_label_hfill;
1700         // This call HAS to be here because of the BidiTables!!!
1701         prepareToPrint(rit, x, fill_separator, fill_hfill,
1702                        fill_label_hfill);
1703
1704         ParagraphList::iterator rit_par = rit->par();
1705         pos_type const rit_pos = rit->pos();
1706
1707         if (last < rit_pos)
1708                 cursor_vpos = rit_pos;
1709         else if (pos > last && !boundary)
1710                 cursor_vpos = (rit_par->isRightToLeftPar(bv()->buffer()->params))
1711                         ? rit_pos : last + 1;
1712         else if (pos > rit_pos && (pos > last || boundary))
1713                 /// Place cursor after char at (logical) position pos - 1
1714                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1715                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1716         else
1717                 /// Place cursor before char at (logical) position pos
1718                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1719                         ? log2vis(pos) : log2vis(pos) + 1;
1720
1721         pos_type body_pos = rit_par->beginningOfBody();
1722         if ((body_pos > 0) &&
1723             ((body_pos - 1 > last) || !rit_par->isLineSeparator(body_pos - 1)))
1724                 body_pos = 0;
1725
1726         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1727                 pos_type pos = vis2log(vpos);
1728                 if (body_pos > 0 && pos == body_pos - 1) {
1729                         x += fill_label_hfill +
1730                                 font_metrics::width(
1731                                         rit_par->layout()->labelsep,
1732                                         getLabelFont(bv()->buffer(), rit_par));
1733                         if (rit_par->isLineSeparator(body_pos - 1))
1734                                 x -= singleWidth(rit_par, body_pos - 1);
1735                 }
1736
1737                 if (hfillExpansion(*this, rit, pos)) {
1738                         x += singleWidth(rit_par, pos);
1739                         if (pos >= body_pos)
1740                                 x += fill_hfill;
1741                         else
1742                                 x += fill_label_hfill;
1743                 } else if (rit_par->isSeparator(pos)) {
1744                         x += singleWidth(rit_par, pos);
1745                         if (pos >= body_pos)
1746                                 x += fill_separator;
1747                 } else
1748                         x += singleWidth(rit_par, pos);
1749         }
1750         return x;
1751 }
1752
1753
1754 void LyXText::setCursorIntern(ParagraphList::iterator pit,
1755                               pos_type pos, bool setfont, bool boundary)
1756 {
1757         InsetText * it = static_cast<InsetText *>(pit->inInset());
1758         if (it) {
1759                 if (it != inset_owner) {
1760                         lyxerr[Debug::INSETS] << "InsetText   is " << it
1761                                               << endl
1762                                               << "inset_owner is "
1763                                               << inset_owner << endl;
1764 #ifdef WITH_WARNINGS
1765 #warning I believe this code is wrong. (Lgb)
1766 #warning Jürgen, have a look at this. (Lgb)
1767 #warning Hmmm, I guess you are right but we
1768 #warning should verify when this is needed
1769 #endif
1770                         // Jürgen, would you like to have a look?
1771                         // I guess we need to move the outer cursor
1772                         // and open and lock the inset (bla bla bla)
1773                         // stuff I don't know... so can you have a look?
1774                         // (Lgb)
1775                         // I moved the lyxerr stuff in here so we can see if
1776                         // this is actually really needed and where!
1777                         // (Jug)
1778                         // it->getLyXText(bv())->setCursorIntern(bv(), par, pos, setfont, boundary);
1779                         return;
1780                 }
1781         }
1782
1783         setCursor(cursor, pit, pos, boundary);
1784         if (setfont)
1785                 setCurrentFont();
1786 }
1787
1788
1789 void LyXText::setCurrentFont()
1790 {
1791         pos_type pos = cursor.pos();
1792         ParagraphList::iterator pit = cursor.par();
1793
1794         if (cursor.boundary() && pos > 0)
1795                 --pos;
1796
1797         if (pos > 0) {
1798                 if (pos == pit->size())
1799                         --pos;
1800                 else // potentional bug... BUG (Lgb)
1801                         if (pit->isSeparator(pos)) {
1802                                 if (pos > cursor.row()->pos() &&
1803                                     bidi_level(pos) % 2 ==
1804                                     bidi_level(pos - 1) % 2)
1805                                         --pos;
1806                                 else if (pos + 1 < pit->size())
1807                                         ++pos;
1808                         }
1809         }
1810
1811         current_font =
1812                 pit->getFontSettings(bv()->buffer()->params, pos);
1813         real_current_font = getFont(bv()->buffer(), pit, pos);
1814
1815         if (cursor.pos() == pit->size() &&
1816             isBoundary(bv()->buffer(), *pit, cursor.pos()) &&
1817             !cursor.boundary()) {
1818                 Language const * lang =
1819                         pit->getParLanguage(bv()->buffer()->params);
1820                 current_font.setLanguage(lang);
1821                 current_font.setNumber(LyXFont::OFF);
1822                 real_current_font.setLanguage(lang);
1823                 real_current_font.setNumber(LyXFont::OFF);
1824         }
1825 }
1826
1827
1828 // returns the column near the specified x-coordinate of the row
1829 // x is set to the real beginning of this column
1830 pos_type
1831 LyXText::getColumnNearX(RowList::iterator rit, int & x, bool & boundary) const
1832 {
1833         float tmpx = 0.0;
1834         float fill_separator;
1835         float fill_hfill;
1836         float fill_label_hfill;
1837
1838         prepareToPrint(rit, tmpx, fill_separator,
1839                        fill_hfill, fill_label_hfill);
1840
1841         pos_type vc = rit->pos();
1842         pos_type last = lastPrintablePos(*this, rit);
1843         pos_type c = 0;
1844
1845         ParagraphList::iterator rit_par = rit->par();
1846         LyXLayout_ptr const & layout = rit->par()->layout();
1847
1848         bool left_side = false;
1849
1850         pos_type body_pos = rit_par->beginningOfBody();
1851         float last_tmpx = tmpx;
1852
1853         if (body_pos > 0 &&
1854             (body_pos - 1 > last ||
1855              !rit_par->isLineSeparator(body_pos - 1)))
1856                 body_pos = 0;
1857
1858         // check for empty row
1859         if (!rit_par->size()) {
1860                 x = int(tmpx);
1861                 return 0;
1862         }
1863
1864         while (vc <= last && tmpx <= x) {
1865                 c = vis2log(vc);
1866                 last_tmpx = tmpx;
1867                 if (body_pos > 0 && c == body_pos - 1) {
1868                         tmpx += fill_label_hfill +
1869                                 font_metrics::width(layout->labelsep,
1870                                                getLabelFont(bv()->buffer(), &*rit_par));
1871                         if (rit_par->isLineSeparator(body_pos - 1))
1872                                 tmpx -= singleWidth(rit_par, body_pos - 1);
1873                 }
1874
1875                 if (hfillExpansion(*this, rit, c)) {
1876                         tmpx += singleWidth(rit_par, c);
1877                         if (c >= body_pos)
1878                                 tmpx += fill_hfill;
1879                         else
1880                                 tmpx += fill_label_hfill;
1881                 } else if (rit_par->isSeparator(c)) {
1882                         tmpx += singleWidth(rit_par, c);
1883                         if (c >= body_pos)
1884                                 tmpx+= fill_separator;
1885                 } else {
1886                         tmpx += singleWidth(rit_par, c);
1887                 }
1888                 ++vc;
1889         }
1890
1891         if ((tmpx + last_tmpx) / 2 > x) {
1892                 tmpx = last_tmpx;
1893                 left_side = true;
1894         }
1895
1896         if (vc > last + 1)  // This shouldn't happen.
1897                 vc = last + 1;
1898
1899         boundary = false;
1900         // This (rtl_support test) is not needed, but gives
1901         // some speedup if rtl_support=false
1902         bool const lastrow = lyxrc.rtl_support &&
1903                 (boost::next(rit) == rowlist_.end() ||
1904                  boost::next(rit)->par() != rit_par);
1905         // If lastrow is false, we don't need to compute
1906         // the value of rtl.
1907         bool const rtl = (lastrow)
1908                 ? rit_par->isRightToLeftPar(bv()->buffer()->params)
1909                 : false;
1910         if (lastrow &&
1911                  ((rtl &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1912                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1913                 c = last + 1;
1914         else if (vc == rit->pos()) {
1915                 c = vis2log(vc);
1916                 if (bidi_level(c) % 2 == 1)
1917                         ++c;
1918         } else {
1919                 c = vis2log(vc - 1);
1920                 bool const rtl = (bidi_level(c) % 2 == 1);
1921                 if (left_side == rtl) {
1922                         ++c;
1923                         boundary = isBoundary(bv()->buffer(), *rit_par, c);
1924                 }
1925         }
1926
1927         if (rit->pos() <= last && c > last
1928             && rit_par->isNewline(last)) {
1929                 if (bidi_level(last) % 2 == 0)
1930                         tmpx -= singleWidth(rit_par, last);
1931                 else
1932                         tmpx += singleWidth(rit_par, last);
1933                 c = last;
1934         }
1935
1936         c -= rit->pos();
1937         x = int(tmpx);
1938         return c;
1939 }
1940
1941
1942 void LyXText::setCursorFromCoordinates(int x, int y)
1943 {
1944         LyXCursor old_cursor = cursor;
1945
1946         setCursorFromCoordinates(cursor, x, y);
1947         setCurrentFont();
1948         deleteEmptyParagraphMechanism(old_cursor);
1949 }
1950
1951
1952 namespace {
1953
1954         /**
1955          * return true if the cursor given is at the end of a row,
1956          * and the next row is filled by an inset that spans an entire
1957          * row.
1958          */
1959         bool beforeFullRowInset(LyXText & lt, LyXCursor const & cur) {
1960                 RowList::iterator row = cur.row();
1961                 if (boost::next(row) == lt.rows().end())
1962                         return false;
1963                 Row const & next = *boost::next(row);
1964
1965                 if (next.pos() != cur.pos() || next.par() != cur.par())
1966                         return false;
1967
1968                 if (cur.pos() == cur.par()->size()
1969                     || !cur.par()->isInset(cur.pos()))
1970                         return false;
1971                 Inset const * inset = cur.par()->getInset(cur.pos());
1972                 if (inset->needFullRow() || inset->display())
1973                         return true;
1974                 return false;
1975         }
1976 }
1977
1978
1979 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1980 {
1981         // Get the row first.
1982
1983         RowList::iterator row = getRowNearY(y);
1984         bool bound = false;
1985         pos_type const column = getColumnNearX(row, x, bound);
1986         cur.par(row->par());
1987         cur.pos(row->pos() + column);
1988         cur.x(x);
1989         cur.y(y + row->baseline());
1990         cur.row(row);
1991
1992         if (beforeFullRowInset(*this, cur)) {
1993                 pos_type last = lastPrintablePos(*this, row);
1994                 float x = getCursorX(boost::next(row), cur.pos(), last, bound);
1995                 cur.ix(int(x));
1996                 cur.iy(y + row->height() + boost::next(row)->baseline());
1997                 cur.irow(boost::next(row));
1998         } else {
1999                 cur.iy(cur.y());
2000                 cur.ix(cur.x());
2001                 cur.irow(row);
2002         }
2003         cur.boundary(bound);
2004 }
2005
2006
2007 void LyXText::cursorLeft(bool internal)
2008 {
2009         if (cursor.pos() > 0) {
2010                 bool boundary = cursor.boundary();
2011                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
2012                 if (!internal && !boundary &&
2013                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos() + 1))
2014                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
2015         } else if (cursor.par() != ownerParagraphs().begin()) { // steps into the above paragraph.
2016                 ParagraphList::iterator pit = boost::prior(cursor.par());
2017                 setCursor(pit, pit->size());
2018         }
2019 }
2020
2021
2022 void LyXText::cursorRight(bool internal)
2023 {
2024         bool const at_end = (cursor.pos() == cursor.par()->size());
2025         bool const at_newline = !at_end &&
2026                 cursor.par()->isNewline(cursor.pos());
2027
2028         if (!internal && cursor.boundary() && !at_newline)
2029                 setCursor(cursor.par(), cursor.pos(), true, false);
2030         else if (!at_end) {
2031                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
2032                 if (!internal &&
2033                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos()))
2034                         setCursor(cursor.par(), cursor.pos(), true, true);
2035         } else if (boost::next(cursor.par()) != ownerParagraphs().end())
2036                 setCursor(boost::next(cursor.par()), 0);
2037 }
2038
2039
2040 void LyXText::cursorUp(bool selecting)
2041 {
2042 #if 1
2043         int x = cursor.x_fix();
2044         int y = cursor.y() - cursor.row()->baseline() - 1;
2045         setCursorFromCoordinates(x, y);
2046         if (!selecting) {
2047                 int topy = top_y();
2048                 int y1 = cursor.iy() - topy;
2049                 int y2 = y1;
2050                 y -= topy;
2051                 Inset * inset_hit = checkInsetHit(x, y1);
2052                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
2053                         inset_hit->edit(bv(), x, y - (y2 - y1), mouse_button::none);
2054                 }
2055         }
2056 #else
2057         setCursorFromCoordinates(bv(), cursor.x_fix(),
2058                                  cursor.y() - cursor.row()->baseline() - 1);
2059 #endif
2060 }
2061
2062
2063 void LyXText::cursorDown(bool selecting)
2064 {
2065 #if 1
2066         int x = cursor.x_fix();
2067         int y = cursor.y() - cursor.row()->baseline() +
2068                 cursor.row()->height() + 1;
2069         setCursorFromCoordinates(x, y);
2070         if (!selecting && cursor.row() == cursor.irow()) {
2071                 int topy = top_y();
2072                 int y1 = cursor.iy() - topy;
2073                 int y2 = y1;
2074                 y -= topy;
2075                 Inset * inset_hit = checkInsetHit(x, y1);
2076                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
2077                         inset_hit->edit(bv(), x, y - (y2 - y1), mouse_button::none);
2078                 }
2079         }
2080 #else
2081         setCursorFromCoordinates(bv(), cursor.x_fix(),
2082                                  cursor.y() - cursor.row()->baseline()
2083                                  + cursor.row()->height() + 1);
2084 #endif
2085 }
2086
2087
2088 void LyXText::cursorUpParagraph()
2089 {
2090         if (cursor.pos() > 0) {
2091                 setCursor(cursor.par(), 0);
2092         }
2093         else if (cursor.par() != ownerParagraphs().begin()) {
2094                 setCursor(boost::prior(cursor.par()), 0);
2095         }
2096 }
2097
2098
2099 void LyXText::cursorDownParagraph()
2100 {
2101         if (boost::next(cursor.par()) != ownerParagraphs().end()) {
2102                 setCursor(boost::next(cursor.par()), 0);
2103         } else {
2104                 setCursor(cursor.par(), cursor.par()->size());
2105         }
2106 }
2107
2108 // fix the cursor `cur' after a characters has been deleted at `where'
2109 // position. Called by deleteEmptyParagraphMechanism
2110 void LyXText::fixCursorAfterDelete(LyXCursor & cur,
2111                                    LyXCursor const & where)
2112 {
2113         // if cursor is not in the paragraph where the delete occured,
2114         // do nothing
2115         if (cur.par() != where.par())
2116                 return;
2117
2118         // if cursor position is after the place where the delete occured,
2119         // update it
2120         if (cur.pos() > where.pos())
2121                 cur.pos(cur.pos()-1);
2122
2123         // check also if we don't want to set the cursor on a spot behind the
2124         // pagragraph because we erased the last character.
2125         if (cur.pos() > cur.par()->size())
2126                 cur.pos(cur.par()->size());
2127
2128         // recompute row et al. for this cursor
2129         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
2130 }
2131
2132
2133 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
2134 {
2135         // Would be wrong to delete anything if we have a selection.
2136         if (selection.set())
2137                 return false;
2138
2139         // We allow all kinds of "mumbo-jumbo" when freespacing.
2140         if (old_cursor.par()->layout()->free_spacing
2141             || old_cursor.par()->isFreeSpacing()) {
2142                 return false;
2143         }
2144
2145         /* Ok I'll put some comments here about what is missing.
2146            I have fixed BackSpace (and thus Delete) to not delete
2147            double-spaces automagically. I have also changed Cut,
2148            Copy and Paste to hopefully do some sensible things.
2149            There are still some small problems that can lead to
2150            double spaces stored in the document file or space at
2151            the beginning of paragraphs. This happens if you have
2152            the cursor betwenn to spaces and then save. Or if you
2153            cut and paste and the selection have a space at the
2154            beginning and then save right after the paste. I am
2155            sure none of these are very hard to fix, but I will
2156            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
2157            that I can get some feedback. (Lgb)
2158         */
2159
2160         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
2161         // delete the LineSeparator.
2162         // MISSING
2163
2164         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
2165         // delete the LineSeparator.
2166         // MISSING
2167
2168         // If the pos around the old_cursor were spaces, delete one of them.
2169         if (old_cursor.par() != cursor.par()
2170             || old_cursor.pos() != cursor.pos()) {
2171                 // Only if the cursor has really moved
2172
2173                 if (old_cursor.pos() > 0
2174                     && old_cursor.pos() < old_cursor.par()->size()
2175                     && old_cursor.par()->isLineSeparator(old_cursor.pos())
2176                     && old_cursor.par()->isLineSeparator(old_cursor.pos() - 1)) {
2177                         old_cursor.par()->erase(old_cursor.pos() - 1);
2178                         redoParagraphs(old_cursor, boost::next(old_cursor.par()));
2179
2180 #ifdef WITH_WARNINGS
2181 #warning This will not work anymore when we have multiple views of the same buffer
2182 // In this case, we will have to correct also the cursors held by
2183 // other bufferviews. It will probably be easier to do that in a more
2184 // automated way in LyXCursor code. (JMarc 26/09/2001)
2185 #endif
2186                         // correct all cursors held by the LyXText
2187                         fixCursorAfterDelete(cursor, old_cursor);
2188                         fixCursorAfterDelete(selection.cursor,
2189                                              old_cursor);
2190                         fixCursorAfterDelete(selection.start,
2191                                              old_cursor);
2192                         fixCursorAfterDelete(selection.end, old_cursor);
2193                         fixCursorAfterDelete(last_sel_cursor,
2194                                              old_cursor);
2195                         fixCursorAfterDelete(toggle_cursor, old_cursor);
2196                         fixCursorAfterDelete(toggle_end_cursor,
2197                                              old_cursor);
2198                         return false;
2199                 }
2200         }
2201
2202         // don't delete anything if this is the ONLY paragraph!
2203         if (ownerParagraphs().size() == 1)
2204                 return false;
2205
2206         // Do not delete empty paragraphs with keepempty set.
2207         if (old_cursor.par()->layout()->keepempty)
2208                 return false;
2209
2210         // only do our magic if we changed paragraph
2211         if (old_cursor.par() == cursor.par())
2212                 return false;
2213
2214         // record if we have deleted a paragraph
2215         // we can't possibly have deleted a paragraph before this point
2216         bool deleted = false;
2217
2218         if (old_cursor.par()->empty() ||
2219             (old_cursor.par()->size() == 1 &&
2220              old_cursor.par()->isLineSeparator(0))) {
2221                 // ok, we will delete anything
2222                 LyXCursor tmpcursor;
2223
2224                 deleted = true;
2225
2226                 bool selection_position_was_oldcursor_position = (
2227                         selection.cursor.par()  == old_cursor.par()
2228                         && selection.cursor.pos() == old_cursor.pos());
2229
2230                 if (old_cursor.row() != rows().begin()) {
2231                         RowList::iterator
2232                                 prevrow = boost::prior(old_cursor.row());
2233                         const_cast<LyXText *>(this)->postPaint(old_cursor.y() - old_cursor.row()->baseline() - prevrow->height());
2234                         tmpcursor = cursor;
2235                         cursor = old_cursor; // that undo can restore the right cursor position
2236                         #warning FIXME. --end() iterator is usable here
2237                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2238                         while (endpit != ownerParagraphs().end() &&
2239                                endpit->getDepth()) {
2240                                 ++endpit;
2241                         }
2242
2243                         setUndo(bv(), Undo::DELETE, &*old_cursor.par(), &*endpit);
2244                         cursor = tmpcursor;
2245
2246                         // delete old row
2247                         removeRow(old_cursor.row());
2248                         // delete old par
2249                         ownerParagraphs().erase(old_cursor.par());
2250
2251                         /* Breakagain the next par. Needed because of
2252                          * the parindent that can occur or dissappear.
2253                          * The next row can change its height, if
2254                          * there is another layout before */
2255                         if (boost::next(prevrow) != rows().end()) {
2256                                 breakAgain(boost::next(prevrow));
2257                                 updateCounters();
2258                         }
2259                         setHeightOfRow(prevrow);
2260                 } else {
2261                         RowList::iterator nextrow = boost::next(old_cursor.row());
2262                         const_cast<LyXText *>(this)->postPaint(
2263                                 old_cursor.y() - old_cursor.row()->baseline());
2264
2265                         tmpcursor = cursor;
2266                         cursor = old_cursor; // that undo can restore the right cursor position
2267 #warning FIXME. --end() iterator is usable here
2268                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2269                         while (endpit != ownerParagraphs().end() &&
2270                                endpit->getDepth()) {
2271                                 ++endpit;
2272                         }
2273
2274                         setUndo(bv(), Undo::DELETE, &*old_cursor.par(), &*endpit);
2275                         cursor = tmpcursor;
2276
2277                         // delete old row
2278                         removeRow(old_cursor.row());
2279                         // delete old par
2280                         ownerParagraphs().erase(old_cursor.par());
2281
2282                         /* Breakagain the next par. Needed because of
2283                            the parindent that can occur or dissappear.
2284                            The next row can change its height, if
2285                            there is another layout before */
2286                         if (nextrow != rows().end()) {
2287                                 breakAgain(nextrow);
2288                                 updateCounters();
2289                         }
2290                 }
2291
2292                 // correct cursor y
2293                 setCursorIntern(cursor.par(), cursor.pos());
2294
2295                 if (selection_position_was_oldcursor_position) {
2296                         // correct selection
2297                         selection.cursor = cursor;
2298                 }
2299         }
2300         if (!deleted) {
2301                 if (old_cursor.par()->stripLeadingSpaces()) {
2302                         redoParagraphs(old_cursor, boost::next(old_cursor.par()));
2303                         // correct cursor y
2304                         setCursorIntern(cursor.par(), cursor.pos());
2305                         selection.cursor = cursor;
2306                 }
2307         }
2308         return deleted;
2309 }
2310
2311
2312 ParagraphList & LyXText::ownerParagraphs() const
2313 {
2314         if (inset_owner) {
2315                 return inset_owner->paragraphs;
2316         }
2317         return bv_owner->buffer()->paragraphs;
2318 }
2319
2320
2321 LyXText::refresh_status LyXText::refreshStatus() const
2322 {
2323         return refresh_status_;
2324 }
2325
2326
2327 void LyXText::clearPaint()
2328 {
2329         refresh_status_ = REFRESH_NONE;
2330         refresh_row = rows().end();
2331         refresh_y = 0;
2332 }
2333
2334
2335 void LyXText::postPaint(int start_y)
2336 {
2337         refresh_status old = refresh_status_;
2338
2339         refresh_status_ = REFRESH_AREA;
2340         refresh_row = rows().end();
2341
2342         if (old != REFRESH_NONE && refresh_y < start_y)
2343                 return;
2344
2345         refresh_y = start_y;
2346
2347         if (!inset_owner)
2348                 return;
2349
2350         // We are an inset's lyxtext. Tell the top-level lyxtext
2351         // it needs to update the row we're in.
2352         LyXText * t = bv()->text;
2353         t->postRowPaint(t->cursor.row(), t->cursor.y() - t->cursor.row()->baseline());
2354 }
2355
2356
2357 // FIXME: we should probably remove this y parameter,
2358 // make refresh_y be 0, and use row->y etc.
2359 void LyXText::postRowPaint(RowList::iterator rit, int start_y)
2360 {
2361         if (refresh_status_ != REFRESH_NONE && refresh_y < start_y) {
2362                 refresh_status_ = REFRESH_AREA;
2363                 return;
2364         } else {
2365                 refresh_y = start_y;
2366         }
2367
2368         if (refresh_status_ == REFRESH_AREA)
2369                 return;
2370
2371         refresh_status_ = REFRESH_ROW;
2372         refresh_row = rit;
2373
2374         if (!inset_owner)
2375                 return;
2376
2377         // We are an inset's lyxtext. Tell the top-level lyxtext
2378         // it needs to update the row we're in.
2379         LyXText * t = bv()->text;
2380         t->postRowPaint(t->cursor.row(), t->cursor.y() - t->cursor.row()->baseline());
2381 }
2382
2383
2384 bool LyXText::isInInset() const
2385 {
2386         // Sub-level has non-null bv owner and
2387         // non-null inset owner.
2388         return inset_owner != 0 && bv_owner != 0;
2389 }
2390
2391
2392 int defaultRowHeight()
2393 {
2394         LyXFont const font(LyXFont::ALL_SANE);
2395         return int(font_metrics::maxAscent(font)
2396                  + font_metrics::maxDescent(font) * 1.5);
2397 }