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