]> git.lyx.org Git - features.git/blob - src/Text.cpp
Move contents of paragraph_funcs.* to Text.h and Text.cpp.
[features.git] / src / Text.cpp
1 /**
2  * \file src/Text.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 Dov Feldstern
9  * \author Jean-Marc Lasgouttes
10  * \author John Levon
11  * \author André Pönitz
12  * \author Stefan Schimanski
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Text.h"
22
23 #include "Author.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "CompletionList.h"
30 #include "Cursor.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "Encoding.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "factory.h"
37 #include "InsetList.h"
38 #include "Language.h"
39 #include "Layout.h"
40 #include "Length.h"
41 #include "Lexer.h"
42 #include "lyxfind.h"
43 #include "LyXRC.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
49 #include "VSpace.h"
50 #include "WordLangTuple.h"
51 #include "WordList.h"
52
53 #include "insets/InsetText.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetCaption.h"
56 #include "insets/InsetLine.h"
57 #include "insets/InsetNewline.h"
58 #include "insets/InsetNewpage.h"
59 #include "insets/InsetOptArg.h"
60 #include "insets/InsetSpace.h"
61 #include "insets/InsetSpecialChar.h"
62 #include "insets/InsetTabular.h"
63
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
70
71 #include <boost/next_prior.hpp>
72
73 #include <sstream>
74
75 using namespace std;
76 using namespace lyx::support;
77
78 namespace lyx {
79
80 using cap::cutSelection;
81 using cap::pasteParagraphList;
82
83 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
84         Paragraph & toPar, pos_type toPos, BufferParams const & params)
85 {
86         // Note: moveItem() does not honour change tracking!
87         // Therefore, it should only be used for breaking and merging paragraphs
88
89         // We need a copy here because the character at fromPos is going to be erased.
90         Font const tmpFont = fromPar.getFontSettings(params, fromPos);
91         Change const tmpChange = fromPar.lookupChange(fromPos);
92
93         if (Inset * tmpInset = fromPar.getInset(fromPos)) {
94                 fromPar.releaseInset(fromPos);
95                 // The inset is not in fromPar any more.
96                 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
97                         delete tmpInset;
98                         return false;
99                 }
100                 return true;
101         }
102
103         char_type const tmpChar = fromPar.getChar(fromPos);
104         fromPar.eraseChar(fromPos, false);
105         toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
106         return true;
107 }
108
109
110 void breakParagraphConservative(BufferParams const & bparams,
111         ParagraphList & pars, pit_type par_offset, pos_type pos)
112 {
113         // create a new paragraph
114         Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
115                                        Paragraph());
116         Paragraph & par = pars[par_offset];
117
118         tmp.setInsetOwner(&par.inInset());
119         tmp.makeSameLayout(par);
120
121         LASSERT(pos <= par.size(), /**/);
122
123         if (pos < par.size()) {
124                 // move everything behind the break position to the new paragraph
125                 pos_type pos_end = par.size() - 1;
126
127                 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
128                         if (moveItem(par, pos, tmp, j, bparams)) {
129                                 ++j;
130                         }
131                 }
132                 // Move over the end-of-par change information
133                 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
134                 par.setChange(par.size(), Change(bparams.trackChanges ?
135                                            Change::INSERTED : Change::UNCHANGED));
136         }
137 }
138
139
140 void mergeParagraph(BufferParams const & bparams,
141         ParagraphList & pars, pit_type par_offset)
142 {
143         Paragraph & next = pars[par_offset + 1];
144         Paragraph & par = pars[par_offset];
145
146         pos_type pos_end = next.size() - 1;
147         pos_type pos_insert = par.size();
148
149         // the imaginary end-of-paragraph character (at par.size()) has to be
150         // marked as unmodified. Otherwise, its change is adopted by the first
151         // character of the next paragraph.
152         if (par.isChanged(par.size())) {
153                 LYXERR(Debug::CHANGES,
154                    "merging par with inserted/deleted end-of-par character");
155                 par.setChange(par.size(), Change(Change::UNCHANGED));
156         }
157
158         Change change = next.lookupChange(next.size());
159
160         // move the content of the second paragraph to the end of the first one
161         for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
162                 if (moveItem(next, 0, par, j, bparams)) {
163                         ++j;
164                 }
165         }
166
167         // move the change of the end-of-paragraph character
168         par.setChange(par.size(), change);
169
170         pars.erase(boost::next(pars.begin(), par_offset + 1));
171 }
172
173
174 pit_type depthHook(pit_type pit, ParagraphList const & pars, depth_type depth)
175 {
176         pit_type newpit = pit;
177
178         if (newpit != 0)
179                 --newpit;
180
181         while (newpit != 0 && pars[newpit].getDepth() > depth)
182                 --newpit;
183
184         if (pars[newpit].getDepth() > depth)
185                 return pit;
186
187         return newpit;
188 }
189
190
191 pit_type outerHook(pit_type par_offset, ParagraphList const & pars)
192 {
193         Paragraph const & par = pars[par_offset];
194
195         if (par.getDepth() == 0)
196                 return pars.size();
197         return depthHook(par_offset, pars, depth_type(par.getDepth() - 1));
198 }
199
200
201 bool isFirstInSequence(pit_type par_offset, ParagraphList const & pars)
202 {
203         Paragraph const & par = pars[par_offset];
204
205         pit_type dhook_offset = depthHook(par_offset, pars, par.getDepth());
206
207         if (dhook_offset == par_offset)
208                 return true;
209
210         Paragraph const & dhook = pars[dhook_offset];
211
212         return dhook.layout() != par.layout()
213                 || dhook.getDepth() != par.getDepth();
214 }
215
216
217 void setLabelWidthStringToSequence(pit_type const par_offset,
218         ParagraphList & pars, docstring const & s)
219 {
220         pit_type offset = par_offset;
221         // Find first of same layout in sequence
222         while (!isFirstInSequence(offset, pars)) {
223                 offset = depthHook(offset, pars, pars[offset].getDepth());
224         }
225
226         // now apply label width string to every par
227         // in sequence
228         pit_type const end = pars.size();
229         depth_type const depth = pars[offset].getDepth();
230         Layout const & layout = pars[offset].layout();
231         for (pit_type pit = offset; pit != end; ++pit) {
232                 while (pars[pit].getDepth() > depth)
233                         ++pit;
234                 if (pars[pit].getDepth() < depth)
235                         return;
236                 if (pars[pit].layout() != layout)
237                         return;
238                 pars[pit].setLabelWidthString(s);
239         }
240 }
241
242
243 int getEndLabel(pit_type p, ParagraphList const & pars)
244 {
245         pit_type pit = p;
246         depth_type par_depth = pars[p].getDepth();
247         while (pit != pit_type(pars.size())) {
248                 Layout const & layout = pars[pit].layout();
249                 int const endlabeltype = layout.endlabeltype;
250
251                 if (endlabeltype != END_LABEL_NO_LABEL) {
252                         if (p + 1 == pit_type(pars.size()))
253                                 return endlabeltype;
254
255                         depth_type const next_depth =
256                                 pars[p + 1].getDepth();
257                         if (par_depth > next_depth ||
258                             (par_depth == next_depth && layout != pars[p + 1].layout()))
259                                 return endlabeltype;
260                         break;
261                 }
262                 if (par_depth == 0)
263                         break;
264                 pit = outerHook(pit, pars);
265                 if (pit != pit_type(pars.size()))
266                         par_depth = pars[pit].getDepth();
267         }
268         return END_LABEL_NO_LABEL;
269 }
270
271
272 Font const outerFont(pit_type par_offset, ParagraphList const & pars)
273 {
274         depth_type par_depth = pars[par_offset].getDepth();
275         FontInfo tmpfont = inherit_font;
276
277         // Resolve against environment font information
278         while (par_offset != pit_type(pars.size())
279                && par_depth
280                && !tmpfont.resolved()) {
281                 par_offset = outerHook(par_offset, pars);
282                 if (par_offset != pit_type(pars.size())) {
283                         tmpfont.realize(pars[par_offset].layout().font);
284                         par_depth = pars[par_offset].getDepth();
285                 }
286         }
287
288         return Font(tmpfont);
289 }
290
291
292 bool isFullyDeleted(ParagraphList const & pars)
293 {
294         pit_type const pars_size = static_cast<pit_type>(pars.size());
295
296         // check all paragraphs
297         for (pit_type pit = 0; pit < pars_size; ++pit) {
298                 if (!pars[pit].empty())   // prevent assertion failure
299                         if (!pars[pit].isDeleted(0, pars[pit].size()))
300                                 return false;
301         }
302         return true;
303 }
304
305
306 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
307 {
308         pit_type pars_size = static_cast<pit_type>(pars.size());
309
310         // first, accept changes within each individual paragraph
311         // (do not consider end-of-par)
312         for (pit_type pit = 0; pit < pars_size; ++pit) {
313                 if (!pars[pit].empty())   // prevent assertion failure
314                         pars[pit].acceptChanges(0, pars[pit].size());
315         }
316
317         // next, accept imaginary end-of-par characters
318         for (pit_type pit = 0; pit < pars_size; ++pit) {
319                 pos_type pos = pars[pit].size();
320
321                 if (pars[pit].isInserted(pos)) {
322                         pars[pit].setChange(pos, Change(Change::UNCHANGED));
323                 } else if (pars[pit].isDeleted(pos)) {
324                         if (pit == pars_size - 1) {
325                                 // we cannot remove a par break at the end of the last
326                                 // paragraph; instead, we mark it unchanged
327                                 pars[pit].setChange(pos, Change(Change::UNCHANGED));
328                         } else {
329                                 mergeParagraph(bparams, pars, pit);
330                                 --pit;
331                                 --pars_size;
332                         }
333                 }
334         }
335 }
336
337 InsetText const & Text::inset() const
338 {
339         return *owner_;
340 }
341
342
343 void Text::readParToken(Paragraph & par, Lexer & lex,
344         string const & token, Font & font, Change & change, ErrorList & errorList)
345 {
346         Buffer const & buf = owner_->buffer();
347         BufferParams const & bp = buf.params();
348
349         if (token[0] != '\\') {
350                 docstring dstr = lex.getDocString();
351                 par.appendString(dstr, font, change);
352
353         } else if (token == "\\begin_layout") {
354                 lex.eatLine();
355                 docstring layoutname = lex.getDocString();
356
357                 font = Font(inherit_font, bp.language);
358                 change = Change(Change::UNCHANGED);
359
360                 DocumentClass const & tclass = bp.documentClass();
361
362                 if (layoutname.empty())
363                         layoutname = tclass.defaultLayoutName();
364
365                 if (owner_->forcePlainLayout()) {
366                         // in this case only the empty layout is allowed
367                         layoutname = tclass.plainLayoutName();
368                 } else if (par.usePlainLayout()) {
369                         // in this case, default layout maps to empty layout 
370                         if (layoutname == tclass.defaultLayoutName())
371                                 layoutname = tclass.plainLayoutName();
372                 } else { 
373                         // otherwise, the empty layout maps to the default
374                         if (layoutname == tclass.plainLayoutName())
375                                 layoutname = tclass.defaultLayoutName();
376                 }
377
378                 // When we apply an unknown layout to a document, we add this layout to the textclass
379                 // of this document. For example, when you apply class article to a beamer document,
380                 // all unknown layouts such as frame will be added to document class article so that
381                 // these layouts can keep their original names.
382                 tclass.addLayoutIfNeeded(layoutname);
383
384                 par.setLayout(bp.documentClass()[layoutname]);
385
386                 // Test whether the layout is obsolete.
387                 Layout const & layout = par.layout();
388                 if (!layout.obsoleted_by().empty())
389                         par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
390
391                 par.params().read(lex);
392
393         } else if (token == "\\end_layout") {
394                 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
395                        << "Missing \\begin_layout ?");
396         } else if (token == "\\end_inset") {
397                 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
398                        << "Missing \\begin_inset ?");
399         } else if (token == "\\begin_inset") {
400                 Inset * inset = readInset(lex, buf);
401                 if (inset)
402                         par.insertInset(par.size(), inset, font, change);
403                 else {
404                         lex.eatLine();
405                         docstring line = lex.getDocString();
406                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
407                                             par.id(), 0, par.size()));
408                 }
409         } else if (token == "\\family") {
410                 lex.next();
411                 setLyXFamily(lex.getString(), font.fontInfo());
412         } else if (token == "\\series") {
413                 lex.next();
414                 setLyXSeries(lex.getString(), font.fontInfo());
415         } else if (token == "\\shape") {
416                 lex.next();
417                 setLyXShape(lex.getString(), font.fontInfo());
418         } else if (token == "\\size") {
419                 lex.next();
420                 setLyXSize(lex.getString(), font.fontInfo());
421         } else if (token == "\\lang") {
422                 lex.next();
423                 string const tok = lex.getString();
424                 Language const * lang = languages.getLanguage(tok);
425                 if (lang) {
426                         font.setLanguage(lang);
427                 } else {
428                         font.setLanguage(bp.language);
429                         lex.printError("Unknown language `$$Token'");
430                 }
431         } else if (token == "\\numeric") {
432                 lex.next();
433                 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
434         } else if (token == "\\emph") {
435                 lex.next();
436                 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
437         } else if (token == "\\bar") {
438                 lex.next();
439                 string const tok = lex.getString();
440
441                 if (tok == "under")
442                         font.fontInfo().setUnderbar(FONT_ON);
443                 else if (tok == "no")
444                         font.fontInfo().setUnderbar(FONT_OFF);
445                 else if (tok == "default")
446                         font.fontInfo().setUnderbar(FONT_INHERIT);
447                 else
448                         lex.printError("Unknown bar font flag "
449                                        "`$$Token'");
450         } else if (token == "\\strikeout") {
451                 lex.next();
452                 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
453         } else if (token == "\\uuline") {
454                 lex.next();
455                 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
456         } else if (token == "\\uwave") {
457                 lex.next();
458                 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
459         } else if (token == "\\noun") {
460                 lex.next();
461                 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
462         } else if (token == "\\color") {
463                 lex.next();
464                 setLyXColor(lex.getString(), font.fontInfo());
465         } else if (token == "\\SpecialChar") {
466                         auto_ptr<Inset> inset;
467                         inset.reset(new InsetSpecialChar);
468                         inset->read(lex);
469                         par.insertInset(par.size(), inset.release(),
470                                         font, change);
471         } else if (token == "\\backslash") {
472                 par.appendChar('\\', font, change);
473         } else if (token == "\\LyXTable") {
474                 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
475                 inset->read(lex);
476                 par.insertInset(par.size(), inset.release(), font, change);
477         } else if (token == "\\lyxline") {
478                 par.insertInset(par.size(), new InsetLine, font, change);
479         } else if (token == "\\change_unchanged") {
480                 change = Change(Change::UNCHANGED);
481         } else if (token == "\\change_inserted" || token == "\\change_deleted") {
482                 lex.eatLine();
483                 istringstream is(lex.getString());
484                 unsigned int aid;
485                 time_t ct;
486                 is >> aid >> ct;
487                 map<unsigned int, int> const & am = bp.author_map;
488                 if (am.find(aid) == am.end()) {
489                         errorList.push_back(ErrorItem(_("Change tracking error"),
490                                             bformat(_("Unknown author index for change: %1$d\n"), aid),
491                                             par.id(), 0, par.size()));
492                         change = Change(Change::UNCHANGED);
493                 } else {
494                         if (token == "\\change_inserted")
495                                 change = Change(Change::INSERTED, am.find(aid)->second, ct);
496                         else
497                                 change = Change(Change::DELETED, am.find(aid)->second, ct);
498                 }
499         } else {
500                 lex.eatLine();
501                 errorList.push_back(ErrorItem(_("Unknown token"),
502                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
503                         lex.getDocString()),
504                         par.id(), 0, par.size()));
505         }
506 }
507
508
509 void Text::readParagraph(Paragraph & par, Lexer & lex,
510         ErrorList & errorList)
511 {
512         lex.nextToken();
513         string token = lex.getString();
514         Font font;
515         Change change(Change::UNCHANGED);
516
517         while (lex.isOK()) {
518                 readParToken(par, lex, token, font, change, errorList);
519
520                 lex.nextToken();
521                 token = lex.getString();
522
523                 if (token.empty())
524                         continue;
525
526                 if (token == "\\end_layout") {
527                         //Ok, paragraph finished
528                         break;
529                 }
530
531                 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
532                 if (token == "\\begin_layout" || token == "\\end_document"
533                     || token == "\\end_inset" || token == "\\begin_deeper"
534                     || token == "\\end_deeper") {
535                         lex.pushToken(token);
536                         lyxerr << "Paragraph ended in line "
537                                << lex.lineNumber() << "\n"
538                                << "Missing \\end_layout.\n";
539                         break;
540                 }
541         }
542         // Final change goes to paragraph break:
543         par.setChange(par.size(), change);
544
545         // Initialize begin_of_body_ on load; redoParagraph maintains
546         par.setBeginOfBody();
547 }
548
549
550 class TextCompletionList : public CompletionList
551 {
552 public:
553         ///
554         TextCompletionList(Cursor const & cur)
555                 : buffer_(cur.buffer()), pos_(0)
556         {}
557         ///
558         virtual ~TextCompletionList() {}
559         
560         ///
561         virtual bool sorted() const { return true; }
562         ///
563         virtual size_t size() const
564         {
565                 return theWordList().size();
566         }
567         ///
568         virtual docstring const & data(size_t idx) const
569         {
570                 return theWordList().word(idx);
571         }
572         
573 private:
574         ///
575         Buffer const * buffer_;
576         ///
577         size_t pos_;
578 };
579
580
581 bool Text::empty() const
582 {
583         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
584                 // FIXME: Should we consider the labeled type as empty too? 
585                 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
586 }
587
588
589 double Text::spacing(Paragraph const & par) const
590 {
591         if (par.params().spacing().isDefault())
592                 return owner_->buffer().params().spacing().getValue();
593         return par.params().spacing().getValue();
594 }
595
596
597 /**
598  * This breaks a paragraph at the specified position.
599  * The new paragraph will:
600  * - Decrease depth by one (or change layout to default layout) when
601  *    keep_layout == false  
602  * - keep current depth and layout when keep_layout == true
603  */
604 static void breakParagraph(BufferParams const & bparams,
605                     ParagraphList & pars, pit_type par_offset, pos_type pos, 
606                     bool keep_layout)
607 {
608         // create a new paragraph, and insert into the list
609         ParagraphList::iterator tmp =
610                 pars.insert(boost::next(pars.begin(), par_offset + 1),
611                             Paragraph());
612
613         Paragraph & par = pars[par_offset];
614
615         // remember to set the inset_owner
616         tmp->setInsetOwner(&par.inInset());
617         // without doing that we get a crash when typing <Return> at the
618         // end of a paragraph
619         tmp->setPlainOrDefaultLayout(bparams.documentClass());
620
621         // layout stays the same with latex-environments
622         if (keep_layout) {
623                 tmp->setLayout(par.layout());
624                 tmp->setLabelWidthString(par.params().labelWidthString());
625                 tmp->params().depth(par.params().depth());
626         } else if (par.params().depth() > 0) {
627                 Paragraph const & hook = pars[outerHook(par_offset, pars)];
628                 tmp->setLayout(hook.layout());
629                 // not sure the line below is useful
630                 tmp->setLabelWidthString(par.params().labelWidthString());
631                 tmp->params().depth(hook.params().depth());
632         }
633
634         bool const isempty = (par.allowEmpty() && par.empty());
635
636         if (!isempty && (par.size() > pos || par.empty())) {
637                 tmp->setLayout(par.layout());
638                 tmp->params().align(par.params().align());
639                 tmp->setLabelWidthString(par.params().labelWidthString());
640
641                 tmp->params().depth(par.params().depth());
642                 tmp->params().noindent(par.params().noindent());
643
644                 // move everything behind the break position
645                 // to the new paragraph
646
647                 /* Note: if !keepempty, empty() == true, then we reach
648                  * here with size() == 0. So pos_end becomes - 1. This
649                  * doesn't cause problems because both loops below
650                  * enforce pos <= pos_end and 0 <= pos
651                  */
652                 pos_type pos_end = par.size() - 1;
653
654                 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
655                         if (moveItem(par, pos, *tmp, j, bparams)) {
656                                 ++j;
657                         }
658                 }
659         }
660
661         // Move over the end-of-par change information
662         tmp->setChange(tmp->size(), par.lookupChange(par.size()));
663         par.setChange(par.size(), Change(bparams.trackChanges ?
664                                            Change::INSERTED : Change::UNCHANGED));
665
666         if (pos) {
667                 // Make sure that we keep the language when
668                 // breaking paragraph.
669                 if (tmp->empty()) {
670                         Font changed = tmp->getFirstFontSettings(bparams);
671                         Font const & old = par.getFontSettings(bparams, par.size());
672                         changed.setLanguage(old.language());
673                         tmp->setFont(0, changed);
674                 }
675
676                 return;
677         }
678
679         if (!isempty) {
680                 bool const soa = par.params().startOfAppendix();
681                 par.params().clear();
682                 // do not lose start of appendix marker (bug 4212)
683                 par.params().startOfAppendix(soa);
684                 par.setPlainOrDefaultLayout(bparams.documentClass());
685         }
686
687         // layout stays the same with latex-environments
688         if (keep_layout) {
689                 par.setLayout(tmp->layout());
690                 par.setLabelWidthString(tmp->params().labelWidthString());
691                 par.params().depth(tmp->params().depth());
692         }
693 }
694
695
696 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
697 {
698         LASSERT(this == cur.text(), /**/);
699
700         Paragraph & cpar = cur.paragraph();
701         pit_type cpit = cur.pit();
702
703         DocumentClass const & tclass = cur.buffer()->params().documentClass();
704         Layout const & layout = cpar.layout();
705
706         // this is only allowed, if the current paragraph is not empty
707         // or caption and if it has not the keepempty flag active
708         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
709             layout.labeltype != LABEL_SENSITIVE)
710                 return;
711
712         // a layout change may affect also the following paragraph
713         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
714
715         // Always break behind a space
716         // It is better to erase the space (Dekel)
717         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
718                 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
719
720         // What should the layout for the new paragraph be?
721         bool keep_layout = inverse_logic ? 
722                 !layout.isEnvironment() 
723                 : layout.isEnvironment();
724
725         // We need to remember this before we break the paragraph, because
726         // that invalidates the layout variable
727         bool sensitive = layout.labeltype == LABEL_SENSITIVE;
728
729         // we need to set this before we insert the paragraph.
730         bool const isempty = cpar.allowEmpty() && cpar.empty();
731
732         lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
733                          cur.pos(), keep_layout);
734
735         // After this, neither paragraph contains any rows!
736
737         cpit = cur.pit();
738         pit_type next_par = cpit + 1;
739
740         // well this is the caption hack since one caption is really enough
741         if (sensitive) {
742                 if (cur.pos() == 0)
743                         // set to standard-layout
744                 //FIXME Check if this should be plainLayout() in some cases
745                         pars_[cpit].applyLayout(tclass.defaultLayout());
746                 else
747                         // set to standard-layout
748                         //FIXME Check if this should be plainLayout() in some cases
749                         pars_[next_par].applyLayout(tclass.defaultLayout());
750         }
751
752         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
753                 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
754                         break; // the character couldn't be deleted physically due to change tracking
755         }
756
757         cur.buffer()->updateLabels();
758
759         // A singlePar update is not enough in this case.
760         cur.updateFlags(Update::Force);
761
762         // This check is necessary. Otherwise the new empty paragraph will
763         // be deleted automatically. And it is more friendly for the user!
764         if (cur.pos() != 0 || isempty)
765                 setCursor(cur, cur.pit() + 1, 0);
766         else
767                 setCursor(cur, cur.pit(), 0);
768 }
769
770
771 // needed to insert the selection
772 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
773                 Font const & font)
774 {
775         BufferParams const & bparams = owner_->buffer().params();
776         pit_type pit = dit.pit();
777         pos_type pos = dit.pos();
778
779         // insert the string, don't insert doublespace
780         bool space_inserted = true;
781         for (docstring::const_iterator cit = str.begin();
782             cit != str.end(); ++cit) {
783                 Paragraph & par = pars_[pit];
784                 if (*cit == '\n') {
785                         if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
786                                 lyx::breakParagraph(bparams, pars_, pit, pos,
787                                                par.layout().isEnvironment());
788                                 ++pit;
789                                 pos = 0;
790                                 space_inserted = true;
791                         } else {
792                                 continue;
793                         }
794                         // do not insert consecutive spaces if !free_spacing
795                 } else if ((*cit == ' ' || *cit == '\t') &&
796                            space_inserted && !par.isFreeSpacing()) {
797                         continue;
798                 } else if (*cit == '\t') {
799                         if (!par.isFreeSpacing()) {
800                                 // tabs are like spaces here
801                                 par.insertChar(pos, ' ', font, bparams.trackChanges);
802                                 ++pos;
803                                 space_inserted = true;
804                         } else {
805                                 par.insertChar(pos, *cit, font, bparams.trackChanges);
806                                 ++pos;
807                                 space_inserted = true;
808                         }
809                 } else if (!isPrintable(*cit)) {
810                         // Ignore unprintables
811                         continue;
812                 } else {
813                         // just insert the character
814                         par.insertChar(pos, *cit, font, bparams.trackChanges);
815                         ++pos;
816                         space_inserted = (*cit == ' ');
817                 }
818         }
819 }
820
821
822 // turn double CR to single CR, others are converted into one
823 // blank. Then insertStringAsLines is called
824 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
825                 Font const & font)
826 {
827         docstring linestr = str;
828         bool newline_inserted = false;
829
830         for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
831                 if (linestr[i] == '\n') {
832                         if (newline_inserted) {
833                                 // we know that \r will be ignored by
834                                 // insertStringAsLines. Of course, it is a dirty
835                                 // trick, but it works...
836                                 linestr[i - 1] = '\r';
837                                 linestr[i] = '\n';
838                         } else {
839                                 linestr[i] = ' ';
840                                 newline_inserted = true;
841                         }
842                 } else if (isPrintable(linestr[i])) {
843                         newline_inserted = false;
844                 }
845         }
846         insertStringAsLines(dit, linestr, font);
847 }
848
849
850 // insert a character, moves all the following breaks in the
851 // same Paragraph one to the right and make a rebreak
852 void Text::insertChar(Cursor & cur, char_type c)
853 {
854         LASSERT(this == cur.text(), /**/);
855
856         cur.recordUndo(INSERT_UNDO);
857
858         TextMetrics const & tm = cur.bv().textMetrics(this);
859         Buffer const & buffer = *cur.buffer();
860         Paragraph & par = cur.paragraph();
861         // try to remove this
862         pit_type const pit = cur.pit();
863
864         bool const freeSpacing = par.layout().free_spacing ||
865                 par.isFreeSpacing();
866
867         if (lyxrc.auto_number) {
868                 static docstring const number_operators = from_ascii("+-/*");
869                 static docstring const number_unary_operators = from_ascii("+-");
870                 static docstring const number_seperators = from_ascii(".,:");
871
872                 if (cur.current_font.fontInfo().number() == FONT_ON) {
873                         if (!isDigit(c) && !contains(number_operators, c) &&
874                             !(contains(number_seperators, c) &&
875                               cur.pos() != 0 &&
876                               cur.pos() != cur.lastpos() &&
877                               tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
878                               tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
879                            )
880                                 number(cur); // Set current_font.number to OFF
881                 } else if (isDigit(c) &&
882                            cur.real_current_font.isVisibleRightToLeft()) {
883                         number(cur); // Set current_font.number to ON
884
885                         if (cur.pos() != 0) {
886                                 char_type const c = par.getChar(cur.pos() - 1);
887                                 if (contains(number_unary_operators, c) &&
888                                     (cur.pos() == 1
889                                      || par.isSeparator(cur.pos() - 2)
890                                      || par.isNewline(cur.pos() - 2))
891                                   ) {
892                                         setCharFont(pit, cur.pos() - 1, cur.current_font,
893                                                 tm.font_);
894                                 } else if (contains(number_seperators, c)
895                                      && cur.pos() >= 2
896                                      && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
897                                         setCharFont(pit, cur.pos() - 1, cur.current_font,
898                                                 tm.font_);
899                                 }
900                         }
901                 }
902         }
903
904         // In Bidi text, we want spaces to be treated in a special way: spaces
905         // which are between words in different languages should get the 
906         // paragraph's language; otherwise, spaces should keep the language 
907         // they were originally typed in. This is only in effect while typing;
908         // after the text is already typed in, the user can always go back and
909         // explicitly set the language of a space as desired. But 99.9% of the
910         // time, what we're doing here is what the user actually meant.
911         // 
912         // The following cases are the ones in which the language of the space
913         // should be changed to match that of the containing paragraph. In the
914         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
915         // represents a space, pipe (|) represents the cursor position (so the
916         // character before it is the one just typed in). The different cases
917         // are depicted logically (not visually), from left to right:
918         // 
919         // 1. A_a|
920         // 2. a_A|
921         //
922         // Theoretically, there are other situations that we should, perhaps, deal
923         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
924         // point (to understand why, just try to create this situation...).
925
926         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
927                 // get font in front and behind the space in question. But do NOT 
928                 // use getFont(cur.pos()) because the character c is not inserted yet
929                 Font const pre_space_font  = tm.displayFont(cur.pit(), cur.pos() - 2);
930                 Font const & post_space_font = cur.real_current_font;
931                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
932                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
933                 
934                 if (pre_space_rtl != post_space_rtl) {
935                         // Set the space's language to match the language of the 
936                         // adjacent character whose direction is the paragraph's
937                         // direction; don't touch other properties of the font
938                         Language const * lang = 
939                                 (pre_space_rtl == par.isRTL(buffer.params())) ?
940                                 pre_space_font.language() : post_space_font.language();
941
942                         Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
943                         space_font.setLanguage(lang);
944                         par.setFont(cur.pos() - 1, space_font);
945                 }
946         }
947         
948         // Next check, if there will be two blanks together or a blank at
949         // the beginning of a paragraph.
950         // I decided to handle blanks like normal characters, the main
951         // difference are the special checks when calculating the row.fill
952         // (blank does not count at the end of a row) and the check here
953
954         // When the free-spacing option is set for the current layout,
955         // disable the double-space checking
956         if (!freeSpacing && isLineSeparatorChar(c)) {
957                 if (cur.pos() == 0) {
958                         static bool sent_space_message = false;
959                         if (!sent_space_message) {
960                                 cur.message(_("You cannot insert a space at the "
961                                                            "beginning of a paragraph. Please read the Tutorial."));
962                                 sent_space_message = true;
963                         }
964                         return;
965                 }
966                 LASSERT(cur.pos() > 0, /**/);
967                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
968                     && !par.isDeleted(cur.pos() - 1)) {
969                         static bool sent_space_message = false;
970                         if (!sent_space_message) {
971                                 cur.message(_("You cannot type two spaces this way. "
972                                                            "Please read the Tutorial."));
973                                 sent_space_message = true;
974                         }
975                         return;
976                 }
977         }
978
979         par.insertChar(cur.pos(), c, cur.current_font,
980                 cur.buffer()->params().trackChanges);
981         cur.checkBufferStructure();
982
983 //              cur.updateFlags(Update::Force);
984         bool boundary = tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
985         setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
986         charInserted(cur);
987 }
988
989
990 void Text::charInserted(Cursor & cur)
991 {
992         Paragraph & par = cur.paragraph();
993
994         // Here we call finishUndo for every 20 characters inserted.
995         // This is from my experience how emacs does it. (Lgb)
996         static unsigned int counter;
997         if (counter < 20) {
998                 ++counter;
999         } else {
1000                 cur.finishUndo();
1001                 counter = 0;
1002         }
1003
1004         // register word if a non-letter was entered
1005         if (cur.pos() > 1
1006             && !par.isWordSeparator(cur.pos() - 2)
1007             && par.isWordSeparator(cur.pos() - 1)) {
1008                 // get the word in front of cursor
1009                 LASSERT(this == cur.text(), /**/);
1010                 cur.paragraph().updateWords();
1011         }
1012 }
1013
1014
1015 // the cursor set functions have a special mechanism. When they
1016 // realize, that you left an empty paragraph, they will delete it.
1017
1018 bool Text::cursorForwardOneWord(Cursor & cur)
1019 {
1020         LASSERT(this == cur.text(), /**/);
1021
1022         pos_type const lastpos = cur.lastpos();
1023         pit_type pit = cur.pit();
1024         pos_type pos = cur.pos();
1025         Paragraph const & par = cur.paragraph();
1026
1027         // Paragraph boundary is a word boundary
1028         if (pos == lastpos) {
1029                 if (pit != cur.lastpit())
1030                         return setCursor(cur, pit + 1, 0);
1031                 else
1032                         return false;
1033         }
1034
1035         if (lyxrc.mac_like_word_movement) {
1036                 // Skip through trailing punctuation and spaces.
1037                 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1038                         ++pos;
1039
1040                 // Skip over either a non-char inset or a full word
1041                 if (pos != lastpos && par.isWordSeparator(pos))
1042                         ++pos;
1043                 else while (pos != lastpos && !par.isWordSeparator(pos))
1044                              ++pos;
1045         } else {
1046                 LASSERT(pos < lastpos, /**/); // see above
1047                 if (!par.isWordSeparator(pos))
1048                         while (pos != lastpos && !par.isWordSeparator(pos))
1049                                 ++pos;
1050                 else if (par.isChar(pos))
1051                         while (pos != lastpos && par.isChar(pos))
1052                                 ++pos;
1053                 else if (!par.isSpace(pos)) // non-char inset
1054                         ++pos;
1055
1056                 // Skip over white space
1057                 while (pos != lastpos && par.isSpace(pos))
1058                              ++pos;             
1059         }
1060
1061         return setCursor(cur, pit, pos);
1062 }
1063
1064
1065 bool Text::cursorBackwardOneWord(Cursor & cur)
1066 {
1067         LASSERT(this == cur.text(), /**/);
1068
1069         pit_type pit = cur.pit();
1070         pos_type pos = cur.pos();
1071         Paragraph & par = cur.paragraph();
1072
1073         // Paragraph boundary is a word boundary
1074         if (pos == 0 && pit != 0)
1075                 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1076
1077         if (lyxrc.mac_like_word_movement) {
1078                 // Skip through punctuation and spaces.
1079                 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1080                         --pos;
1081
1082                 // Skip over either a non-char inset or a full word
1083                 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1084                         --pos;
1085                 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1086                              --pos;
1087         } else {
1088                 // Skip over white space
1089                 while (pos != 0 && par.isSpace(pos - 1))
1090                              --pos;
1091
1092                 if (pos != 0 && !par.isWordSeparator(pos - 1))
1093                         while (pos != 0 && !par.isWordSeparator(pos - 1))
1094                                 --pos;
1095                 else if (pos != 0 && par.isChar(pos - 1))
1096                         while (pos != 0 && par.isChar(pos - 1))
1097                                 --pos;
1098                 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1099                         --pos;
1100         }
1101
1102         return setCursor(cur, pit, pos);
1103 }
1104
1105
1106 bool Text::cursorVisLeftOneWord(Cursor & cur)
1107 {
1108         LASSERT(this == cur.text(), /**/);
1109
1110         pos_type left_pos, right_pos;
1111         bool left_is_letter, right_is_letter;
1112
1113         Cursor temp_cur = cur;
1114
1115         // always try to move at least once...
1116         while (temp_cur.posVisLeft(true /* skip_inset */)) {
1117
1118                 // collect some information about current cursor position
1119                 temp_cur.getSurroundingPos(left_pos, right_pos);
1120                 left_is_letter = 
1121                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1122                 right_is_letter = 
1123                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1124
1125                 // if we're not at a letter/non-letter boundary, continue moving
1126                 if (left_is_letter == right_is_letter)
1127                         continue;
1128
1129                 // we should stop when we have an LTR word on our right or an RTL word
1130                 // on our left
1131                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1132                                 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1133                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1134                                 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1135                         break;
1136         }
1137
1138         return setCursor(cur, temp_cur.pit(), temp_cur.pos(), 
1139                                          true, temp_cur.boundary());
1140 }
1141
1142
1143 bool Text::cursorVisRightOneWord(Cursor & cur)
1144 {
1145         LASSERT(this == cur.text(), /**/);
1146
1147         pos_type left_pos, right_pos;
1148         bool left_is_letter, right_is_letter;
1149
1150         Cursor temp_cur = cur;
1151
1152         // always try to move at least once...
1153         while (temp_cur.posVisRight(true /* skip_inset */)) {
1154
1155                 // collect some information about current cursor position
1156                 temp_cur.getSurroundingPos(left_pos, right_pos);
1157                 left_is_letter = 
1158                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1159                 right_is_letter = 
1160                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1161
1162                 // if we're not at a letter/non-letter boundary, continue moving
1163                 if (left_is_letter == right_is_letter)
1164                         continue;
1165
1166                 // we should stop when we have an LTR word on our right or an RTL word
1167                 // on our left
1168                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1169                                 temp_cur.buffer()->params(), 
1170                                 left_pos).isRightToLeft())
1171                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1172                                 temp_cur.buffer()->params(), 
1173                                 right_pos).isRightToLeft()))
1174                         break;
1175         }
1176
1177         return setCursor(cur, temp_cur.pit(), temp_cur.pos(), 
1178                                          true, temp_cur.boundary());
1179 }
1180
1181
1182 void Text::selectWord(Cursor & cur, word_location loc)
1183 {
1184         LASSERT(this == cur.text(), /**/);
1185         CursorSlice from = cur.top();
1186         CursorSlice to = cur.top();
1187         getWord(from, to, loc);
1188         if (cur.top() != from)
1189                 setCursor(cur, from.pit(), from.pos());
1190         if (to == from)
1191                 return;
1192         cur.resetAnchor();
1193         setCursor(cur, to.pit(), to.pos());
1194         cur.setSelection();
1195 }
1196
1197
1198 void Text::selectAll(Cursor & cur)
1199 {
1200         LASSERT(this == cur.text(), /**/);
1201         if (cur.lastpos() == 0 && cur.lastpit() == 0)
1202                 return;
1203         // If the cursor is at the beginning, make sure the cursor ends there
1204         if (cur.pit() == 0 && cur.pos() == 0) {
1205                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1206                 cur.resetAnchor();
1207                 setCursor(cur, 0, 0);           
1208         } else {
1209                 setCursor(cur, 0, 0);
1210                 cur.resetAnchor();
1211                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1212         }
1213         cur.setSelection();
1214 }
1215
1216
1217 // Select the word currently under the cursor when no
1218 // selection is currently set
1219 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1220 {
1221         LASSERT(this == cur.text(), /**/);
1222         if (cur.selection())
1223                 return false;
1224         selectWord(cur, loc);
1225         return cur.selection();
1226 }
1227
1228
1229 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1230 {
1231         LASSERT(this == cur.text(), /**/);
1232
1233         if (!cur.selection()) {
1234                 bool const changed = cur.paragraph().isChanged(cur.pos());
1235                 if (!(changed && findNextChange(&cur.bv())))
1236                         return;
1237         }
1238
1239         cur.recordUndoSelection();
1240
1241         pit_type begPit = cur.selectionBegin().pit();
1242         pit_type endPit = cur.selectionEnd().pit();
1243
1244         pos_type begPos = cur.selectionBegin().pos();
1245         pos_type endPos = cur.selectionEnd().pos();
1246
1247         // keep selection info, because endPos becomes invalid after the first loop
1248         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1249
1250         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1251
1252         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1253                 pos_type parSize = pars_[pit].size();
1254
1255                 // ignore empty paragraphs; otherwise, an assertion will fail for
1256                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1257                 if (parSize == 0)
1258                         continue;
1259
1260                 // do not consider first paragraph if the cursor starts at pos size()
1261                 if (pit == begPit && begPos == parSize)
1262                         continue;
1263
1264                 // do not consider last paragraph if the cursor ends at pos 0
1265                 if (pit == endPit && endPos == 0)
1266                         break; // last iteration anyway
1267
1268                 pos_type left  = (pit == begPit ? begPos : 0);
1269                 pos_type right = (pit == endPit ? endPos : parSize);
1270
1271                 if (op == ACCEPT) {
1272                         pars_[pit].acceptChanges(left, right);
1273                 } else {
1274                         pars_[pit].rejectChanges(left, right);
1275                 }
1276         }
1277
1278         // next, accept/reject imaginary end-of-par characters
1279
1280         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1281                 pos_type pos = pars_[pit].size();
1282
1283                 // skip if the selection ends before the end-of-par
1284                 if (pit == endPit && endsBeforeEndOfPar)
1285                         break; // last iteration anyway
1286
1287                 // skip if this is not the last paragraph of the document
1288                 // note: the user should be able to accept/reject the par break of the last par!
1289                 if (pit == endPit && pit + 1 != int(pars_.size()))
1290                         break; // last iteration anway
1291
1292                 if (op == ACCEPT) {
1293                         if (pars_[pit].isInserted(pos)) {
1294                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1295                         } else if (pars_[pit].isDeleted(pos)) {
1296                                 if (pit + 1 == int(pars_.size())) {
1297                                         // we cannot remove a par break at the end of the last paragraph;
1298                                         // instead, we mark it unchanged
1299                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1300                                 } else {
1301                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1302                                         --endPit;
1303                                         --pit;
1304                                 }
1305                         }
1306                 } else {
1307                         if (pars_[pit].isDeleted(pos)) {
1308                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1309                         } else if (pars_[pit].isInserted(pos)) {
1310                                 if (pit + 1 == int(pars_.size())) {
1311                                         // we mark the par break at the end of the last paragraph unchanged
1312                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1313                                 } else {
1314                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1315                                         --endPit;
1316                                         --pit;
1317                                 }
1318                         }
1319                 }
1320         }
1321
1322         // finally, invoke the DEPM
1323
1324         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1325
1326         //
1327
1328         cur.finishUndo();
1329         cur.clearSelection();
1330         setCursorIntern(cur, begPit, begPos);
1331         cur.updateFlags(Update::Force);
1332         cur.buffer()->updateLabels();
1333 }
1334
1335
1336 void Text::acceptChanges()
1337 {
1338         BufferParams const & bparams = owner_->buffer().params();
1339         lyx::acceptChanges(pars_, bparams);
1340         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1341 }
1342
1343
1344 void Text::rejectChanges()
1345 {
1346         BufferParams const & bparams = owner_->buffer().params();
1347         pit_type pars_size = static_cast<pit_type>(pars_.size());
1348
1349         // first, reject changes within each individual paragraph
1350         // (do not consider end-of-par)
1351         for (pit_type pit = 0; pit < pars_size; ++pit) {
1352                 if (!pars_[pit].empty())   // prevent assertion failure
1353                         pars_[pit].rejectChanges(0, pars_[pit].size());
1354         }
1355
1356         // next, reject imaginary end-of-par characters
1357         for (pit_type pit = 0; pit < pars_size; ++pit) {
1358                 pos_type pos = pars_[pit].size();
1359
1360                 if (pars_[pit].isDeleted(pos)) {
1361                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1362                 } else if (pars_[pit].isInserted(pos)) {
1363                         if (pit == pars_size - 1) {
1364                                 // we mark the par break at the end of the last
1365                                 // paragraph unchanged
1366                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1367                         } else {
1368                                 mergeParagraph(bparams, pars_, pit);
1369                                 --pit;
1370                                 --pars_size;
1371                         }
1372                 }
1373         }
1374
1375         // finally, invoke the DEPM
1376         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1377 }
1378
1379
1380 void Text::deleteWordForward(Cursor & cur)
1381 {
1382         LASSERT(this == cur.text(), /**/);
1383         if (cur.lastpos() == 0)
1384                 cursorForward(cur);
1385         else {
1386                 cur.resetAnchor();
1387                 cur.setSelection(true);
1388                 cursorForwardOneWord(cur);
1389                 cur.setSelection();
1390                 cutSelection(cur, true, false);
1391                 cur.checkBufferStructure();
1392         }
1393 }
1394
1395
1396 void Text::deleteWordBackward(Cursor & cur)
1397 {
1398         LASSERT(this == cur.text(), /**/);
1399         if (cur.lastpos() == 0)
1400                 cursorBackward(cur);
1401         else {
1402                 cur.resetAnchor();
1403                 cur.setSelection(true);
1404                 cursorBackwardOneWord(cur);
1405                 cur.setSelection();
1406                 cutSelection(cur, true, false);
1407                 cur.checkBufferStructure();
1408         }
1409 }
1410
1411
1412 // Kill to end of line.
1413 void Text::changeCase(Cursor & cur, TextCase action)
1414 {
1415         LASSERT(this == cur.text(), /**/);
1416         CursorSlice from;
1417         CursorSlice to;
1418
1419         bool gotsel = false;
1420         if (cur.selection()) {
1421                 from = cur.selBegin();
1422                 to = cur.selEnd();
1423                 gotsel = true;
1424         } else {
1425                 from = cur.top();
1426                 getWord(from, to, PARTIAL_WORD);
1427                 cursorForwardOneWord(cur);
1428         }
1429
1430         cur.recordUndoSelection();
1431
1432         pit_type begPit = from.pit();
1433         pit_type endPit = to.pit();
1434
1435         pos_type begPos = from.pos();
1436         pos_type endPos = to.pos();
1437
1438         pos_type right = 0; // needed after the for loop
1439
1440         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1441                 Paragraph & par = pars_[pit];
1442                 pos_type const pos = (pit == begPit ? begPos : 0);
1443                 right = (pit == endPit ? endPos : par.size());
1444                 par.changeCase(cur.buffer()->params(), pos, right, action);
1445         }
1446
1447         // the selection may have changed due to logically-only deleted chars
1448         if (gotsel) {
1449                 setCursor(cur, begPit, begPos);
1450                 cur.resetAnchor();
1451                 setCursor(cur, endPit, right);
1452                 cur.setSelection();
1453         } else
1454                 setCursor(cur, endPit, right);
1455
1456         cur.checkBufferStructure();
1457 }
1458
1459
1460 bool Text::handleBibitems(Cursor & cur)
1461 {
1462         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1463                 return false;
1464
1465         if (cur.pos() != 0)
1466                 return false;
1467
1468         BufferParams const & bufparams = cur.buffer()->params();
1469         Paragraph const & par = cur.paragraph();
1470         Cursor prevcur = cur;
1471         if (cur.pit() > 0) {
1472                 --prevcur.pit();
1473                 prevcur.pos() = prevcur.lastpos();
1474         }
1475         Paragraph const & prevpar = prevcur.paragraph();
1476
1477         // if a bibitem is deleted, merge with previous paragraph
1478         // if this is a bibliography item as well
1479         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1480                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1481                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1482                                                         prevcur.pit());
1483                 cur.buffer()->updateLabels();
1484                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1485                 cur.updateFlags(Update::Force);
1486                 return true;
1487         } 
1488
1489         // otherwise reset to default
1490         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1491         return true;
1492 }
1493
1494
1495 bool Text::erase(Cursor & cur)
1496 {
1497         LASSERT(this == cur.text(), return false);
1498         bool needsUpdate = false;
1499         Paragraph & par = cur.paragraph();
1500
1501         if (cur.pos() != cur.lastpos()) {
1502                 // this is the code for a normal delete, not pasting
1503                 // any paragraphs
1504                 cur.recordUndo(DELETE_UNDO);
1505                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1506                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1507                         // the character has been logically deleted only => skip it
1508                         cur.top().forwardPos();
1509
1510                 if (was_inset)
1511                         cur.buffer()->updateLabels();
1512                 else
1513                         cur.checkBufferStructure();
1514                 needsUpdate = true;
1515         } else {
1516                 if (cur.pit() == cur.lastpit())
1517                         return dissolveInset(cur);
1518
1519                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1520                         par.setChange(cur.pos(), Change(Change::DELETED));
1521                         cur.forwardPos();
1522                         needsUpdate = true;
1523                 } else {
1524                         setCursorIntern(cur, cur.pit() + 1, 0);
1525                         needsUpdate = backspacePos0(cur);
1526                 }
1527         }
1528
1529         needsUpdate |= handleBibitems(cur);
1530
1531         if (needsUpdate) {
1532                 // Make sure the cursor is correct. Is this really needed?
1533                 // No, not really... at least not here!
1534                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1535                 cur.checkBufferStructure();
1536         }
1537
1538         return needsUpdate;
1539 }
1540
1541
1542 bool Text::backspacePos0(Cursor & cur)
1543 {
1544         LASSERT(this == cur.text(), /**/);
1545         if (cur.pit() == 0)
1546                 return false;
1547
1548         bool needsUpdate = false;
1549
1550         BufferParams const & bufparams = cur.buffer()->params();
1551         DocumentClass const & tclass = bufparams.documentClass();
1552         ParagraphList & plist = cur.text()->paragraphs();
1553         Paragraph const & par = cur.paragraph();
1554         Cursor prevcur = cur;
1555         --prevcur.pit();
1556         prevcur.pos() = prevcur.lastpos();
1557         Paragraph const & prevpar = prevcur.paragraph();
1558
1559         // is it an empty paragraph?
1560         if (cur.lastpos() == 0
1561             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1562                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1563                 plist.erase(boost::next(plist.begin(), cur.pit()));
1564                 needsUpdate = true;
1565         }
1566         // is previous par empty?
1567         else if (prevcur.lastpos() == 0
1568                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1569                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1570                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1571                 needsUpdate = true;
1572         }
1573         // Pasting is not allowed, if the paragraphs have different
1574         // layouts. I think it is a real bug of all other
1575         // word processors to allow it. It confuses the user.
1576         // Correction: Pasting is always allowed with standard-layout
1577         // or the empty layout.
1578         else if (par.layout() == prevpar.layout()
1579                  || tclass.isDefaultLayout(par.layout())
1580                  || tclass.isPlainLayout(par.layout())) {
1581                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1582                 mergeParagraph(bufparams, plist, prevcur.pit());
1583                 needsUpdate = true;
1584         }
1585
1586         if (needsUpdate) {
1587                 cur.buffer()->updateLabels();
1588                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1589         }
1590
1591         return needsUpdate;
1592 }
1593
1594
1595 bool Text::backspace(Cursor & cur)
1596 {
1597         LASSERT(this == cur.text(), /**/);
1598         bool needsUpdate = false;
1599         if (cur.pos() == 0) {
1600                 if (cur.pit() == 0)
1601                         return dissolveInset(cur);
1602
1603                 Paragraph & prev_par = pars_[cur.pit() - 1];
1604
1605                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1606                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1607                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1608                         return true;
1609                 }
1610                 // The cursor is at the beginning of a paragraph, so
1611                 // the backspace will collapse two paragraphs into one.
1612                 needsUpdate = backspacePos0(cur);
1613
1614         } else {
1615                 // this is the code for a normal backspace, not pasting
1616                 // any paragraphs
1617                 cur.recordUndo(DELETE_UNDO);
1618                 // We used to do cursorBackwardIntern() here, but it is
1619                 // not a good idea since it triggers the auto-delete
1620                 // mechanism. So we do a cursorBackwardIntern()-lite,
1621                 // without the dreaded mechanism. (JMarc)
1622                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1623                                 false, cur.boundary());
1624                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1625                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1626                 if (was_inset)
1627                         cur.buffer()->updateLabels();
1628                 else
1629                         cur.checkBufferStructure();
1630         }
1631
1632         if (cur.pos() == cur.lastpos())
1633                 cur.setCurrentFont();
1634
1635         needsUpdate |= handleBibitems(cur);
1636
1637         // A singlePar update is not enough in this case.
1638 //              cur.updateFlags(Update::Force);
1639         setCursor(cur.top(), cur.pit(), cur.pos());
1640
1641         return needsUpdate;
1642 }
1643
1644
1645 bool Text::dissolveInset(Cursor & cur)
1646 {
1647         LASSERT(this == cur.text(), return false);
1648
1649         if (isMainText() || cur.inset().nargs() != 1)
1650                 return false;
1651
1652         cur.recordUndoInset();
1653         cur.setMark(false);
1654         cur.selHandle(false);
1655         // save position
1656         pos_type spos = cur.pos();
1657         pit_type spit = cur.pit();
1658         ParagraphList plist;
1659         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1660                 plist = paragraphs();
1661         cur.popBackward();
1662         // store cursor offset
1663         if (spit == 0)
1664                 spos += cur.pos();
1665         spit += cur.pit();
1666         Buffer & b = *cur.buffer();
1667         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1668         if (!plist.empty()) {
1669                 // ERT paragraphs have the Language latex_language.
1670                 // This is invalid outside of ERT, so we need to
1671                 // change it to the buffer language.
1672                 ParagraphList::iterator it = plist.begin();
1673                 ParagraphList::iterator it_end = plist.end();
1674                 for (; it != it_end; it++)
1675                         it->changeLanguage(b.params(), latex_language, b.language());
1676
1677                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1678                                    b.errorList("Paste"));
1679                 // restore position
1680                 cur.pit() = min(cur.lastpit(), spit);
1681                 cur.pos() = min(cur.lastpos(), spos);
1682         } else
1683                 // this is the least that needs to be done (bug 6003)
1684                 // in the above case, pasteParagraphList handles this
1685                 cur.buffer()->updateLabels();
1686         cur.clearSelection();
1687         cur.resetAnchor();
1688         return true;
1689 }
1690
1691
1692 void Text::getWord(CursorSlice & from, CursorSlice & to,
1693         word_location const loc) const
1694 {
1695         to = from;
1696         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1697 }
1698
1699
1700 void Text::write(ostream & os) const
1701 {
1702         Buffer const & buf = owner_->buffer();
1703         ParagraphList::const_iterator pit = paragraphs().begin();
1704         ParagraphList::const_iterator end = paragraphs().end();
1705         depth_type dth = 0;
1706         for (; pit != end; ++pit)
1707                 pit->write(os, buf.params(), dth);
1708
1709         // Close begin_deeper
1710         for(; dth > 0; --dth)
1711                 os << "\n\\end_deeper";
1712 }
1713
1714
1715 bool Text::read(Lexer & lex, 
1716                 ErrorList & errorList, InsetText * insetPtr)
1717 {
1718         Buffer const & buf = owner_->buffer();
1719         depth_type depth = 0;
1720         bool res = true;
1721
1722         while (lex.isOK()) {
1723                 lex.nextToken();
1724                 string const token = lex.getString();
1725
1726                 if (token.empty())
1727                         continue;
1728
1729                 if (token == "\\end_inset")
1730                         break;
1731
1732                 if (token == "\\end_body")
1733                         continue;
1734
1735                 if (token == "\\begin_body")
1736                         continue;
1737
1738                 if (token == "\\end_document") {
1739                         res = false;
1740                         break;
1741                 }
1742
1743                 if (token == "\\begin_layout") {
1744                         lex.pushToken(token);
1745
1746                         Paragraph par;
1747                         par.setInsetOwner(insetPtr);
1748                         par.params().depth(depth);
1749                         par.setFont(0, Font(inherit_font, buf.params().language));
1750                         pars_.push_back(par);
1751                         readParagraph(pars_.back(), lex, errorList);
1752
1753                         // register the words in the global word list
1754                         CursorSlice sl = CursorSlice(*insetPtr);
1755                         sl.pit() = pars_.size() - 1;
1756                         pars_.back().updateWords();
1757                 } else if (token == "\\begin_deeper") {
1758                         ++depth;
1759                 } else if (token == "\\end_deeper") {
1760                         if (!depth)
1761                                 lex.printError("\\end_deeper: " "depth is already null");
1762                         else
1763                                 --depth;
1764                 } else {
1765                         LYXERR0("Handling unknown body token: `" << token << '\'');
1766                 }
1767         }
1768
1769         // avoid a crash on weird documents (bug 4859)
1770         if (pars_.empty()) {
1771                 Paragraph par;
1772                 par.setInsetOwner(insetPtr);
1773                 par.params().depth(depth);
1774                 par.setFont(0, Font(inherit_font, 
1775                                     buf.params().language));
1776                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1777                 pars_.push_back(par);
1778         }
1779         
1780         return res;
1781 }
1782
1783 // Returns the current font and depth as a message.
1784 docstring Text::currentState(Cursor const & cur) const
1785 {
1786         LASSERT(this == cur.text(), /**/);
1787         Buffer & buf = *cur.buffer();
1788         Paragraph const & par = cur.paragraph();
1789         odocstringstream os;
1790
1791         if (buf.params().trackChanges)
1792                 os << _("[Change Tracking] ");
1793
1794         Change change = par.lookupChange(cur.pos());
1795
1796         if (change.changed()) {
1797                 Author const & a = buf.params().authors().get(change.author);
1798                 os << _("Change: ") << a.name();
1799                 if (!a.email().empty())
1800                         os << " (" << a.email() << ")";
1801                 // FIXME ctime is english, we should translate that
1802                 os << _(" at ") << ctime(&change.changetime);
1803                 os << " : ";
1804         }
1805
1806         // I think we should only show changes from the default
1807         // font. (Asger)
1808         // No, from the document font (MV)
1809         Font font = cur.real_current_font;
1810         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1811
1812         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1813
1814         // The paragraph depth
1815         int depth = cur.paragraph().getDepth();
1816         if (depth > 0)
1817                 os << bformat(_(", Depth: %1$d"), depth);
1818
1819         // The paragraph spacing, but only if different from
1820         // buffer spacing.
1821         Spacing const & spacing = par.params().spacing();
1822         if (!spacing.isDefault()) {
1823                 os << _(", Spacing: ");
1824                 switch (spacing.getSpace()) {
1825                 case Spacing::Single:
1826                         os << _("Single");
1827                         break;
1828                 case Spacing::Onehalf:
1829                         os << _("OneHalf");
1830                         break;
1831                 case Spacing::Double:
1832                         os << _("Double");
1833                         break;
1834                 case Spacing::Other:
1835                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1836                         break;
1837                 case Spacing::Default:
1838                         // should never happen, do nothing
1839                         break;
1840                 }
1841         }
1842
1843 #ifdef DEVEL_VERSION
1844         os << _(", Inset: ") << &cur.inset();
1845         os << _(", Paragraph: ") << cur.pit();
1846         os << _(", Id: ") << par.id();
1847         os << _(", Position: ") << cur.pos();
1848         // FIXME: Why is the check for par.size() needed?
1849         // We are called with cur.pos() == par.size() quite often.
1850         if (!par.empty() && cur.pos() < par.size()) {
1851                 // Force output of code point, not character
1852                 size_t const c = par.getChar(cur.pos());
1853                 os << _(", Char: 0x") << hex << c;
1854         }
1855         os << _(", Boundary: ") << cur.boundary();
1856 //      Row & row = cur.textRow();
1857 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1858 #endif
1859         return os.str();
1860 }
1861
1862
1863 docstring Text::getPossibleLabel(Cursor const & cur) const
1864 {
1865         pit_type pit = cur.pit();
1866
1867         Layout const * layout = &(pars_[pit].layout());
1868
1869         docstring text;
1870         docstring par_text = pars_[pit].asString();
1871         string piece;
1872         // the return string of math matrices might contain linebreaks
1873         par_text = subst(par_text, '\n', '-');
1874         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1875                 if (par_text.empty())
1876                         break;
1877                 docstring head;
1878                 par_text = split(par_text, head, ' ');
1879                 // Is it legal to use spaces in labels ?
1880                 if (i > 0)
1881                         text += '-';
1882                 text += head;
1883         }
1884
1885         // No need for a prefix if the user said so.
1886         if (lyxrc.label_init_length <= 0)
1887                 return text;
1888
1889         // Will contain the label type.
1890         docstring name;
1891
1892         // For section, subsection, etc...
1893         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1894                 Layout const * layout2 = &(pars_[pit - 1].layout());
1895                 if (layout2->latextype != LATEX_PARAGRAPH) {
1896                         --pit;
1897                         layout = layout2;
1898                 }
1899         }
1900         if (layout->latextype != LATEX_PARAGRAPH)
1901                 name = from_ascii(layout->latexname());
1902
1903         // for captions, we just take the caption type
1904         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1905         if (caption_inset)
1906                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1907
1908         // If none of the above worked, we'll see if we're inside various
1909         // types of insets and take our abbreviation from them.
1910         if (name.empty()) {
1911                 InsetCode const codes[] = {
1912                         FLOAT_CODE,
1913                         WRAP_CODE,
1914                         FOOT_CODE
1915                 };
1916                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1917                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1918                         if (float_inset) {
1919                                 name = float_inset->name();
1920                                 break;
1921                         }
1922                 }
1923         }
1924
1925         // Create a correct prefix for prettyref
1926         if (name == "theorem")
1927                 name = from_ascii("thm");
1928         else if (name == "Foot")
1929                 name = from_ascii("fn");
1930         else if (name == "listing")
1931                 name = from_ascii("lst");
1932
1933         if (!name.empty())
1934                 text = name.substr(0, 3) + ':' + text;
1935
1936         return text;
1937 }
1938
1939
1940 docstring Text::asString(int options) const
1941 {
1942         return asString(0, pars_.size(), options);
1943 }
1944
1945
1946 docstring Text::asString(pit_type beg, pit_type end, int options) const
1947 {
1948         size_t i = size_t(beg);
1949         docstring str = pars_[i].asString(options);
1950         for (++i; i != size_t(end); ++i) {
1951                 str += '\n';
1952                 str += pars_[i].asString(options);
1953         }
1954         return str;
1955 }
1956
1957
1958
1959 void Text::charsTranspose(Cursor & cur)
1960 {
1961         LASSERT(this == cur.text(), /**/);
1962
1963         pos_type pos = cur.pos();
1964
1965         // If cursor is at beginning or end of paragraph, do nothing.
1966         if (pos == cur.lastpos() || pos == 0)
1967                 return;
1968
1969         Paragraph & par = cur.paragraph();
1970
1971         // Get the positions of the characters to be transposed.
1972         pos_type pos1 = pos - 1;
1973         pos_type pos2 = pos;
1974
1975         // In change tracking mode, ignore deleted characters.
1976         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1977                 ++pos2;
1978         if (pos2 == cur.lastpos())
1979                 return;
1980
1981         while (pos1 >= 0 && par.isDeleted(pos1))
1982                 --pos1;
1983         if (pos1 < 0)
1984                 return;
1985
1986         // Don't do anything if one of the "characters" is not regular text.
1987         if (par.isInset(pos1) || par.isInset(pos2))
1988                 return;
1989
1990         // Store the characters to be transposed (including font information).
1991         char_type const char1 = par.getChar(pos1);
1992         Font const font1 =
1993                 par.getFontSettings(cur.buffer()->params(), pos1);
1994
1995         char_type const char2 = par.getChar(pos2);
1996         Font const font2 =
1997                 par.getFontSettings(cur.buffer()->params(), pos2);
1998
1999         // And finally, we are ready to perform the transposition.
2000         // Track the changes if Change Tracking is enabled.
2001         bool const trackChanges = cur.buffer()->params().trackChanges;
2002
2003         cur.recordUndo();
2004
2005         par.eraseChar(pos2, trackChanges);
2006         par.eraseChar(pos1, trackChanges);
2007         par.insertChar(pos1, char2, font2, trackChanges);
2008         par.insertChar(pos2, char1, font1, trackChanges);
2009
2010         cur.checkBufferStructure();
2011
2012         // After the transposition, move cursor to after the transposition.
2013         setCursor(cur, cur.pit(), pos2);
2014         cur.forwardPos();
2015 }
2016
2017
2018 DocIterator Text::macrocontextPosition() const
2019 {
2020         return macrocontext_position_;
2021 }
2022
2023
2024 void Text::setMacrocontextPosition(DocIterator const & pos)
2025 {
2026         macrocontext_position_ = pos;
2027 }
2028
2029
2030 docstring Text::previousWord(CursorSlice const & sl) const
2031 {
2032         CursorSlice from = sl;
2033         CursorSlice to = sl;
2034         getWord(from, to, PREVIOUS_WORD);
2035         if (sl == from || to == from)
2036                 return docstring();
2037         
2038         Paragraph const & par = sl.paragraph();
2039         return par.asString(from.pos(), to.pos());
2040 }
2041
2042
2043 bool Text::completionSupported(Cursor const & cur) const
2044 {
2045         Paragraph const & par = cur.paragraph();
2046         return cur.pos() > 0
2047                 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2048                 && !par.isWordSeparator(cur.pos() - 1);
2049 }
2050
2051
2052 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2053 {
2054         return new TextCompletionList(cur);
2055 }
2056
2057
2058 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2059 {       
2060         LASSERT(cur.bv().cursor() == cur, /**/);
2061         cur.insert(s);
2062         cur.bv().cursor() = cur;
2063         if (!(cur.disp_.update() & Update::Force))
2064                 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2065         return true;
2066 }
2067         
2068         
2069 docstring Text::completionPrefix(Cursor const & cur) const
2070 {
2071         return previousWord(cur.top());
2072 }
2073
2074 } // namespace lyx