]> git.lyx.org Git - features.git/blob - src/Text2.cpp
Move Text::insertStringAsLines and Text::insertStringAsParagraphs from Text2.cpp...
[features.git] / src / Text2.cpp
1 /**
2  * \file text2.cpp
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 Stefan Schimanski
15  * \author Dekel Tsur
16  * \author Jürgen Vigna
17  *
18  * Full author contact details are available in file CREDITS.
19  */
20
21 #include <config.h>
22
23 #include "Text.h"
24
25 #include "Bidi.h"
26 #include "Buffer.h"
27 #include "buffer_funcs.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "Changes.h"
32 #include "Cursor.h"
33 #include "CutAndPaste.h"
34 #include "DispatchResult.h"
35 #include "ErrorList.h"
36 #include "FuncRequest.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXFunc.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "insets/InsetCollapsable.h"
50
51 #include "mathed/InsetMathHull.h"
52
53 #include "support/lassert.h"
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/textutils.h"
57
58 #include <boost/next_prior.hpp>
59
60 #include <sstream>
61
62 using namespace std;
63
64 namespace lyx {
65
66 bool Text::isMainText() const
67 {
68         return &owner_->buffer().text() == this;
69 }
70
71
72 // Note that this is supposed to return a fully realized font.
73 FontInfo Text::layoutFont(pit_type const pit) const
74 {
75         Layout const & layout = pars_[pit].layout();
76
77         if (!pars_[pit].getDepth())  {
78                 FontInfo lf = layout.resfont;
79                 // In case the default family has been customized
80                 if (layout.font.family() == INHERIT_FAMILY)
81                         lf.setFamily(owner_->buffer().params().getFont().fontInfo().family());
82                 // FIXME
83                 // It ought to be possible here just to use Inset::getLayout() and skip
84                 // the asInsetCollapsable() bit. Unfortunatley, that doesn't work right
85                 // now, because Inset::getLayout() will return a default-constructed
86                 // InsetLayout, and that e.g. sets the foreground color to red. So we
87                 // need to do some work to make that possible.
88                 InsetCollapsable const * icp = owner_->asInsetCollapsable();
89                 if (!icp)
90                         return lf;
91                 FontInfo icf = icp->getLayout().font();
92                 icf.realize(lf);
93                 return icf;
94         }
95
96         FontInfo font = layout.font;
97         // Realize with the fonts of lesser depth.
98         //font.realize(outerFont(pit, paragraphs()));
99         font.realize(owner_->buffer().params().getFont().fontInfo());
100
101         return font;
102 }
103
104
105 // Note that this is supposed to return a fully realized font.
106 FontInfo Text::labelFont(Paragraph const & par) const
107 {
108         Buffer const & buffer = owner_->buffer();
109         Layout const & layout = par.layout();
110
111         if (!par.getDepth()) {
112                 FontInfo lf = layout.reslabelfont;
113                 // In case the default family has been customized
114                 if (layout.labelfont.family() == INHERIT_FAMILY)
115                         lf.setFamily(buffer.params().getFont().fontInfo().family());
116                 return lf;
117         }
118
119         FontInfo font = layout.labelfont;
120         // Realize with the fonts of lesser depth.
121         font.realize(buffer.params().getFont().fontInfo());
122
123         return font;
124 }
125
126
127 void Text::setCharFont(pit_type pit,
128                 pos_type pos, Font const & fnt, Font const & display_font)
129 {
130         Buffer const & buffer = owner_->buffer();
131         Font font = fnt;
132         Layout const & layout = pars_[pit].layout();
133
134         // Get concrete layout font to reduce against
135         FontInfo layoutfont;
136
137         if (pos < pars_[pit].beginOfBody())
138                 layoutfont = layout.labelfont;
139         else
140                 layoutfont = layout.font;
141
142         // Realize against environment font information
143         if (pars_[pit].getDepth()) {
144                 pit_type tp = pit;
145                 while (!layoutfont.resolved() &&
146                        tp != pit_type(paragraphs().size()) &&
147                        pars_[tp].getDepth()) {
148                         tp = outerHook(tp, paragraphs());
149                         if (tp != pit_type(paragraphs().size()))
150                                 layoutfont.realize(pars_[tp].layout().font);
151                 }
152         }
153
154         // Inside inset, apply the inset's font attributes if any
155         // (charstyle!)
156         if (!isMainText())
157                 layoutfont.realize(display_font.fontInfo());
158
159         layoutfont.realize(buffer.params().getFont().fontInfo());
160
161         // Now, reduce font against full layout font
162         font.fontInfo().reduce(layoutfont);
163
164         pars_[pit].setFont(pos, font);
165 }
166
167
168 void Text::setInsetFont(BufferView const & bv, pit_type pit,
169                 pos_type pos, Font const & font, bool toggleall)
170 {
171         Inset * const inset = pars_[pit].getInset(pos);
172         LASSERT(inset && inset->noFontChange(), /**/);
173
174         CursorSlice::idx_type endidx = inset->nargs();
175         for (CursorSlice cs(*inset); cs.idx() != endidx; ++cs.idx()) {
176                 Text * text = cs.text();
177                 if (text) {
178                         // last position of the cell
179                         CursorSlice cellend = cs;
180                         cellend.pit() = cellend.lastpit();
181                         cellend.pos() = cellend.lastpos();
182                         text->setFont(bv, cs, cellend, font, toggleall);
183                 }
184         }
185 }
186
187
188 // return past-the-last paragraph influenced by a layout change on pit
189 pit_type Text::undoSpan(pit_type pit)
190 {
191         pit_type const end = paragraphs().size();
192         pit_type nextpit = pit + 1;
193         if (nextpit == end)
194                 return nextpit;
195         //because of parindents
196         if (!pars_[pit].getDepth())
197                 return boost::next(nextpit);
198         //because of depth constrains
199         for (; nextpit != end; ++pit, ++nextpit) {
200                 if (!pars_[pit].getDepth())
201                         break;
202         }
203         return nextpit;
204 }
205
206
207 void Text::setLayout(pit_type start, pit_type end,
208                      docstring const & layout)
209 {
210         LASSERT(start != end, /**/);
211
212         Buffer const & buffer = owner_->buffer();
213         BufferParams const & bp = buffer.params();
214         Layout const & lyxlayout = bp.documentClass()[layout];
215
216         for (pit_type pit = start; pit != end; ++pit) {
217                 Paragraph & par = pars_[pit];
218                 par.applyLayout(lyxlayout);
219                 if (lyxlayout.margintype == MARGIN_MANUAL)
220                         par.setLabelWidthString(par.expandLabel(lyxlayout, bp));
221         }
222 }
223
224
225 // set layout over selection and make a total rebreak of those paragraphs
226 void Text::setLayout(Cursor & cur, docstring const & layout)
227 {
228         LASSERT(this == cur.text(), /**/);
229
230         pit_type start = cur.selBegin().pit();
231         pit_type end = cur.selEnd().pit() + 1;
232         pit_type undopit = undoSpan(end - 1);
233         recUndo(cur, start, undopit - 1);
234         setLayout(start, end, layout);
235         cur.buffer()->updateLabels();
236 }
237
238
239 static bool changeDepthAllowed(Text::DEPTH_CHANGE type,
240                         Paragraph const & par, int max_depth)
241 {
242         if (par.layout().labeltype == LABEL_BIBLIO)
243                 return false;
244         int const depth = par.params().depth();
245         if (type == Text::INC_DEPTH && depth < max_depth)
246                 return true;
247         if (type == Text::DEC_DEPTH && depth > 0)
248                 return true;
249         return false;
250 }
251
252
253 bool Text::changeDepthAllowed(Cursor & cur, DEPTH_CHANGE type) const
254 {
255         LASSERT(this == cur.text(), /**/);
256         // this happens when selecting several cells in tabular (bug 2630)
257         if (cur.selBegin().idx() != cur.selEnd().idx())
258                 return false;
259
260         pit_type const beg = cur.selBegin().pit();
261         pit_type const end = cur.selEnd().pit() + 1;
262         int max_depth = (beg != 0 ? pars_[beg - 1].getMaxDepthAfter() : 0);
263
264         for (pit_type pit = beg; pit != end; ++pit) {
265                 if (lyx::changeDepthAllowed(type, pars_[pit], max_depth))
266                         return true;
267                 max_depth = pars_[pit].getMaxDepthAfter();
268         }
269         return false;
270 }
271
272
273 void Text::changeDepth(Cursor & cur, DEPTH_CHANGE type)
274 {
275         LASSERT(this == cur.text(), /**/);
276         pit_type const beg = cur.selBegin().pit();
277         pit_type const end = cur.selEnd().pit() + 1;
278         cur.recordUndoSelection();
279         int max_depth = (beg != 0 ? pars_[beg - 1].getMaxDepthAfter() : 0);
280
281         for (pit_type pit = beg; pit != end; ++pit) {
282                 Paragraph & par = pars_[pit];
283                 if (lyx::changeDepthAllowed(type, par, max_depth)) {
284                         int const depth = par.params().depth();
285                         if (type == INC_DEPTH)
286                                 par.params().depth(depth + 1);
287                         else
288                                 par.params().depth(depth - 1);
289                 }
290                 max_depth = par.getMaxDepthAfter();
291         }
292         // this handles the counter labels, and also fixes up
293         // depth values for follow-on (child) paragraphs
294         cur.buffer()->updateLabels();
295 }
296
297
298 void Text::setFont(Cursor & cur, Font const & font, bool toggleall)
299 {
300         LASSERT(this == cur.text(), /**/);
301         // Set the current_font
302         // Determine basis font
303         FontInfo layoutfont;
304         pit_type pit = cur.pit();
305         if (cur.pos() < pars_[pit].beginOfBody())
306                 layoutfont = labelFont(pars_[pit]);
307         else
308                 layoutfont = layoutFont(pit);
309
310         // Update current font
311         cur.real_current_font.update(font,
312                                         cur.buffer()->params().language,
313                                         toggleall);
314
315         // Reduce to implicit settings
316         cur.current_font = cur.real_current_font;
317         cur.current_font.fontInfo().reduce(layoutfont);
318         // And resolve it completely
319         cur.real_current_font.fontInfo().realize(layoutfont);
320
321         // if there is no selection that's all we need to do
322         if (!cur.selection())
323                 return;
324
325         // Ok, we have a selection.
326         cur.recordUndoSelection();
327
328         setFont(cur.bv(), cur.selectionBegin().top(), 
329                 cur.selectionEnd().top(), font, toggleall);
330 }
331
332
333 void Text::setFont(BufferView const & bv, CursorSlice const & begin,
334                 CursorSlice const & end, Font const & font,
335                 bool toggleall)
336 {
337         Buffer const & buffer = bv.buffer();
338
339         // Don't use forwardChar here as ditend might have
340         // pos() == lastpos() and forwardChar would miss it.
341         // Can't use forwardPos either as this descends into
342         // nested insets.
343         Language const * language = buffer.params().language;
344         for (CursorSlice dit = begin; dit != end; dit.forwardPos()) {
345                 if (dit.pos() == dit.lastpos())
346                         continue;
347                 pit_type const pit = dit.pit();
348                 pos_type const pos = dit.pos();
349                 Inset * inset = pars_[pit].getInset(pos);
350                 if (inset && inset->noFontChange()) {
351                         // We need to propagate the font change to all
352                         // text cells of the inset (bug 1973).
353                         // FIXME: This should change, see documentation
354                         // of noFontChange in Inset.h
355                         setInsetFont(bv, pit, pos, font, toggleall);
356                 }
357                 TextMetrics const & tm = bv.textMetrics(this);
358                 Font f = tm.displayFont(pit, pos);
359                 f.update(font, language, toggleall);
360                 setCharFont(pit, pos, f, tm.font_);
361         }
362 }
363
364
365 bool Text::cursorTop(Cursor & cur)
366 {
367         LASSERT(this == cur.text(), /**/);
368         return setCursor(cur, 0, 0);
369 }
370
371
372 bool Text::cursorBottom(Cursor & cur)
373 {
374         LASSERT(this == cur.text(), /**/);
375         return setCursor(cur, cur.lastpit(), boost::prior(paragraphs().end())->size());
376 }
377
378
379 void Text::toggleFree(Cursor & cur, Font const & font, bool toggleall)
380 {
381         LASSERT(this == cur.text(), /**/);
382         // If the mask is completely neutral, tell user
383         if (font.fontInfo() == ignore_font && font.language() == ignore_language) {
384                 // Could only happen with user style
385                 cur.message(_("No font change defined."));
386                 return;
387         }
388
389         // Try implicit word selection
390         // If there is a change in the language the implicit word selection
391         // is disabled.
392         CursorSlice const resetCursor = cur.top();
393         bool const implicitSelection =
394                 font.language() == ignore_language
395                 && font.fontInfo().number() == FONT_IGNORE
396                 && selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
397
398         // Set font
399         setFont(cur, font, toggleall);
400
401         // Implicit selections are cleared afterwards
402         // and cursor is set to the original position.
403         if (implicitSelection) {
404                 cur.clearSelection();
405                 cur.top() = resetCursor;
406                 cur.resetAnchor();
407         }
408 }
409
410
411 docstring Text::getStringToIndex(Cursor const & cur)
412 {
413         LASSERT(this == cur.text(), /**/);
414
415         if (cur.selection())
416                 return cur.selectionAsString(false);
417
418         // Try implicit word selection. If there is a change
419         // in the language the implicit word selection is
420         // disabled.
421         Cursor tmpcur = cur;
422         selectWord(tmpcur, PREVIOUS_WORD);
423
424         if (!tmpcur.selection())
425                 cur.message(_("Nothing to index!"));
426         else if (tmpcur.selBegin().pit() != tmpcur.selEnd().pit())
427                 cur.message(_("Cannot index more than one paragraph!"));
428         else
429                 return tmpcur.selectionAsString(false);
430         
431         return docstring();
432 }
433
434
435 void Text::setParagraphs(Cursor & cur, docstring arg, bool merge) 
436 {
437         LASSERT(cur.text(), /**/);
438         // make sure that the depth behind the selection are restored, too
439         pit_type undopit = undoSpan(cur.selEnd().pit());
440         recUndo(cur, cur.selBegin().pit(), undopit - 1);
441
442         //FIXME UNICODE
443         string const argument = to_utf8(arg);
444         depth_type priordepth = -1;
445         Layout priorlayout;
446         for (pit_type pit = cur.selBegin().pit(), end = cur.selEnd().pit();
447              pit <= end; ++pit) {
448                 Paragraph & par = pars_[pit];
449                 ParagraphParameters params = par.params();
450                 params.read(argument, merge);
451                 // Changes to label width string apply to all paragraphs
452                 // with same layout in a sequence.
453                 // Do this only once for a selected range of paragraphs
454                 // of the same layout and depth.
455                 if (par.getDepth() != priordepth || par.layout() != priorlayout)
456                         setLabelWidthStringToSequence(pit, pars_,
457                                         params.labelWidthString());
458                 par.params().apply(params, par.layout());
459                 priordepth = par.getDepth();
460                 priorlayout = par.layout();
461         }
462 }
463
464
465 //FIXME This is a little redundant now, but it's probably worth keeping,
466 //especially if we're going to go away from using serialization internally
467 //quite so much.
468 void Text::setParagraphs(Cursor & cur, ParagraphParameters const & p) 
469 {
470         LASSERT(cur.text(), /**/);
471         // make sure that the depth behind the selection are restored, too
472         pit_type undopit = undoSpan(cur.selEnd().pit());
473         recUndo(cur, cur.selBegin().pit(), undopit - 1);
474
475         depth_type priordepth = -1;
476         Layout priorlayout;
477         for (pit_type pit = cur.selBegin().pit(), end = cur.selEnd().pit();
478              pit <= end; ++pit) {
479                 Paragraph & par = pars_[pit];
480                 // Changes to label width string apply to all paragraphs
481                 // with same layout in a sequence.
482                 // Do this only once for a selected range of paragraphs
483                 // of the same layout and depth.
484                 if (par.getDepth() != priordepth || par.layout() != priorlayout)
485                         setLabelWidthStringToSequence(pit, pars_,
486                                         par.params().labelWidthString());
487                 par.params().apply(p, par.layout());
488                 priordepth = par.getDepth();
489                 priorlayout = par.layout();
490         }
491 }
492
493
494 // this really should just insert the inset and not move the cursor.
495 void Text::insertInset(Cursor & cur, Inset * inset)
496 {
497         LASSERT(this == cur.text(), /**/);
498         LASSERT(inset, /**/);
499         cur.paragraph().insertInset(cur.pos(), inset, cur.current_font,
500                 Change(cur.buffer()->params().trackChanges
501                 ? Change::INSERTED : Change::UNCHANGED));
502 }
503
504
505 bool Text::setCursor(Cursor & cur, pit_type par, pos_type pos,
506                         bool setfont, bool boundary)
507 {
508         TextMetrics const & tm = cur.bv().textMetrics(this);
509         bool const update_needed = !tm.contains(par);
510         Cursor old = cur;
511         setCursorIntern(cur, par, pos, setfont, boundary);
512         return cur.bv().checkDepm(cur, old) || update_needed;
513 }
514
515
516 void Text::setCursor(CursorSlice & cur, pit_type par, pos_type pos)
517 {
518         LASSERT(par != int(paragraphs().size()), /**/);
519         cur.pit() = par;
520         cur.pos() = pos;
521
522         // now some strict checking
523         Paragraph & para = getPar(par);
524
525         // None of these should happen, but we're scaredy-cats
526         if (pos < 0) {
527                 lyxerr << "dont like -1" << endl;
528                 LASSERT(false, /**/);
529         }
530
531         if (pos > para.size()) {
532                 lyxerr << "dont like 1, pos: " << pos
533                        << " size: " << para.size()
534                        << " par: " << par << endl;
535                 LASSERT(false, /**/);
536         }
537 }
538
539
540 void Text::setCursorIntern(Cursor & cur,
541                               pit_type par, pos_type pos, bool setfont, bool boundary)
542 {
543         LASSERT(this == cur.text(), /**/);
544         cur.boundary(boundary);
545         setCursor(cur.top(), par, pos);
546         if (setfont)
547                 cur.setCurrentFont();
548 }
549
550
551 bool Text::checkAndActivateInset(Cursor & cur, bool front)
552 {
553         if (cur.selection())
554                 return false;
555         if (front && cur.pos() == cur.lastpos())
556                 return false;
557         if (!front && cur.pos() == 0)
558                 return false;
559         Inset * inset = front ? cur.nextInset() : cur.prevInset();
560         if (!inset || !inset->editable())
561                 return false;
562         /*
563          * Apparently, when entering an inset we are expected to be positioned
564          * *before* it in the containing paragraph, regardless of the direction
565          * from which we are entering. Otherwise, cursor placement goes awry,
566          * and when we exit from the beginning, we'll be placed *after* the
567          * inset.
568          */
569         if (!front)
570                 --cur.pos();
571         inset->edit(cur, front);
572         return true;
573 }
574
575
576 bool Text::checkAndActivateInsetVisual(Cursor & cur, bool movingForward, bool movingLeft)
577 {
578         if (cur.selection())
579                 return false;
580         if (cur.pos() == -1)
581                 return false;
582         if (cur.pos() == cur.lastpos())
583                 return false;
584         Paragraph & par = cur.paragraph();
585         Inset * inset = par.isInset(cur.pos()) ? par.getInset(cur.pos()) : 0;
586         if (!inset || !inset->editable())
587                 return false;
588         inset->edit(cur, movingForward, 
589                 movingLeft ? Inset::ENTRY_DIRECTION_RIGHT : Inset::ENTRY_DIRECTION_LEFT);
590         return true;
591 }
592
593
594 bool Text::cursorBackward(Cursor & cur)
595 {
596         // Tell BufferView to test for FitCursor in any case!
597         cur.updateFlags(Update::FitCursor);
598
599         // not at paragraph start?
600         if (cur.pos() > 0) {
601                 // if on right side of boundary (i.e. not at paragraph end, but line end)
602                 // -> skip it, i.e. set boundary to true, i.e. go only logically left
603                 // there are some exceptions to ignore this: lineseps, newlines, spaces
604 #if 0
605                 // some effectless debug code to see the values in the debugger
606                 bool bound = cur.boundary();
607                 int rowpos = cur.textRow().pos();
608                 int pos = cur.pos();
609                 bool sep = cur.paragraph().isSeparator(cur.pos() - 1);
610                 bool newline = cur.paragraph().isNewline(cur.pos() - 1);
611                 bool linesep = cur.paragraph().isLineSeparator(cur.pos() - 1);
612 #endif
613                 if (!cur.boundary() &&
614                                 cur.textRow().pos() == cur.pos() &&
615                                 !cur.paragraph().isLineSeparator(cur.pos() - 1) &&
616                                 !cur.paragraph().isNewline(cur.pos() - 1) &&
617                                 !cur.paragraph().isSeparator(cur.pos() - 1)) {
618                         return setCursor(cur, cur.pit(), cur.pos(), true, true);
619                 }
620                 
621                 // go left and try to enter inset
622                 if (checkAndActivateInset(cur, false))
623                         return false;
624                 
625                 // normal character left
626                 return setCursor(cur, cur.pit(), cur.pos() - 1, true, false);
627         }
628
629         // move to the previous paragraph or do nothing
630         if (cur.pit() > 0)
631                 return setCursor(cur, cur.pit() - 1, getPar(cur.pit() - 1).size(), true, false);
632         return false;
633 }
634
635
636 bool Text::cursorVisLeft(Cursor & cur, bool skip_inset)
637 {
638         Cursor temp_cur = cur;
639         temp_cur.posVisLeft(skip_inset);
640         if (temp_cur.depth() > cur.depth()) {
641                 cur = temp_cur;
642                 return false;
643         }
644         return setCursor(cur, temp_cur.pit(), temp_cur.pos(), 
645                 true, temp_cur.boundary());
646 }
647
648
649 bool Text::cursorVisRight(Cursor & cur, bool skip_inset)
650 {
651         Cursor temp_cur = cur;
652         temp_cur.posVisRight(skip_inset);
653         if (temp_cur.depth() > cur.depth()) {
654                 cur = temp_cur;
655                 return false;
656         }
657         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
658                 true, temp_cur.boundary());
659 }
660
661
662 bool Text::cursorForward(Cursor & cur)
663 {
664         // Tell BufferView to test for FitCursor in any case!
665         cur.updateFlags(Update::FitCursor);
666
667         // not at paragraph end?
668         if (cur.pos() != cur.lastpos()) {
669                 // in front of editable inset, i.e. jump into it?
670                 if (checkAndActivateInset(cur, true))
671                         return false;
672
673                 TextMetrics const & tm = cur.bv().textMetrics(this);
674                 // if left of boundary -> just jump to right side
675                 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
676                 if (cur.boundary() && !tm.isRTLBoundary(cur.pit(), cur.pos()))
677                         return setCursor(cur, cur.pit(), cur.pos(), true, false);
678
679                 // next position is left of boundary, 
680                 // but go to next line for special cases like space, newline, linesep
681 #if 0
682                 // some effectless debug code to see the values in the debugger
683                 int endpos = cur.textRow().endpos();
684                 int lastpos = cur.lastpos();
685                 int pos = cur.pos();
686                 bool linesep = cur.paragraph().isLineSeparator(cur.pos());
687                 bool newline = cur.paragraph().isNewline(cur.pos());
688                 bool sep = cur.paragraph().isSeparator(cur.pos());
689                 if (cur.pos() != cur.lastpos()) {
690                         bool linesep2 = cur.paragraph().isLineSeparator(cur.pos()+1);
691                         bool newline2 = cur.paragraph().isNewline(cur.pos()+1);
692                         bool sep2 = cur.paragraph().isSeparator(cur.pos()+1);
693                 }
694 #endif
695                 if (cur.textRow().endpos() == cur.pos() + 1 &&
696                     cur.textRow().endpos() != cur.lastpos() &&
697                                 !cur.paragraph().isNewline(cur.pos()) &&
698                                 !cur.paragraph().isLineSeparator(cur.pos()) &&
699                                 !cur.paragraph().isSeparator(cur.pos())) {
700                         return setCursor(cur, cur.pit(), cur.pos() + 1, true, true);
701                 }
702                 
703                 // in front of RTL boundary? Stay on this side of the boundary because:
704                 //   ab|cDDEEFFghi -> abc|DDEEFFghi
705                 if (tm.isRTLBoundary(cur.pit(), cur.pos() + 1))
706                         return setCursor(cur, cur.pit(), cur.pos() + 1, true, true);
707                 
708                 // move right
709                 return setCursor(cur, cur.pit(), cur.pos() + 1, true, false);
710         }
711
712         // move to next paragraph
713         if (cur.pit() != cur.lastpit())
714                 return setCursor(cur, cur.pit() + 1, 0, true, false);
715         return false;
716 }
717
718
719 bool Text::cursorUpParagraph(Cursor & cur)
720 {
721         bool updated = false;
722         if (cur.pos() > 0)
723                 updated = setCursor(cur, cur.pit(), 0);
724         else if (cur.pit() != 0)
725                 updated = setCursor(cur, cur.pit() - 1, 0);
726         return updated;
727 }
728
729
730 bool Text::cursorDownParagraph(Cursor & cur)
731 {
732         bool updated = false;
733         if (cur.pit() != cur.lastpit())
734                 updated = setCursor(cur, cur.pit() + 1, 0);
735         else
736                 updated = setCursor(cur, cur.pit(), cur.lastpos());
737         return updated;
738 }
739
740
741 // fix the cursor `cur' after a characters has been deleted at `where'
742 // position. Called by deleteEmptyParagraphMechanism
743 void Text::fixCursorAfterDelete(CursorSlice & cur, CursorSlice const & where)
744 {
745         // Do nothing if cursor is not in the paragraph where the
746         // deletion occured,
747         if (cur.pit() != where.pit())
748                 return;
749
750         // If cursor position is after the deletion place update it
751         if (cur.pos() > where.pos())
752                 --cur.pos();
753
754         // Check also if we don't want to set the cursor on a spot behind the
755         // pagragraph because we erased the last character.
756         if (cur.pos() > cur.lastpos())
757                 cur.pos() = cur.lastpos();
758 }
759
760
761 bool Text::deleteEmptyParagraphMechanism(Cursor & cur,
762                 Cursor & old, bool & need_anchor_change)
763 {
764         //LYXERR(Debug::DEBUG, "DEPM: cur:\n" << cur << "old:\n" << old);
765
766         Paragraph & oldpar = old.paragraph();
767
768         // We allow all kinds of "mumbo-jumbo" when freespacing.
769         if (oldpar.isFreeSpacing())
770                 return false;
771
772         /* Ok I'll put some comments here about what is missing.
773            There are still some small problems that can lead to
774            double spaces stored in the document file or space at
775            the beginning of paragraphs(). This happens if you have
776            the cursor between to spaces and then save. Or if you
777            cut and paste and the selection have a space at the
778            beginning and then save right after the paste. (Lgb)
779         */
780
781         // If old.pos() == 0 and old.pos()(1) == LineSeparator
782         // delete the LineSeparator.
783         // MISSING
784
785         // If old.pos() == 1 and old.pos()(0) == LineSeparator
786         // delete the LineSeparator.
787         // MISSING
788
789         // Find a common inset and the corresponding depth.
790         size_t depth = 0;
791         for (; depth < cur.depth(); ++depth)
792                 if (&old.inset() == &cur[depth].inset())
793                         break;
794
795         // Whether a common inset is found and whether the cursor is still in 
796         // the same paragraph (possibly nested).
797         bool const same_par = depth < cur.depth() && old.pit() == cur[depth].pit();
798         bool const same_par_pos = depth == cur.depth() - 1 && same_par 
799                 && old.pos() == cur[depth].pos();
800         
801         // If the chars around the old cursor were spaces, delete one of them.
802         if (!same_par_pos) {
803                 // Only if the cursor has really moved.
804                 if (old.pos() > 0
805                     && old.pos() < oldpar.size()
806                     && oldpar.isLineSeparator(old.pos())
807                     && oldpar.isLineSeparator(old.pos() - 1)
808                     && !oldpar.isDeleted(old.pos() - 1)
809                     && !oldpar.isDeleted(old.pos())) {
810                         oldpar.eraseChar(old.pos() - 1, cur.buffer()->params().trackChanges);
811 // FIXME: This will not work anymore when we have multiple views of the same buffer
812 // In this case, we will have to correct also the cursors held by
813 // other bufferviews. It will probably be easier to do that in a more
814 // automated way in CursorSlice code. (JMarc 26/09/2001)
815                         // correct all cursor parts
816                         if (same_par) {
817                                 fixCursorAfterDelete(cur[depth], old.top());
818                                 need_anchor_change = true;
819                         }
820                         return true;
821                 }
822         }
823
824         // only do our magic if we changed paragraph
825         if (same_par)
826                 return false;
827
828         // don't delete anything if this is the ONLY paragraph!
829         if (old.lastpit() == 0)
830                 return false;
831
832         // Do not delete empty paragraphs with keepempty set.
833         if (oldpar.allowEmpty())
834                 return false;
835
836         if (oldpar.empty() || (oldpar.size() == 1 && oldpar.isLineSeparator(0))) {
837                 // Delete old par.
838                 old.recordUndo(ATOMIC_UNDO,
839                            max(old.pit() - 1, pit_type(0)),
840                            min(old.pit() + 1, old.lastpit()));
841                 ParagraphList & plist = old.text()->paragraphs();
842                 bool const soa = oldpar.params().startOfAppendix();
843                 plist.erase(boost::next(plist.begin(), old.pit()));
844                 // do not lose start of appendix marker (bug 4212)
845                 if (soa && old.pit() < pit_type(plist.size()))
846                         plist[old.pit()].params().startOfAppendix(true);
847
848                 // see #warning (FIXME?) above 
849                 if (cur.depth() >= old.depth()) {
850                         CursorSlice & curslice = cur[old.depth() - 1];
851                         if (&curslice.inset() == &old.inset()
852                             && curslice.pit() > old.pit()) {
853                                 --curslice.pit();
854                                 // since a paragraph has been deleted, all the
855                                 // insets after `old' have been copied and
856                                 // their address has changed. Therefore we
857                                 // need to `regenerate' cur. (JMarc)
858                                 cur.updateInsets(&(cur.bottom().inset()));
859                                 need_anchor_change = true;
860                         }
861                 }
862                 return true;
863         }
864
865         if (oldpar.stripLeadingSpaces(cur.buffer()->params().trackChanges)) {
866                 need_anchor_change = true;
867                 // We return true here because the Paragraph contents changed and
868                 // we need a redraw before further action is processed.
869                 return true;
870         }
871
872         return false;
873 }
874
875
876 void Text::deleteEmptyParagraphMechanism(pit_type first, pit_type last, bool trackChanges)
877 {
878         LASSERT(first >= 0 && first <= last && last < (int) pars_.size(), /**/);
879
880         for (pit_type pit = first; pit <= last; ++pit) {
881                 Paragraph & par = pars_[pit];
882
883                 // We allow all kinds of "mumbo-jumbo" when freespacing.
884                 if (par.isFreeSpacing())
885                         continue;
886
887                 for (pos_type pos = 1; pos < par.size(); ++pos) {
888                         if (par.isLineSeparator(pos) && par.isLineSeparator(pos - 1)
889                             && !par.isDeleted(pos - 1)) {
890                                 if (par.eraseChar(pos - 1, trackChanges)) {
891                                         --pos;
892                                 }
893                         }
894                 }
895
896                 // don't delete anything if this is the only remaining paragraph within the given range
897                 // note: Text::acceptOrRejectChanges() sets the cursor to 'first' after calling DEPM
898                 if (first == last)
899                         continue;
900
901                 // don't delete empty paragraphs with keepempty set
902                 if (par.allowEmpty())
903                         continue;
904
905                 if (par.empty() || (par.size() == 1 && par.isLineSeparator(0))) {
906                         pars_.erase(boost::next(pars_.begin(), pit));
907                         --pit;
908                         --last;
909                         continue;
910                 }
911
912                 par.stripLeadingSpaces(trackChanges);
913         }
914 }
915
916
917 void Text::recUndo(Cursor & cur, pit_type first, pit_type last) const
918 {
919         cur.recordUndo(ATOMIC_UNDO, first, last);
920 }
921
922
923 void Text::recUndo(Cursor & cur, pit_type par) const
924 {
925         cur.recordUndo(ATOMIC_UNDO, par, par);
926 }
927
928 } // namespace lyx