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