]> git.lyx.org Git - lyx.git/blob - src/text2.C
Make buffer's member variables private; use accessor functions.
[lyx.git] / src / text2.C
1 /**
2  * \file text2.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Allan Rae
14  * \author Dekel Tsur
15  * \author Jürgen Vigna
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "lyxtext.h"
23
24 #include "buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferView.h"
27 #include "counters.h"
28 #include "CutAndPaste.h"
29 #include "debug.h"
30 #include "errorlist.h"
31 #include "Floating.h"
32 #include "FloatList.h"
33 #include "funcrequest.h"
34 #include "gettext.h"
35 #include "language.h"
36 #include "lyxrc.h"
37 #include "lyxrow.h"
38 #include "lyxrow_funcs.h"
39 #include "metricsinfo.h"
40 #include "paragraph_funcs.h"
41 #include "ParagraphParameters.h"
42 #include "undo_funcs.h"
43
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46
47 #include "insets/insetbibitem.h"
48 #include "insets/insetenv.h"
49 #include "insets/insetfloat.h"
50 #include "insets/insetwrap.h"
51
52 #include "support/LAssert.h"
53 #include "support/lstrings.h"
54 #include "support/textutils.h"
55
56 #include <boost/tuple/tuple.hpp>
57
58 #include "support/std_sstream.h"
59
60 using namespace lyx::support;
61
62 using std::endl;
63
64 using std::ostringstream;
65
66 using lyx::pos_type;
67
68
69 LyXText::LyXText(BufferView * bv, InsetText * inset, bool ininset,
70           ParagraphList & paragraphs)
71         : height(0), width(0), anchor_y_(0),
72           inset_owner(inset), the_locking_inset(0), bv_owner(bv),
73           in_inset_(ininset), paragraphs_(paragraphs)
74 {
75 }
76
77
78 void LyXText::init(BufferView * bview)
79 {
80         bv_owner = bview;
81
82         ParagraphList::iterator const beg = ownerParagraphs().begin();
83         ParagraphList::iterator const end = ownerParagraphs().end();
84         for (ParagraphList::iterator pit = beg; pit != end; ++pit)
85                 pit->rows.clear();
86
87         width = 0;
88         height = 0;
89
90         anchor_y_ = 0;
91
92         current_font = getFont(beg, 0);
93
94         redoParagraphs(beg, end);
95         setCursorIntern(beg, 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 LyXFont LyXText::getFont(ParagraphList::iterator pit, pos_type pos) const
108 {
109         Assert(pos >= 0);
110
111         LyXLayout_ptr const & layout = pit->layout();
112 #warning broken?
113         BufferParams const & params = bv()->buffer()->params();
114
115         // We specialize the 95% common case:
116         if (!pit->getDepth()) {
117                 if (layout->labeltype == LABEL_MANUAL
118                     && pos < pit->beginningOfBody()) {
119                         // 1% goes here
120                         LyXFont f = pit->getFontSettings(params, pos);
121                         if (pit->inInset())
122                                 pit->inInset()->getDrawFont(f);
123                         return f.realize(layout->reslabelfont);
124                 } else {
125                         LyXFont f = pit->getFontSettings(params, pos);
126                         if (pit->inInset())
127                                 pit->inInset()->getDrawFont(f);
128                         return f.realize(layout->resfont);
129                 }
130         }
131
132         // The uncommon case need not be optimized as much
133
134         LyXFont layoutfont;
135
136         if (pos < pit->beginningOfBody()) {
137                 // 1% goes here
138                 layoutfont = layout->labelfont;
139         } else {
140                 // 99% goes here
141                 layoutfont = layout->font;
142         }
143
144         LyXFont tmpfont = pit->getFontSettings(params, pos);
145         tmpfont.realize(layoutfont);
146
147         if (pit->inInset())
148                 pit->inInset()->getDrawFont(tmpfont);
149
150         // Realize with the fonts of lesser depth.
151         tmpfont.realize(outerFont(pit, ownerParagraphs()));
152         tmpfont.realize(defaultfont_);
153
154         return tmpfont;
155 }
156
157
158 LyXFont LyXText::getLayoutFont(ParagraphList::iterator pit) const
159 {
160         LyXLayout_ptr const & layout = pit->layout();
161
162         if (!pit->getDepth())
163                 return layout->resfont;
164
165         LyXFont font = layout->font;
166         // Realize with the fonts of lesser depth.
167         font.realize(outerFont(pit, ownerParagraphs()));
168         font.realize(defaultfont_);
169
170         return font;
171 }
172
173
174 LyXFont LyXText::getLabelFont(ParagraphList::iterator pit) const
175 {
176         LyXLayout_ptr const & layout = pit->layout();
177
178         if (!pit->getDepth())
179                 return layout->reslabelfont;
180
181         LyXFont font = layout->labelfont;
182         // Realize with the fonts of lesser depth.
183         font.realize(outerFont(pit, ownerParagraphs()));
184         font.realize(defaultfont_);
185
186         return font;
187 }
188
189
190 void LyXText::setCharFont(ParagraphList::iterator pit,
191                           pos_type pos, LyXFont const & fnt,
192                           bool toggleall)
193 {
194         BufferParams const & params = bv()->buffer()->params();
195         LyXFont font = getFont(pit, pos);
196         font.update(fnt, params.language, toggleall);
197         // Let the insets convert their font
198         if (pit->isInset(pos)) {
199                 InsetOld * inset = pit->getInset(pos);
200                 if (isEditableInset(inset)) {
201                         static_cast<UpdatableInset *>(inset)
202                                 ->setFont(bv(), fnt, toggleall, true);
203                 }
204         }
205
206         // Plug through to version below:
207         setCharFont(pit, pos, font);
208 }
209
210
211 void LyXText::setCharFont(
212         ParagraphList::iterator pit, pos_type pos, LyXFont const & fnt)
213 {
214         LyXFont font = fnt;
215         LyXLayout_ptr const & layout = pit->layout();
216
217         // Get concrete layout font to reduce against
218         LyXFont layoutfont;
219
220         if (pos < pit->beginningOfBody())
221                 layoutfont = layout->labelfont;
222         else
223                 layoutfont = layout->font;
224
225         // Realize against environment font information
226         if (pit->getDepth()) {
227                 ParagraphList::iterator tp = pit;
228                 while (!layoutfont.resolved() &&
229                        tp != ownerParagraphs().end() &&
230                        tp->getDepth()) {
231                         tp = outerHook(tp, ownerParagraphs());
232                         if (tp != ownerParagraphs().end())
233                                 layoutfont.realize(tp->layout()->font);
234                 }
235         }
236
237         layoutfont.realize(defaultfont_);
238
239         // Now, reduce font against full layout font
240         font.reduce(layoutfont);
241
242         pit->setFont(pos, font);
243 }
244
245
246 InsetOld * LyXText::getInset() const
247 {
248         ParagraphList::iterator pit = cursor.par();
249         pos_type const pos = cursor.pos();
250
251         if (pos < pit->size() && pit->isInset(pos)) {
252                 return pit->getInset(pos);
253         }
254         return 0;
255 }
256
257
258 void LyXText::toggleInset()
259 {
260         InsetOld * inset = getInset();
261         // is there an editable inset at cursor position?
262         if (!isEditableInset(inset)) {
263                 // No, try to see if we are inside a collapsable inset
264                 if (inset_owner && inset_owner->owner()
265                     && inset_owner->owner()->isOpen()) {
266                         bv()->unlockInset(inset_owner->owner());
267                         inset_owner->owner()->close(bv());
268                         bv()->getLyXText()->cursorRight(bv());
269                 }
270                 return;
271         }
272         //bv()->owner()->message(inset->editMessage());
273
274         // do we want to keep this?? (JMarc)
275         if (!isHighlyEditableInset(inset))
276                 recordUndo(bv(), Undo::ATOMIC);
277
278         if (inset->isOpen())
279                 inset->close(bv());
280         else
281                 inset->open(bv());
282
283         bv()->updateInset(inset);
284 }
285
286
287 /* used in setlayout */
288 // Asger is not sure we want to do this...
289 void LyXText::makeFontEntriesLayoutSpecific(BufferParams const & params,
290                                             Paragraph & par)
291 {
292         LyXLayout_ptr const & layout = par.layout();
293         pos_type const psize = par.size();
294
295         LyXFont layoutfont;
296         for (pos_type pos = 0; pos < psize; ++pos) {
297                 if (pos < par.beginningOfBody())
298                         layoutfont = layout->labelfont;
299                 else
300                         layoutfont = layout->font;
301
302                 LyXFont tmpfont = par.getFontSettings(params, pos);
303                 tmpfont.reduce(layoutfont);
304                 par.setFont(pos, tmpfont);
305         }
306 }
307
308
309 ParagraphList::iterator
310 LyXText::setLayout(LyXCursor & cur, LyXCursor & sstart_cur,
311                    LyXCursor & send_cur,
312                    string const & layout)
313 {
314         ParagraphList::iterator endpit = boost::next(send_cur.par());
315         ParagraphList::iterator undoendpit = endpit;
316         ParagraphList::iterator pars_end = ownerParagraphs().end();
317
318         if (endpit != pars_end && endpit->getDepth()) {
319                 while (endpit != pars_end && endpit->getDepth()) {
320                         ++endpit;
321                         undoendpit = endpit;
322                 }
323         } else if (endpit != pars_end) {
324                 // because of parindents etc.
325                 ++endpit;
326         }
327
328         recordUndo(bv(), Undo::ATOMIC, sstart_cur.par(), boost::prior(undoendpit));
329
330         // ok we have a selection. This is always between sstart_cur
331         // and sel_end cursor
332         cur = sstart_cur;
333         ParagraphList::iterator pit = sstart_cur.par();
334         ParagraphList::iterator epit = boost::next(send_cur.par());
335
336         BufferParams const & bufparams = bv()->buffer()->params();
337         LyXLayout_ptr const & lyxlayout =
338                 bufparams.getLyXTextClass()[layout];
339
340         do {
341                 pit->applyLayout(lyxlayout);
342                 makeFontEntriesLayoutSpecific(bufparams, *pit);
343                 pit->params().spaceTop(lyxlayout->fill_top ?
344                                          VSpace(VSpace::VFILL)
345                                          : VSpace(VSpace::NONE));
346                 pit->params().spaceBottom(lyxlayout->fill_bottom ?
347                                             VSpace(VSpace::VFILL)
348                                             : VSpace(VSpace::NONE));
349                 if (lyxlayout->margintype == MARGIN_MANUAL)
350                         pit->setLabelWidthString(lyxlayout->labelstring());
351                 cur.par(pit);
352                 ++pit;
353         } while (pit != epit);
354
355         return endpit;
356 }
357
358
359 // set layout over selection and make a total rebreak of those paragraphs
360 void LyXText::setLayout(string const & layout)
361 {
362         LyXCursor tmpcursor = cursor;  // store the current cursor
363
364         // if there is no selection just set the layout
365         // of the current paragraph
366         if (!selection.set()) {
367                 selection.start = cursor;  // dummy selection
368                 selection.end = cursor;
369         }
370
371         // special handling of new environment insets
372         BufferParams const & params = bv()->buffer()->params();
373         LyXLayout_ptr const & lyxlayout = params.getLyXTextClass()[layout];
374         if (lyxlayout->is_environment) {
375                 // move everything in a new environment inset
376                 lyxerr << "setting layout " << layout << endl;
377                 bv()->owner()->dispatch(FuncRequest(LFUN_HOME));
378                 bv()->owner()->dispatch(FuncRequest(LFUN_ENDSEL));
379                 bv()->owner()->dispatch(FuncRequest(LFUN_CUT));
380                 InsetOld * inset = new InsetEnvironment(params, layout);
381                 if (bv()->insertInset(inset)) {
382                         //inset->edit(bv());
383                         //bv()->owner()->dispatch(FuncRequest(LFUN_PASTE));
384                 }
385                 else
386                         delete inset;
387                 return;
388         }
389
390         ParagraphList::iterator endpit = setLayout(cursor, selection.start,
391                                                    selection.end, layout);
392         redoParagraphs(selection.start.par(), endpit);
393
394         // we have to reset the selection, because the
395         // geometry could have changed
396         setCursor(selection.start.par(), selection.start.pos(), false);
397         selection.cursor = cursor;
398         setCursor(selection.end.par(), selection.end.pos(), false);
399         updateCounters();
400         clearSelection();
401         setSelection();
402         setCursor(tmpcursor.par(), tmpcursor.pos(), true);
403 }
404
405
406 bool LyXText::changeDepth(bv_funcs::DEPTH_CHANGE type, bool test_only)
407 {
408         ParagraphList::iterator pit = cursor.par();
409         ParagraphList::iterator end = cursor.par();
410         ParagraphList::iterator start = pit;
411
412         if (selection.set()) {
413                 pit = selection.start.par();
414                 end = selection.end.par();
415                 start = pit;
416         }
417
418         ParagraphList::iterator pastend = boost::next(end);
419
420         if (!test_only)
421                 recordUndo(bv(), Undo::ATOMIC, start, end);
422
423         bool changed = false;
424
425         int prev_after_depth = 0;
426 #warning parlist ... could be nicer ?
427         if (start != ownerParagraphs().begin()) {
428                 prev_after_depth = boost::prior(start)->getMaxDepthAfter();
429         }
430
431         while (true) {
432                 int const depth = pit->params().depth();
433                 if (type == bv_funcs::INC_DEPTH) {
434                         if (depth < prev_after_depth
435                             && pit->layout()->labeltype != LABEL_BIBLIO) {
436                                 changed = true;
437                                 if (!test_only)
438                                         pit->params().depth(depth + 1);
439                         }
440                 } else if (depth) {
441                         changed = true;
442                         if (!test_only)
443                                 pit->params().depth(depth - 1);
444                 }
445
446                 prev_after_depth = pit->getMaxDepthAfter();
447
448                 if (pit == end) {
449                         break;
450                 }
451
452                 ++pit;
453         }
454
455         if (test_only)
456                 return changed;
457
458         redoParagraphs(start, pastend);
459
460         // We need to actually move the text->cursor. I don't
461         // understand why ...
462         LyXCursor tmpcursor = cursor;
463
464         // we have to reset the visual selection because the
465         // geometry could have changed
466         if (selection.set()) {
467                 setCursor(selection.start.par(), selection.start.pos());
468                 selection.cursor = cursor;
469                 setCursor(selection.end.par(), selection.end.pos());
470         }
471
472         // this handles the counter labels, and also fixes up
473         // depth values for follow-on (child) paragraphs
474         updateCounters();
475
476         setSelection();
477         setCursor(tmpcursor.par(), tmpcursor.pos());
478
479         return changed;
480 }
481
482
483 // set font over selection and make a total rebreak of those paragraphs
484 void LyXText::setFont(LyXFont const & font, bool toggleall)
485 {
486         // if there is no selection just set the current_font
487         if (!selection.set()) {
488                 // Determine basis font
489                 LyXFont layoutfont;
490                 if (cursor.pos() < cursor.par()->beginningOfBody()) {
491                         layoutfont = getLabelFont(cursor.par());
492                 } else {
493                         layoutfont = getLayoutFont(cursor.par());
494                 }
495                 // Update current font
496                 real_current_font.update(font,
497                                          bv()->buffer()->params().language,
498                                          toggleall);
499
500                 // Reduce to implicit settings
501                 current_font = real_current_font;
502                 current_font.reduce(layoutfont);
503                 // And resolve it completely
504                 real_current_font.realize(layoutfont);
505
506                 return;
507         }
508
509         LyXCursor tmpcursor = cursor; // store the current cursor
510
511         // ok we have a selection. This is always between sel_start_cursor
512         // and sel_end cursor
513
514         recordUndo(bv(), Undo::ATOMIC, selection.start.par(), selection.end.par());
515         freezeUndo();
516         cursor = selection.start;
517         while (cursor.par() != selection.end.par() ||
518                cursor.pos() < selection.end.pos())
519         {
520                 if (cursor.pos() < cursor.par()->size()) {
521                         // an open footnote should behave like a closed one
522                         setCharFont(cursor.par(), cursor.pos(),
523                                     font, toggleall);
524                         cursor.pos(cursor.pos() + 1);
525                 } else {
526                         cursor.pos(0);
527                         cursor.par(boost::next(cursor.par()));
528                 }
529         }
530         unFreezeUndo();
531
532         redoParagraph(selection.start.par());
533
534         // we have to reset the selection, because the
535         // geometry could have changed, but we keep
536         // it for user convenience
537         setCursor(selection.start.par(), selection.start.pos());
538         selection.cursor = cursor;
539         setCursor(selection.end.par(), selection.end.pos());
540         setSelection();
541         setCursor(tmpcursor.par(), tmpcursor.pos(), true,
542                   tmpcursor.boundary());
543 }
544
545
546 int LyXText::redoParagraphInternal(ParagraphList::iterator pit)
547 {
548         RowList::iterator rit = pit->rows.begin();
549         RowList::iterator end = pit->rows.end();
550
551         // remove rows of paragraph, keep track of height changes
552         for (int i = 0; rit != end; ++rit, ++i)
553                 height -= rit->height();
554         pit->rows.clear();
555
556         // redo insets
557         InsetList::iterator ii = pit->insetlist.begin();
558         InsetList::iterator iend = pit->insetlist.end();
559         for (; ii != iend; ++ii) {
560                 Dimension dim;
561                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
562                 ii->inset->metrics(mi, dim);
563         }
564
565         // rebreak the paragraph
566         for (pos_type z = 0; z < pit->size() + 1; ) {
567                 Row row(z);
568                 z = rowBreakPoint(pit, row) + 1;
569                 row.end(z);
570                 pit->rows.push_back(row);
571         }
572
573         int par_width = 0;
574         // set height and fill and width of rows
575         int const ww = workWidth();
576         for (rit = pit->rows.begin(); rit != end; ++rit) {
577                 int const f = fill(pit, rit, ww);
578                 int const w = ww - f;
579                 par_width = std::max(par_width, w);
580                 rit->fill(f);
581                 rit->width(w);
582                 prepareToPrint(pit, rit);
583                 setHeightOfRow(pit, rit);
584                 height += rit->height();
585         }
586
587         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
588         return par_width;
589 }
590
591
592 int LyXText::redoParagraphs(ParagraphList::iterator start,
593   ParagraphList::iterator end)
594 {
595         int pars_width = 0;
596         for ( ; start != end; ++start) {
597                 int par_width = redoParagraphInternal(start);
598                 pars_width = std::max(par_width, pars_width);
599         }
600         updateRowPositions();
601         return pars_width;
602 }
603
604
605 void LyXText::redoParagraph(ParagraphList::iterator pit)
606 {
607         redoParagraphInternal(pit);
608         updateRowPositions();
609 }
610
611
612 void LyXText::fullRebreak()
613 {
614         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
615         redoCursor();
616         selection.cursor = cursor;
617 }
618
619
620 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
621 {
622         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
623         //      << " workWidth: " << workWidth() << endl;
624         //Assert(mi.base.textwidth);
625
626         // rebuild row cache
627         width  = 0;
628         ///height = 0;
629
630         //anchor_y_ = 0;
631         width = redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
632
633         // final dimension
634         dim.asc = firstRow()->ascent_of_text();
635         dim.des = height - dim.asc;
636         dim.wid = std::max(mi.base.textwidth, int(width));
637 }
638
639
640 // important for the screen
641
642
643 // the cursor set functions have a special mechanism. When they
644 // realize, that you left an empty paragraph, they will delete it.
645 // They also delete the corresponding row
646
647 // need the selection cursor:
648 void LyXText::setSelection()
649 {
650         TextCursor::setSelection();
651 }
652
653
654
655 void LyXText::clearSelection()
656 {
657         TextCursor::clearSelection();
658
659         // reset this in the bv_owner!
660         if (bv_owner && bv_owner->text)
661                 bv_owner->text->xsel_cache.set(false);
662 }
663
664
665 void LyXText::cursorHome()
666 {
667         setCursor(cursor.par(), cursorRow()->pos());
668 }
669
670
671 void LyXText::cursorEnd()
672 {
673         setCursor(cursor.par(), cursorRow()->end() - 1);
674 }
675
676
677 void LyXText::cursorTop()
678 {
679         setCursor(ownerParagraphs().begin(), 0);
680 }
681
682
683 void LyXText::cursorBottom()
684 {
685         ParagraphList::iterator lastpit =
686                 boost::prior(ownerParagraphs().end());
687         setCursor(lastpit, lastpit->size());
688 }
689
690
691 void LyXText::toggleFree(LyXFont const & font, bool toggleall)
692 {
693         // If the mask is completely neutral, tell user
694         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
695                 // Could only happen with user style
696                 bv()->owner()->message(_("No font change defined. Use Character under the Layout menu to define font change."));
697                 return;
698         }
699
700         // Try implicit word selection
701         // If there is a change in the language the implicit word selection
702         // is disabled.
703         LyXCursor resetCursor = cursor;
704         bool implicitSelection = (font.language() == ignore_language
705                                   && font.number() == LyXFont::IGNORE)
706                 ? selectWordWhenUnderCursor(lyx::WHOLE_WORD_STRICT) : false;
707
708         // Set font
709         setFont(font, toggleall);
710
711         // Implicit selections are cleared afterwards
712         //and cursor is set to the original position.
713         if (implicitSelection) {
714                 clearSelection();
715                 cursor = resetCursor;
716                 setCursor(cursor.par(), cursor.pos());
717                 selection.cursor = cursor;
718         }
719 }
720
721
722 string LyXText::getStringToIndex()
723 {
724         // Try implicit word selection
725         // If there is a change in the language the implicit word selection
726         // is disabled.
727         LyXCursor const reset_cursor = cursor;
728         bool const implicitSelection =
729                 selectWordWhenUnderCursor(lyx::PREVIOUS_WORD);
730
731         string idxstring;
732         if (!selection.set())
733                 bv()->owner()->message(_("Nothing to index!"));
734         else if (selection.start.par() != selection.end.par())
735                 bv()->owner()->message(_("Cannot index more than one paragraph!"));
736         else
737                 idxstring = selectionAsString(*bv()->buffer(), false);
738
739         // Reset cursors to their original position.
740         cursor = reset_cursor;
741         setCursor(cursor.par(), cursor.pos());
742         selection.cursor = cursor;
743
744         // Clear the implicit selection.
745         if (implicitSelection)
746                 clearSelection();
747
748         return idxstring;
749 }
750
751
752 // the DTP switches for paragraphs. LyX will store them in the first
753 // physical paragraph. When a paragraph is broken, the top settings rest,
754 // the bottom settings are given to the new one. So I can make sure,
755 // they do not duplicate themself and you cannnot make dirty things with
756 // them!
757
758 void LyXText::setParagraph(bool line_top, bool line_bottom,
759                            bool pagebreak_top, bool pagebreak_bottom,
760                            VSpace const & space_top,
761                            VSpace const & space_bottom,
762                            Spacing const & spacing,
763                            LyXAlignment align,
764                            string const & labelwidthstring,
765                            bool noindent)
766 {
767         LyXCursor tmpcursor = cursor;
768         if (!selection.set()) {
769                 selection.start = cursor;
770                 selection.end = cursor;
771         }
772
773         // make sure that the depth behind the selection are restored, too
774         ParagraphList::iterator endpit = boost::next(selection.end.par());
775         ParagraphList::iterator undoendpit = endpit;
776         ParagraphList::iterator pars_end = ownerParagraphs().end();
777
778         if (endpit != pars_end && endpit->getDepth()) {
779                 while (endpit != pars_end && endpit->getDepth()) {
780                         ++endpit;
781                         undoendpit = endpit;
782                 }
783         } else if (endpit != pars_end) {
784                 // because of parindents etc.
785                 ++endpit;
786         }
787
788         recordUndo(bv(), Undo::ATOMIC, selection.start.par(),
789                 boost::prior(undoendpit));
790
791
792         ParagraphList::iterator tmppit = selection.end.par();
793
794         while (tmppit != boost::prior(selection.start.par())) {
795                 setCursor(tmppit, 0);
796
797                 ParagraphList::iterator pit = cursor.par();
798                 ParagraphParameters & params = pit->params();
799
800                 params.lineTop(line_top);
801                 params.lineBottom(line_bottom);
802                 params.pagebreakTop(pagebreak_top);
803                 params.pagebreakBottom(pagebreak_bottom);
804                 params.spaceTop(space_top);
805                 params.spaceBottom(space_bottom);
806                 params.spacing(spacing);
807                 // does the layout allow the new alignment?
808                 LyXLayout_ptr const & layout = pit->layout();
809
810                 if (align == LYX_ALIGN_LAYOUT)
811                         align = layout->align;
812                 if (align & layout->alignpossible) {
813                         if (align == layout->align)
814                                 params.align(LYX_ALIGN_LAYOUT);
815                         else
816                                 params.align(align);
817                 }
818                 pit->setLabelWidthString(labelwidthstring);
819                 params.noindent(noindent);
820                 tmppit = boost::prior(pit);
821         }
822
823         redoParagraphs(selection.start.par(), endpit);
824
825         clearSelection();
826         setCursor(selection.start.par(), selection.start.pos());
827         selection.cursor = cursor;
828         setCursor(selection.end.par(), selection.end.pos());
829         setSelection();
830         setCursor(tmpcursor.par(), tmpcursor.pos());
831         if (inset_owner)
832                 bv()->updateInset(inset_owner);
833 }
834
835
836 // set the counter of a paragraph. This includes the labels
837 void LyXText::setCounter(Buffer const & buf, ParagraphList::iterator pit)
838 {
839         BufferParams const & bufparams = buf.params();
840         LyXTextClass const & textclass = bufparams.getLyXTextClass();
841         LyXLayout_ptr const & layout = pit->layout();
842
843         if (pit != ownerParagraphs().begin()) {
844
845                 pit->params().appendix(boost::prior(pit)->params().appendix());
846                 if (!pit->params().appendix() &&
847                     pit->params().startOfAppendix()) {
848                         pit->params().appendix(true);
849                         textclass.counters().reset();
850                 }
851                 pit->enumdepth = boost::prior(pit)->enumdepth;
852                 pit->itemdepth = boost::prior(pit)->itemdepth;
853         } else {
854                 pit->params().appendix(pit->params().startOfAppendix());
855                 pit->enumdepth = 0;
856                 pit->itemdepth = 0;
857         }
858
859         // Maybe we have to increment the enumeration depth.
860         // BUT, enumeration in a footnote is considered in isolation from its
861         //      surrounding paragraph so don't increment if this is the
862         //      first line of the footnote
863         // AND, bibliographies can't have their depth changed ie. they
864         //      are always of depth 0
865         if (pit != ownerParagraphs().begin()
866             && boost::prior(pit)->getDepth() < pit->getDepth()
867             && boost::prior(pit)->layout()->labeltype == LABEL_COUNTER_ENUMI
868             && pit->enumdepth < 3
869             && layout->labeltype != LABEL_BIBLIO) {
870                 pit->enumdepth++;
871         }
872
873         // Maybe we have to decrement the enumeration depth, see note above
874         if (pit != ownerParagraphs().begin()
875             && boost::prior(pit)->getDepth() > pit->getDepth()
876             && layout->labeltype != LABEL_BIBLIO) {
877                 pit->enumdepth = depthHook(pit, ownerParagraphs(),
878                                            pit->getDepth())->enumdepth;
879         }
880
881         if (!pit->params().labelString().empty()) {
882                 pit->params().labelString(string());
883         }
884
885         if (layout->margintype == MARGIN_MANUAL) {
886                 if (pit->params().labelWidthString().empty())
887                         pit->setLabelWidthString(layout->labelstring());
888         } else {
889                 pit->setLabelWidthString(string());
890         }
891
892         // is it a layout that has an automatic label?
893         if (layout->labeltype >= LABEL_COUNTER_CHAPTER) {
894                 int const i = layout->labeltype - LABEL_COUNTER_CHAPTER;
895
896                 ostringstream s;
897
898                 if (i >= 0 && i <= bufparams.secnumdepth) {
899                         string numbertype;
900                         string langtype;
901
902                         textclass.counters().step(layout->latexname());
903
904                         // Is there a label? Useful for Chapter layout
905                         if (!pit->params().appendix()) {
906                                 s << buf.B_(layout->labelstring());
907                         } else {
908                                 s << buf.B_(layout->labelstring_appendix());
909                         }
910
911                         // Use of an integer is here less than elegant. For now.
912                         int head = textclass.maxcounter() - LABEL_COUNTER_CHAPTER;
913                         if (!pit->params().appendix()) {
914                                 numbertype = "sectioning";
915                         } else {
916                                 numbertype = "appendix";
917                                 if (pit->isRightToLeftPar(bufparams))
918                                         langtype = "hebrew";
919                                 else
920                                         langtype = "latin";
921                         }
922
923                         s << " "
924                           << textclass.counters()
925                                 .numberLabel(layout->latexname(),
926                                              numbertype, langtype, head);
927
928                         pit->params().labelString(STRCONV(s.str()));
929
930                         // reset enum counters
931                         textclass.counters().reset("enum");
932                 } else if (layout->labeltype < LABEL_COUNTER_ENUMI) {
933                         textclass.counters().reset("enum");
934                 } else if (layout->labeltype == LABEL_COUNTER_ENUMI) {
935                         // FIXME
936                         // Yes I know this is a really, really! bad solution
937                         // (Lgb)
938                         string enumcounter("enum");
939
940                         switch (pit->enumdepth) {
941                         case 2:
942                                 enumcounter += 'i';
943                         case 1:
944                                 enumcounter += 'i';
945                         case 0:
946                                 enumcounter += 'i';
947                                 break;
948                         case 3:
949                                 enumcounter += "iv";
950                                 break;
951                         default:
952                                 // not a valid enumdepth...
953                                 break;
954                         }
955
956                         textclass.counters().step(enumcounter);
957
958                         s << textclass.counters()
959                                 .numberLabel(enumcounter, "enumeration");
960                         pit->params().labelString(STRCONV(s.str()));
961                 }
962         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
963                 textclass.counters().step("bibitem");
964                 int number = textclass.counters().value("bibitem");
965                 if (pit->bibitem()) {
966                         pit->bibitem()->setCounter(number);
967                         pit->params().labelString(layout->labelstring());
968                 }
969                 // In biblio should't be following counters but...
970         } else {
971                 string s = buf.B_(layout->labelstring());
972
973                 // the caption hack:
974                 if (layout->labeltype == LABEL_SENSITIVE) {
975                         ParagraphList::iterator end = ownerParagraphs().end();
976                         ParagraphList::iterator tmppit = pit;
977                         InsetOld * in = 0;
978                         bool isOK = false;
979                         while (tmppit != end && tmppit->inInset()
980                                // the single '=' is intended below
981                                && (in = tmppit->inInset()->owner()))
982                         {
983                                 if (in->lyxCode() == InsetOld::FLOAT_CODE ||
984                                     in->lyxCode() == InsetOld::WRAP_CODE) {
985                                         isOK = true;
986                                         break;
987                                 } else {
988                                         Paragraph const * owner = &ownerPar(buf, in);
989                                         tmppit = ownerParagraphs().begin();
990                                         for ( ; tmppit != end; ++tmppit)
991                                                 if (&*tmppit == owner)
992                                                         break;
993                                 }
994                         }
995
996                         if (isOK) {
997                                 string type;
998
999                                 if (in->lyxCode() == InsetOld::FLOAT_CODE)
1000                                         type = static_cast<InsetFloat*>(in)->params().type;
1001                                 else if (in->lyxCode() == InsetOld::WRAP_CODE)
1002                                         type = static_cast<InsetWrap*>(in)->params().type;
1003                                 else
1004                                         Assert(0);
1005
1006                                 Floating const & fl = textclass.floats().getType(type);
1007
1008                                 textclass.counters().step(fl.type());
1009
1010                                 // Doesn't work... yet.
1011                                 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
1012                         } else {
1013                                 // par->SetLayout(0);
1014                                 // s = layout->labelstring;
1015                                 s = _("Senseless: ");
1016                         }
1017                 }
1018                 pit->params().labelString(s);
1019
1020                 // reset the enumeration counter. They are always reset
1021                 // when there is any other layout between
1022                 // Just fall-through between the cases so that all
1023                 // enum counters deeper than enumdepth is also reset.
1024                 switch (pit->enumdepth) {
1025                 case 0:
1026                         textclass.counters().reset("enumi");
1027                 case 1:
1028                         textclass.counters().reset("enumii");
1029                 case 2:
1030                         textclass.counters().reset("enumiii");
1031                 case 3:
1032                         textclass.counters().reset("enumiv");
1033                 }
1034         }
1035 }
1036
1037
1038 // Updates all counters. Paragraphs with changed label string will be rebroken
1039 void LyXText::updateCounters()
1040 {
1041         // start over
1042         bv()->buffer()->params().getLyXTextClass().counters().reset();
1043
1044         ParagraphList::iterator beg = ownerParagraphs().begin();
1045         ParagraphList::iterator end = ownerParagraphs().end();
1046         for (ParagraphList::iterator pit = beg; pit != end; ++pit) {
1047                 string const oldLabel = pit->params().labelString();
1048
1049                 size_t maxdepth = 0;
1050                 if (pit != beg)
1051                         maxdepth = boost::prior(pit)->getMaxDepthAfter();
1052
1053                 if (pit->params().depth() > maxdepth)
1054                         pit->params().depth(maxdepth);
1055
1056                 // setCounter can potentially change the labelString.
1057                 setCounter(*bv()->buffer(), pit);
1058
1059                 string const & newLabel = pit->params().labelString();
1060
1061                 if (oldLabel != newLabel)
1062                         redoParagraph(pit);
1063         }
1064 }
1065
1066
1067 void LyXText::insertInset(InsetOld * inset)
1068 {
1069         if (!cursor.par()->insetAllowed(inset->lyxCode()))
1070                 return;
1071         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1072         freezeUndo();
1073         cursor.par()->insertInset(cursor.pos(), inset);
1074         // Just to rebreak and refresh correctly.
1075         // The character will not be inserted a second time
1076         insertChar(Paragraph::META_INSET);
1077         // If we enter a highly editable inset the cursor should be before
1078         // the inset. After an Undo LyX tries to call inset->edit(...)
1079         // and fails if the cursor is behind the inset and getInset
1080         // does not return the inset!
1081         if (isHighlyEditableInset(inset))
1082                 cursorLeft(true);
1083         unFreezeUndo();
1084 }
1085
1086
1087 void LyXText::cutSelection(bool doclear, bool realcut)
1088 {
1089         // Stuff what we got on the clipboard. Even if there is no selection.
1090
1091         // There is a problem with having the stuffing here in that the
1092         // larger the selection the slower LyX will get. This can be
1093         // solved by running the line below only when the selection has
1094         // finished. The solution used currently just works, to make it
1095         // faster we need to be more clever and probably also have more
1096         // calls to stuffClipboard. (Lgb)
1097         bv()->stuffClipboard(selectionAsString(*bv()->buffer(), true));
1098
1099         // This doesn't make sense, if there is no selection
1100         if (!selection.set())
1101                 return;
1102
1103         // OK, we have a selection. This is always between selection.start
1104         // and selection.end
1105
1106         // make sure that the depth behind the selection are restored, too
1107         ParagraphList::iterator endpit = boost::next(selection.end.par());
1108         ParagraphList::iterator undoendpit = endpit;
1109         ParagraphList::iterator pars_end = ownerParagraphs().end();
1110
1111         if (endpit != pars_end && endpit->getDepth()) {
1112                 while (endpit != pars_end && endpit->getDepth()) {
1113                         ++endpit;
1114                         undoendpit = endpit;
1115                 }
1116         } else if (endpit != pars_end) {
1117                 // because of parindents etc.
1118                 ++endpit;
1119         }
1120
1121         recordUndo(bv(), Undo::DELETE, selection.start.par(),
1122                    boost::prior(undoendpit));
1123
1124         endpit = selection.end.par();
1125         int endpos = selection.end.pos();
1126
1127         BufferParams const & bufparams = bv()->buffer()->params();
1128         boost::tie(endpit, endpos) = realcut ?
1129                 CutAndPaste::cutSelection(bufparams,
1130                                           ownerParagraphs(),
1131                                           selection.start.par(), endpit,
1132                                           selection.start.pos(), endpos,
1133                                           bufparams.textclass,
1134                                           doclear)
1135                 : CutAndPaste::eraseSelection(bufparams,
1136                                               ownerParagraphs(),
1137                                               selection.start.par(), endpit,
1138                                               selection.start.pos(), endpos,
1139                                               doclear);
1140         // sometimes necessary
1141         if (doclear)
1142                 selection.start.par()->stripLeadingSpaces();
1143
1144         redoParagraphs(selection.start.par(), boost::next(endpit));
1145         // cutSelection can invalidate the cursor so we need to set
1146         // it anew. (Lgb)
1147         // we prefer the end for when tracking changes
1148         cursor.pos(endpos);
1149         cursor.par(endpit);
1150
1151         // need a valid cursor. (Lgb)
1152         clearSelection();
1153
1154         setCursor(cursor.par(), cursor.pos());
1155         selection.cursor = cursor;
1156         updateCounters();
1157 }
1158
1159
1160 void LyXText::copySelection()
1161 {
1162         // stuff the selection onto the X clipboard, from an explicit copy request
1163         bv()->stuffClipboard(selectionAsString(*bv()->buffer(), true));
1164
1165         // this doesnt make sense, if there is no selection
1166         if (!selection.set())
1167                 return;
1168
1169         // ok we have a selection. This is always between selection.start
1170         // and sel_end cursor
1171
1172         // copy behind a space if there is one
1173         while (selection.start.par()->size() > selection.start.pos()
1174                && selection.start.par()->isLineSeparator(selection.start.pos())
1175                && (selection.start.par() != selection.end.par()
1176                    || selection.start.pos() < selection.end.pos()))
1177                 selection.start.pos(selection.start.pos() + 1);
1178
1179         CutAndPaste::copySelection(selection.start.par(),
1180                                    selection.end.par(),
1181                                    selection.start.pos(), selection.end.pos(),
1182                                    bv()->buffer()->params().textclass);
1183 }
1184
1185
1186 void LyXText::pasteSelection(size_t sel_index)
1187 {
1188         // this does not make sense, if there is nothing to paste
1189         if (!CutAndPaste::checkPastePossible())
1190                 return;
1191
1192         recordUndo(bv(), Undo::INSERT, cursor.par());
1193
1194         ParagraphList::iterator endpit;
1195         PitPosPair ppp;
1196
1197         ErrorList el;
1198
1199         boost::tie(ppp, endpit) =
1200                 CutAndPaste::pasteSelection(*bv()->buffer(),
1201                                             ownerParagraphs(),
1202                                             cursor.par(), cursor.pos(),
1203                                             bv()->buffer()->params().textclass,
1204                                             sel_index, el);
1205         bufferErrors(*bv()->buffer(), el);
1206         bv()->showErrorList(_("Paste"));
1207
1208         redoParagraphs(cursor.par(), endpit);
1209
1210         setCursor(cursor.par(), cursor.pos());
1211         clearSelection();
1212
1213         selection.cursor = cursor;
1214         setCursor(ppp.first, ppp.second);
1215         setSelection();
1216         updateCounters();
1217 }
1218
1219
1220 void LyXText::setSelectionRange(lyx::pos_type length)
1221 {
1222         if (!length)
1223                 return;
1224
1225         selection.cursor = cursor;
1226         while (length--)
1227                 cursorRight(bv());
1228         setSelection();
1229 }
1230
1231
1232 // simple replacing. The font of the first selected character is used
1233 void LyXText::replaceSelectionWithString(string const & str)
1234 {
1235         recordUndo(bv(), Undo::ATOMIC);
1236         freezeUndo();
1237
1238         if (!selection.set()) { // create a dummy selection
1239                 selection.end = cursor;
1240                 selection.start = cursor;
1241         }
1242
1243         // Get font setting before we cut
1244         pos_type pos = selection.end.pos();
1245         LyXFont const font = selection.start.par()
1246                 ->getFontSettings(bv()->buffer()->params(),
1247                                   selection.start.pos());
1248
1249         // Insert the new string
1250         string::const_iterator cit = str.begin();
1251         string::const_iterator end = str.end();
1252         for (; cit != end; ++cit) {
1253                 selection.end.par()->insertChar(pos, (*cit), font);
1254                 ++pos;
1255         }
1256
1257         // Cut the selection
1258         cutSelection(true, false);
1259
1260         unFreezeUndo();
1261 }
1262
1263
1264 // needed to insert the selection
1265 void LyXText::insertStringAsLines(string const & str)
1266 {
1267         ParagraphList::iterator pit = cursor.par();
1268         pos_type pos = cursor.pos();
1269         ParagraphList::iterator endpit = boost::next(cursor.par());
1270
1271         recordUndo(bv(), Undo::ATOMIC);
1272
1273         // only to be sure, should not be neccessary
1274         clearSelection();
1275
1276         bv()->buffer()->insertStringAsLines(pit, pos, current_font, str);
1277
1278         redoParagraphs(cursor.par(), endpit);
1279         setCursor(cursor.par(), cursor.pos());
1280         selection.cursor = cursor;
1281         setCursor(pit, pos);
1282         setSelection();
1283 }
1284
1285
1286 // turns double-CR to single CR, others where converted into one
1287 // blank. Then InsertStringAsLines is called
1288 void LyXText::insertStringAsParagraphs(string const & str)
1289 {
1290         string linestr(str);
1291         bool newline_inserted = false;
1292         string::size_type const siz = linestr.length();
1293
1294         for (string::size_type i = 0; i < siz; ++i) {
1295                 if (linestr[i] == '\n') {
1296                         if (newline_inserted) {
1297                                 // we know that \r will be ignored by
1298                                 // InsertStringA. Of course, it is a dirty
1299                                 // trick, but it works...
1300                                 linestr[i - 1] = '\r';
1301                                 linestr[i] = '\n';
1302                         } else {
1303                                 linestr[i] = ' ';
1304                                 newline_inserted = true;
1305                         }
1306                 } else if (IsPrintable(linestr[i])) {
1307                         newline_inserted = false;
1308                 }
1309         }
1310         insertStringAsLines(linestr);
1311 }
1312
1313
1314 bool LyXText::setCursor(ParagraphList::iterator pit,
1315                         pos_type pos,
1316                         bool setfont, bool boundary)
1317 {
1318         LyXCursor old_cursor = cursor;
1319         setCursorIntern(pit, pos, setfont, boundary);
1320         return deleteEmptyParagraphMechanism(old_cursor);
1321 }
1322
1323
1324 void LyXText::redoCursor()
1325 {
1326 #warning maybe the same for selections?
1327         setCursor(cursor, cursor.par(), cursor.pos(), cursor.boundary());
1328 }
1329
1330
1331 void LyXText::setCursor(LyXCursor & cur, ParagraphList::iterator pit,
1332                         pos_type pos, bool boundary)
1333 {
1334         Assert(pit != ownerParagraphs().end());
1335
1336         cur.par(pit);
1337         cur.pos(pos);
1338         cur.boundary(boundary);
1339         if (noRows())
1340                 return;
1341
1342         // get the cursor y position in text
1343
1344         RowList::iterator row = getRow(pit, pos);
1345         int y = row->y();
1346
1347         // y is now the beginning of the cursor row
1348         y += row->baseline();
1349         // y is now the cursor baseline
1350         cur.y(y);
1351
1352         pos_type last = lastPos(*pit, row);
1353
1354         // None of these should happen, but we're scaredy-cats
1355         if (pos > pit->size()) {
1356                 lyxerr << "dont like 1, pos: " << pos << " size: " << pit->size() << endl;
1357                 pos = 0;
1358                 cur.pos(0);
1359         } else if (pos > last + 1) {
1360                 lyxerr << "dont like 2 please report" << endl;
1361                 // This shouldn't happen.
1362                 pos = last + 1;
1363                 cur.pos(pos);
1364         } else if (pos < row->pos()) {
1365                 lyxerr << "dont like 3 please report" << endl;
1366                 pos = row->pos();
1367                 cur.pos(pos);
1368         }
1369
1370         // now get the cursors x position
1371         float x = getCursorX(pit, row, pos, last, boundary);
1372         cur.x(int(x));
1373         cur.x_fix(cur.x());
1374 }
1375
1376
1377 float LyXText::getCursorX(ParagraphList::iterator pit, RowList::iterator rit,
1378                           pos_type pos, pos_type last, bool boundary) const
1379 {
1380         pos_type cursor_vpos    = 0;
1381         double x                = rit->x();
1382         double fill_separator   = rit->fill_separator();
1383         double fill_hfill       = rit->fill_hfill();
1384         double fill_label_hfill = rit->fill_label_hfill();
1385         pos_type const rit_pos  = rit->pos();
1386
1387         if (last < rit_pos)
1388                 cursor_vpos = rit_pos;
1389         else if (pos > last && !boundary)
1390                 cursor_vpos = (pit->isRightToLeftPar(bv()->buffer()->params()))
1391                         ? rit_pos : last + 1;
1392         else if (pos > rit_pos && (pos > last || boundary))
1393                 // Place cursor after char at (logical) position pos - 1
1394                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1395                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1396         else
1397                 // Place cursor before char at (logical) position pos
1398                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1399                         ? log2vis(pos) : log2vis(pos) + 1;
1400
1401         pos_type body_pos = pit->beginningOfBody();
1402         if (body_pos > 0 &&
1403             (body_pos - 1 > last || !pit->isLineSeparator(body_pos - 1)))
1404                 body_pos = 0;
1405
1406         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1407                 pos_type pos = vis2log(vpos);
1408                 if (body_pos > 0 && pos == body_pos - 1) {
1409                         x += fill_label_hfill +
1410                                 font_metrics::width(
1411                                         pit->layout()->labelsep, getLabelFont(pit));
1412                         if (pit->isLineSeparator(body_pos - 1))
1413                                 x -= singleWidth(pit, body_pos - 1);
1414                 }
1415
1416                 if (hfillExpansion(*pit, rit, pos)) {
1417                         x += singleWidth(pit, pos);
1418                         if (pos >= body_pos)
1419                                 x += fill_hfill;
1420                         else
1421                                 x += fill_label_hfill;
1422                 } else if (pit->isSeparator(pos)) {
1423                         x += singleWidth(pit, pos);
1424                         if (pos >= body_pos)
1425                                 x += fill_separator;
1426                 } else
1427                         x += singleWidth(pit, pos);
1428         }
1429         return x;
1430 }
1431
1432
1433 void LyXText::setCursorIntern(ParagraphList::iterator pit,
1434                               pos_type pos, bool setfont, bool boundary)
1435 {
1436         setCursor(cursor, pit, pos, boundary);
1437         if (setfont)
1438                 setCurrentFont();
1439 }
1440
1441
1442 void LyXText::setCurrentFont()
1443 {
1444         pos_type pos = cursor.pos();
1445         ParagraphList::iterator pit = cursor.par();
1446
1447         if (cursor.boundary() && pos > 0)
1448                 --pos;
1449
1450         if (pos > 0) {
1451                 if (pos == pit->size())
1452                         --pos;
1453                 else // potentional bug... BUG (Lgb)
1454                         if (pit->isSeparator(pos)) {
1455                                 if (pos > cursorRow()->pos() &&
1456                                     bidi_level(pos) % 2 ==
1457                                     bidi_level(pos - 1) % 2)
1458                                         --pos;
1459                                 else if (pos + 1 < pit->size())
1460                                         ++pos;
1461                         }
1462         }
1463
1464         BufferParams const & bufparams = bv()->buffer()->params();
1465         current_font = pit->getFontSettings(bufparams, pos);
1466         real_current_font = getFont(pit, pos);
1467
1468         if (cursor.pos() == pit->size() &&
1469             isBoundary(*bv()->buffer(), *pit, cursor.pos()) &&
1470             !cursor.boundary()) {
1471                 Language const * lang =
1472                         pit->getParLanguage(bufparams);
1473                 current_font.setLanguage(lang);
1474                 current_font.setNumber(LyXFont::OFF);
1475                 real_current_font.setLanguage(lang);
1476                 real_current_font.setNumber(LyXFont::OFF);
1477         }
1478 }
1479
1480
1481 // returns the column near the specified x-coordinate of the row
1482 // x is set to the real beginning of this column
1483 pos_type LyXText::getColumnNearX(ParagraphList::iterator pit,
1484         RowList::iterator rit, int & x, bool & boundary) const
1485 {
1486         double tmpx             = rit->x();
1487         double fill_separator   = rit->fill_separator();
1488         double fill_hfill       = rit->fill_hfill();
1489         double fill_label_hfill = rit->fill_label_hfill();
1490
1491         pos_type vc = rit->pos();
1492         pos_type last = lastPos(*pit, rit);
1493         pos_type c = 0;
1494         LyXLayout_ptr const & layout = pit->layout();
1495
1496         bool left_side = false;
1497
1498         pos_type body_pos = pit->beginningOfBody();
1499         double last_tmpx = tmpx;
1500
1501         if (body_pos > 0 &&
1502             (body_pos - 1 > last ||
1503              !pit->isLineSeparator(body_pos - 1)))
1504                 body_pos = 0;
1505
1506         // check for empty row
1507         if (!pit->size()) {
1508                 x = int(tmpx);
1509                 return 0;
1510         }
1511
1512         while (vc <= last && tmpx <= x) {
1513                 c = vis2log(vc);
1514                 last_tmpx = tmpx;
1515                 if (body_pos > 0 && c == body_pos - 1) {
1516                         tmpx += fill_label_hfill +
1517                                 font_metrics::width(layout->labelsep, getLabelFont(pit));
1518                         if (pit->isLineSeparator(body_pos - 1))
1519                                 tmpx -= singleWidth(pit, body_pos - 1);
1520                 }
1521
1522                 if (hfillExpansion(*pit, rit, c)) {
1523                         tmpx += singleWidth(pit, c);
1524                         if (c >= body_pos)
1525                                 tmpx += fill_hfill;
1526                         else
1527                                 tmpx += fill_label_hfill;
1528                 } else if (pit->isSeparator(c)) {
1529                         tmpx += singleWidth(pit, c);
1530                         if (c >= body_pos)
1531                                 tmpx += fill_separator;
1532                 } else {
1533                         tmpx += singleWidth(pit, c);
1534                 }
1535                 ++vc;
1536         }
1537
1538         if ((tmpx + last_tmpx) / 2 > x) {
1539                 tmpx = last_tmpx;
1540                 left_side = true;
1541         }
1542
1543         if (vc > last + 1)  // This shouldn't happen.
1544                 vc = last + 1;
1545
1546         boundary = false;
1547         // This (rtl_support test) is not needed, but gives
1548         // some speedup if rtl_support == false
1549         bool const lastrow = lyxrc.rtl_support
1550                         && boost::next(rit) == pit->rows.end();
1551
1552         // If lastrow is false, we don't need to compute
1553         // the value of rtl.
1554         bool const rtl = (lastrow)
1555                 ? pit->isRightToLeftPar(bv()->buffer()->params())
1556                 : false;
1557         if (lastrow &&
1558                  ((rtl  &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1559                   (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1560                 c = last + 1;
1561         else if (vc == rit->pos()) {
1562                 c = vis2log(vc);
1563                 if (bidi_level(c) % 2 == 1)
1564                         ++c;
1565         } else {
1566                 c = vis2log(vc - 1);
1567                 bool const rtl = (bidi_level(c) % 2 == 1);
1568                 if (left_side == rtl) {
1569                         ++c;
1570                         boundary = isBoundary(*bv()->buffer(), *pit, c);
1571                 }
1572         }
1573
1574         if (rit->pos() <= last && c > last && pit->isNewline(last)) {
1575                 if (bidi_level(last) % 2 == 0)
1576                         tmpx -= singleWidth(pit, last);
1577                 else
1578                         tmpx += singleWidth(pit, last);
1579                 c = last;
1580         }
1581
1582         c -= rit->pos();
1583         x = int(tmpx);
1584         return c;
1585 }
1586
1587
1588 void LyXText::setCursorFromCoordinates(int x, int y)
1589 {
1590         LyXCursor old_cursor = cursor;
1591         setCursorFromCoordinates(cursor, x, y);
1592         setCurrentFont();
1593         deleteEmptyParagraphMechanism(old_cursor);
1594 }
1595
1596
1597 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1598 {
1599         // Get the row first.
1600         ParagraphList::iterator pit;
1601         RowList::iterator rit = getRowNearY(y, pit);
1602         y = rit->y();
1603
1604         bool bound = false;
1605         pos_type const column = getColumnNearX(pit, rit, x, bound);
1606         cur.par(pit);
1607         cur.pos(rit->pos() + column);
1608         cur.x(x);
1609         cur.y(y + rit->baseline());
1610
1611         cur.boundary(bound);
1612 }
1613
1614
1615 void LyXText::cursorLeft(bool internal)
1616 {
1617         if (cursor.pos() > 0) {
1618                 bool boundary = cursor.boundary();
1619                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
1620                 if (!internal && !boundary &&
1621                     isBoundary(*bv()->buffer(), *cursor.par(), cursor.pos() + 1))
1622                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
1623         } else if (cursor.par() != ownerParagraphs().begin()) {
1624                 // steps into the paragraph above
1625                 ParagraphList::iterator pit = boost::prior(cursor.par());
1626                 setCursor(pit, pit->size());
1627         }
1628 }
1629
1630
1631 void LyXText::cursorRight(bool internal)
1632 {
1633         bool const at_end = (cursor.pos() == cursor.par()->size());
1634         bool const at_newline = !at_end &&
1635                 cursor.par()->isNewline(cursor.pos());
1636
1637         if (!internal && cursor.boundary() && !at_newline)
1638                 setCursor(cursor.par(), cursor.pos(), true, false);
1639         else if (!at_end) {
1640                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
1641                 if (!internal &&
1642                     isBoundary(*bv()->buffer(), *cursor.par(), cursor.pos()))
1643                         setCursor(cursor.par(), cursor.pos(), true, true);
1644         } else if (boost::next(cursor.par()) != ownerParagraphs().end())
1645                 setCursor(boost::next(cursor.par()), 0);
1646 }
1647
1648
1649 void LyXText::cursorUp(bool selecting)
1650 {
1651 #if 1
1652         int x = cursor.x_fix();
1653         int y = cursor.y() - cursorRow()->baseline() - 1;
1654         setCursorFromCoordinates(x, y);
1655         if (!selecting) {
1656                 int topy = bv_owner->top_y();
1657                 int y1 = cursor.y() - topy;
1658                 int y2 = y1;
1659                 y -= topy;
1660                 InsetOld * inset_hit = checkInsetHit(x, y1);
1661                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1662                         inset_hit->localDispatch(
1663                                 FuncRequest(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none));
1664                 }
1665         }
1666 #else
1667         lyxerr << "cursorUp: y " << cursor.y() << " bl: " <<
1668                 cursorRow()->baseline() << endl;
1669         setCursorFromCoordinates(cursor.x_fix(),
1670                 cursor.y() - cursorRow()->baseline() - 1);
1671 #endif
1672 }
1673
1674
1675 void LyXText::cursorDown(bool selecting)
1676 {
1677 #if 1
1678         int x = cursor.x_fix();
1679         int y = cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1;
1680         setCursorFromCoordinates(x, y);
1681         if (!selecting && cursorRow() == cursorIRow()) {
1682                 int topy = bv_owner->top_y();
1683                 int y1 = cursor.y() - topy;
1684                 int y2 = y1;
1685                 y -= topy;
1686                 InsetOld * inset_hit = checkInsetHit(x, y1);
1687                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1688                         FuncRequest cmd(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none);
1689                         inset_hit->localDispatch(cmd);
1690                 }
1691         }
1692 #else
1693         setCursorFromCoordinates(cursor.x_fix(),
1694                  cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1);
1695 #endif
1696 }
1697
1698
1699 void LyXText::cursorUpParagraph()
1700 {
1701         if (cursor.pos() > 0)
1702                 setCursor(cursor.par(), 0);
1703         else if (cursor.par() != ownerParagraphs().begin())
1704                 setCursor(boost::prior(cursor.par()), 0);
1705 }
1706
1707
1708 void LyXText::cursorDownParagraph()
1709 {
1710         ParagraphList::iterator par = cursor.par();
1711         ParagraphList::iterator next_par = boost::next(par);
1712
1713         if (next_par != ownerParagraphs().end())
1714                 setCursor(next_par, 0);
1715         else
1716                 setCursor(par, par->size());
1717 }
1718
1719
1720 // fix the cursor `cur' after a characters has been deleted at `where'
1721 // position. Called by deleteEmptyParagraphMechanism
1722 void LyXText::fixCursorAfterDelete(LyXCursor & cur, LyXCursor const & where)
1723 {
1724         // if cursor is not in the paragraph where the delete occured,
1725         // do nothing
1726         if (cur.par() != where.par())
1727                 return;
1728
1729         // if cursor position is after the place where the delete occured,
1730         // update it
1731         if (cur.pos() > where.pos())
1732                 cur.pos(cur.pos()-1);
1733
1734         // check also if we don't want to set the cursor on a spot behind the
1735         // pagragraph because we erased the last character.
1736         if (cur.pos() > cur.par()->size())
1737                 cur.pos(cur.par()->size());
1738
1739         // recompute row et al. for this cursor
1740         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
1741 }
1742
1743
1744 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
1745 {
1746         // Would be wrong to delete anything if we have a selection.
1747         if (selection.set())
1748                 return false;
1749
1750         // We allow all kinds of "mumbo-jumbo" when freespacing.
1751         if (old_cursor.par()->isFreeSpacing())
1752                 return false;
1753
1754         /* Ok I'll put some comments here about what is missing.
1755            I have fixed BackSpace (and thus Delete) to not delete
1756            double-spaces automagically. I have also changed Cut,
1757            Copy and Paste to hopefully do some sensible things.
1758            There are still some small problems that can lead to
1759            double spaces stored in the document file or space at
1760            the beginning of paragraphs. This happens if you have
1761            the cursor between to spaces and then save. Or if you
1762            cut and paste and the selection have a space at the
1763            beginning and then save right after the paste. I am
1764            sure none of these are very hard to fix, but I will
1765            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
1766            that I can get some feedback. (Lgb)
1767         */
1768
1769         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
1770         // delete the LineSeparator.
1771         // MISSING
1772
1773         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
1774         // delete the LineSeparator.
1775         // MISSING
1776
1777         // If the pos around the old_cursor were spaces, delete one of them.
1778         if (old_cursor.par() != cursor.par()
1779             || old_cursor.pos() != cursor.pos()) {
1780
1781                 // Only if the cursor has really moved
1782                 if (old_cursor.pos() > 0
1783                     && old_cursor.pos() < old_cursor.par()->size()
1784                     && old_cursor.par()->isLineSeparator(old_cursor.pos())
1785                     && old_cursor.par()->isLineSeparator(old_cursor.pos() - 1)) {
1786                         bool erased = old_cursor.par()->erase(old_cursor.pos() - 1);
1787                         redoParagraph(old_cursor.par());
1788
1789                         if (!erased)
1790                                 return false;
1791 #ifdef WITH_WARNINGS
1792 #warning This will not work anymore when we have multiple views of the same buffer
1793 // In this case, we will have to correct also the cursors held by
1794 // other bufferviews. It will probably be easier to do that in a more
1795 // automated way in LyXCursor code. (JMarc 26/09/2001)
1796 #endif
1797                         // correct all cursors held by the LyXText
1798                         fixCursorAfterDelete(cursor, old_cursor);
1799                         fixCursorAfterDelete(selection.cursor, old_cursor);
1800                         fixCursorAfterDelete(selection.start, old_cursor);
1801                         fixCursorAfterDelete(selection.end, old_cursor);
1802                         return false;
1803                 }
1804         }
1805
1806         // don't delete anything if this is the ONLY paragraph!
1807         if (ownerParagraphs().size() == 1)
1808                 return false;
1809
1810         // Do not delete empty paragraphs with keepempty set.
1811         if (old_cursor.par()->allowEmpty())
1812                 return false;
1813
1814         // only do our magic if we changed paragraph
1815         if (old_cursor.par() == cursor.par())
1816                 return false;
1817
1818         // record if we have deleted a paragraph
1819         // we can't possibly have deleted a paragraph before this point
1820         bool deleted = false;
1821
1822         if (old_cursor.par()->empty() ||
1823             (old_cursor.par()->size() == 1 &&
1824              old_cursor.par()->isLineSeparator(0))) {
1825                 // ok, we will delete something
1826                 LyXCursor tmpcursor;
1827
1828                 deleted = true;
1829
1830                 bool selection_position_was_oldcursor_position = (
1831                         selection.cursor.par()  == old_cursor.par()
1832                         && selection.cursor.pos() == old_cursor.pos());
1833
1834                 tmpcursor = cursor;
1835                 cursor = old_cursor; // that undo can restore the right cursor position
1836
1837                 ParagraphList::iterator endpit = boost::next(old_cursor.par());
1838                 while (endpit != ownerParagraphs().end() && endpit->getDepth())
1839                         ++endpit;
1840
1841                 recordUndo(bv(), Undo::DELETE, old_cursor.par(), boost::prior(endpit));
1842                 cursor = tmpcursor;
1843
1844                 // delete old par
1845                 ownerParagraphs().erase(old_cursor.par());
1846                 redoParagraph();
1847
1848                 // correct cursor y
1849                 setCursorIntern(cursor.par(), cursor.pos());
1850
1851                 if (selection_position_was_oldcursor_position) {
1852                         // correct selection
1853                         selection.cursor = cursor;
1854                 }
1855         }
1856         if (!deleted) {
1857                 if (old_cursor.par()->stripLeadingSpaces()) {
1858                         redoParagraph(old_cursor.par());
1859                         // correct cursor y
1860                         setCursorIntern(cursor.par(), cursor.pos());
1861                         selection.cursor = cursor;
1862                 }
1863         }
1864         return deleted;
1865 }
1866
1867
1868 ParagraphList & LyXText::ownerParagraphs() const
1869 {
1870         return paragraphs_;
1871 }
1872
1873
1874 bool LyXText::isInInset() const
1875 {
1876         // Sub-level has non-null bv owner and non-null inset owner.
1877         return inset_owner != 0;
1878 }
1879
1880
1881 int defaultRowHeight()
1882 {
1883         LyXFont const font(LyXFont::ALL_SANE);
1884         return int(font_metrics::maxAscent(font)
1885                  + font_metrics::maxDescent(font) * 1.5);
1886 }