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