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