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