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