]> git.lyx.org Git - features.git/blob - src/Text.cpp
Fix problem with static error list.
[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/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                 tclass.addLayoutIfNeeded(layoutname);
360                 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
361                 if (added_one) {
362                         // Warn the user.
363                         docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
364                         errorList.push_back(
365                                 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
366                 }
367
368                 par.setLayout(bp.documentClass()[layoutname]);
369
370                 // Test whether the layout is obsolete.
371                 Layout const & layout = par.layout();
372                 if (!layout.obsoleted_by().empty())
373                         par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
374
375                 par.params().read(lex);
376
377         } else if (token == "\\end_layout") {
378                 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
379                        << "Missing \\begin_layout ?");
380         } else if (token == "\\end_inset") {
381                 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
382                        << "Missing \\begin_inset ?");
383         } else if (token == "\\begin_inset") {
384                 Inset * inset = readInset(lex, buf);
385                 if (inset)
386                         par.insertInset(par.size(), inset, font, change);
387                 else {
388                         lex.eatLine();
389                         docstring line = lex.getDocString();
390                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
391                                             par.id(), 0, par.size()));
392                 }
393         } else if (token == "\\family") {
394                 lex.next();
395                 setLyXFamily(lex.getString(), font.fontInfo());
396         } else if (token == "\\series") {
397                 lex.next();
398                 setLyXSeries(lex.getString(), font.fontInfo());
399         } else if (token == "\\shape") {
400                 lex.next();
401                 setLyXShape(lex.getString(), font.fontInfo());
402         } else if (token == "\\size") {
403                 lex.next();
404                 setLyXSize(lex.getString(), font.fontInfo());
405         } else if (token == "\\lang") {
406                 lex.next();
407                 string const tok = lex.getString();
408                 Language const * lang = languages.getLanguage(tok);
409                 if (lang) {
410                         font.setLanguage(lang);
411                 } else {
412                         font.setLanguage(bp.language);
413                         lex.printError("Unknown language `$$Token'");
414                 }
415         } else if (token == "\\numeric") {
416                 lex.next();
417                 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
418         } else if (token == "\\emph") {
419                 lex.next();
420                 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
421         } else if (token == "\\bar") {
422                 lex.next();
423                 string const tok = lex.getString();
424
425                 if (tok == "under")
426                         font.fontInfo().setUnderbar(FONT_ON);
427                 else if (tok == "no")
428                         font.fontInfo().setUnderbar(FONT_OFF);
429                 else if (tok == "default")
430                         font.fontInfo().setUnderbar(FONT_INHERIT);
431                 else
432                         lex.printError("Unknown bar font flag "
433                                        "`$$Token'");
434         } else if (token == "\\strikeout") {
435                 lex.next();
436                 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
437         } else if (token == "\\uuline") {
438                 lex.next();
439                 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
440         } else if (token == "\\uwave") {
441                 lex.next();
442                 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
443         } else if (token == "\\noun") {
444                 lex.next();
445                 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
446         } else if (token == "\\color") {
447                 lex.next();
448                 setLyXColor(lex.getString(), font.fontInfo());
449         } else if (token == "\\SpecialChar") {
450                 auto_ptr<Inset> inset;
451                 inset.reset(new InsetSpecialChar);
452                 inset->read(lex);
453                 inset->setBuffer(*buf);
454                 par.insertInset(par.size(), inset.release(), font, change);
455         } else if (token == "\\backslash") {
456                 par.appendChar('\\', font, change);
457         } else if (token == "\\LyXTable") {
458                 auto_ptr<Inset> inset(new InsetTabular(buf));
459                 inset->read(lex);
460                 par.insertInset(par.size(), inset.release(), font, change);
461         } else if (token == "\\change_unchanged") {
462                 change = Change(Change::UNCHANGED);
463         } else if (token == "\\change_inserted" || token == "\\change_deleted") {
464                 lex.eatLine();
465                 istringstream is(lex.getString());
466                 int aid;
467                 time_t ct;
468                 is >> aid >> ct;
469                 BufferParams::AuthorMap const & am = bp.author_map;
470                 if (am.find(aid) == am.end()) {
471                         errorList.push_back(ErrorItem(_("Change tracking error"),
472                                             bformat(_("Unknown author index for change: %1$d\n"), aid),
473                                             par.id(), 0, par.size()));
474                         change = Change(Change::UNCHANGED);
475                 } else {
476                         if (token == "\\change_inserted")
477                                 change = Change(Change::INSERTED, am.find(aid)->second, ct);
478                         else
479                                 change = Change(Change::DELETED, am.find(aid)->second, ct);
480                 }
481         } else {
482                 lex.eatLine();
483                 errorList.push_back(ErrorItem(_("Unknown token"),
484                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
485                         lex.getDocString()),
486                         par.id(), 0, par.size()));
487         }
488 }
489
490
491 void Text::readParagraph(Paragraph & par, Lexer & lex,
492         ErrorList & errorList)
493 {
494         lex.nextToken();
495         string token = lex.getString();
496         Font font;
497         Change change(Change::UNCHANGED);
498
499         while (lex.isOK()) {
500                 readParToken(par, lex, token, font, change, errorList);
501
502                 lex.nextToken();
503                 token = lex.getString();
504
505                 if (token.empty())
506                         continue;
507
508                 if (token == "\\end_layout") {
509                         //Ok, paragraph finished
510                         break;
511                 }
512
513                 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
514                 if (token == "\\begin_layout" || token == "\\end_document"
515                     || token == "\\end_inset" || token == "\\begin_deeper"
516                     || token == "\\end_deeper") {
517                         lex.pushToken(token);
518                         lyxerr << "Paragraph ended in line "
519                                << lex.lineNumber() << "\n"
520                                << "Missing \\end_layout.\n";
521                         break;
522                 }
523         }
524         // Final change goes to paragraph break:
525         par.setChange(par.size(), change);
526
527         // Initialize begin_of_body_ on load; redoParagraph maintains
528         par.setBeginOfBody();
529         
530         // mark paragraph for spell checking on load
531         // par.requestSpellCheck();
532 }
533
534
535 class TextCompletionList : public CompletionList
536 {
537 public:
538         ///
539         TextCompletionList(Cursor const & cur, WordList const * list)
540                 : buffer_(cur.buffer()), pos_(0), list_(list)
541         {}
542         ///
543         virtual ~TextCompletionList() {}
544         
545         ///
546         virtual bool sorted() const { return true; }
547         ///
548         virtual size_t size() const
549         {
550                 return list_->size();
551         }
552         ///
553         virtual docstring const & data(size_t idx) const
554         {
555                 return list_->word(idx);
556         }
557         
558 private:
559         ///
560         Buffer const * buffer_;
561         ///
562         size_t pos_;
563         ///
564         WordList const * list_;
565 };
566
567
568 bool Text::empty() const
569 {
570         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
571                 // FIXME: Should we consider the labeled type as empty too? 
572                 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
573 }
574
575
576 double Text::spacing(Paragraph const & par) const
577 {
578         if (par.params().spacing().isDefault())
579                 return owner_->buffer().params().spacing().getValue();
580         return par.params().spacing().getValue();
581 }
582
583
584 /**
585  * This breaks a paragraph at the specified position.
586  * The new paragraph will:
587  * - Decrease depth by one (or change layout to default layout) when
588  *    keep_layout == false  
589  * - keep current depth and layout when keep_layout == true
590  */
591 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos, 
592                     bool keep_layout)
593 {
594         BufferParams const & bparams = text.inset().buffer().params();
595         ParagraphList & pars = text.paragraphs();
596         // create a new paragraph, and insert into the list
597         ParagraphList::iterator tmp =
598                 pars.insert(boost::next(pars.begin(), par_offset + 1),
599                             Paragraph());
600
601         Paragraph & par = pars[par_offset];
602
603         // remember to set the inset_owner
604         tmp->setInsetOwner(&par.inInset());
605         // without doing that we get a crash when typing <Return> at the
606         // end of a paragraph
607         tmp->setPlainOrDefaultLayout(bparams.documentClass());
608
609         if (keep_layout) {
610                 tmp->setLayout(par.layout());
611                 tmp->setLabelWidthString(par.params().labelWidthString());
612                 tmp->params().depth(par.params().depth());
613         } else if (par.params().depth() > 0) {
614                 Paragraph const & hook = pars[text.outerHook(par_offset)];
615                 tmp->setLayout(hook.layout());
616                 // not sure the line below is useful
617                 tmp->setLabelWidthString(par.params().labelWidthString());
618                 tmp->params().depth(hook.params().depth());
619         }
620
621         bool const isempty = (par.allowEmpty() && par.empty());
622
623         if (!isempty && (par.size() > pos || par.empty())) {
624                 tmp->setLayout(par.layout());
625                 tmp->params().align(par.params().align());
626                 tmp->setLabelWidthString(par.params().labelWidthString());
627
628                 tmp->params().depth(par.params().depth());
629                 tmp->params().noindent(par.params().noindent());
630
631                 // move everything behind the break position
632                 // to the new paragraph
633
634                 /* Note: if !keepempty, empty() == true, then we reach
635                  * here with size() == 0. So pos_end becomes - 1. This
636                  * doesn't cause problems because both loops below
637                  * enforce pos <= pos_end and 0 <= pos
638                  */
639                 pos_type pos_end = par.size() - 1;
640
641                 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
642                         if (moveItem(par, pos, *tmp, j, bparams)) {
643                                 ++j;
644                         }
645                 }
646         }
647
648         // Move over the end-of-par change information
649         tmp->setChange(tmp->size(), par.lookupChange(par.size()));
650         par.setChange(par.size(), Change(bparams.trackChanges ?
651                                            Change::INSERTED : Change::UNCHANGED));
652
653         if (pos) {
654                 // Make sure that we keep the language when
655                 // breaking paragraph.
656                 if (tmp->empty()) {
657                         Font changed = tmp->getFirstFontSettings(bparams);
658                         Font const & old = par.getFontSettings(bparams, par.size());
659                         changed.setLanguage(old.language());
660                         tmp->setFont(0, changed);
661                 }
662
663                 return;
664         }
665
666         if (!isempty) {
667                 bool const soa = par.params().startOfAppendix();
668                 par.params().clear();
669                 // do not lose start of appendix marker (bug 4212)
670                 par.params().startOfAppendix(soa);
671                 par.setPlainOrDefaultLayout(bparams.documentClass());
672         }
673
674         if (keep_layout) {
675                 par.setLayout(tmp->layout());
676                 par.setLabelWidthString(tmp->params().labelWidthString());
677                 par.params().depth(tmp->params().depth());
678         }
679 }
680
681
682 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
683 {
684         LASSERT(this == cur.text(), /**/);
685
686         Paragraph & cpar = cur.paragraph();
687         pit_type cpit = cur.pit();
688
689         DocumentClass const & tclass = cur.buffer()->params().documentClass();
690         Layout const & layout = cpar.layout();
691
692         if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
693                 if (changeDepthAllowed(cur, DEC_DEPTH))
694                         changeDepth(cur, DEC_DEPTH);
695                 else 
696                         setLayout(cur, tclass.defaultLayoutName());
697                 return;
698         }
699
700         // a layout change may affect also the following paragraph
701         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
702
703         // Always break behind a space
704         // It is better to erase the space (Dekel)
705         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
706                 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
707
708         // What should the layout for the new paragraph be?
709         bool keep_layout = layout.isEnvironment() 
710                 || (layout.isParagraph() && layout.parbreak_is_newline);
711         if (inverse_logic)
712                 keep_layout = !keep_layout;
713
714         // We need to remember this before we break the paragraph, because
715         // that invalidates the layout variable
716         bool sensitive = layout.labeltype == LABEL_SENSITIVE;
717
718         // we need to set this before we insert the paragraph.
719         bool const isempty = cpar.allowEmpty() && cpar.empty();
720
721         lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
722
723         // After this, neither paragraph contains any rows!
724
725         cpit = cur.pit();
726         pit_type next_par = cpit + 1;
727
728         // well this is the caption hack since one caption is really enough
729         if (sensitive) {
730                 if (cur.pos() == 0)
731                         // set to standard-layout
732                 //FIXME Check if this should be plainLayout() in some cases
733                         pars_[cpit].applyLayout(tclass.defaultLayout());
734                 else
735                         // set to standard-layout
736                         //FIXME Check if this should be plainLayout() in some cases
737                         pars_[next_par].applyLayout(tclass.defaultLayout());
738         }
739
740         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
741                 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
742                         break; // the character couldn't be deleted physically due to change tracking
743         }
744
745         // A singlePar update is not enough in this case.
746         cur.screenUpdateFlags(Update::Force);
747         cur.forceBufferUpdate();
748
749         // This check is necessary. Otherwise the new empty paragraph will
750         // be deleted automatically. And it is more friendly for the user!
751         if (cur.pos() != 0 || isempty)
752                 setCursor(cur, cur.pit() + 1, 0);
753         else
754                 setCursor(cur, cur.pit(), 0);
755 }
756
757
758 // needed to insert the selection
759 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
760                 Font const & font)
761 {
762         BufferParams const & bparams = owner_->buffer().params();
763         pit_type pit = dit.pit();
764         pos_type pos = dit.pos();
765
766         // insert the string, don't insert doublespace
767         bool space_inserted = true;
768         for (docstring::const_iterator cit = str.begin();
769             cit != str.end(); ++cit) {
770                 Paragraph & par = pars_[pit];
771                 if (*cit == '\n') {
772                         if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
773                                 lyx::breakParagraph(*this, pit, pos,
774                                         par.layout().isEnvironment());
775                                 ++pit;
776                                 pos = 0;
777                                 space_inserted = true;
778                         } else {
779                                 continue;
780                         }
781                         // do not insert consecutive spaces if !free_spacing
782                 } else if ((*cit == ' ' || *cit == '\t') &&
783                            space_inserted && !par.isFreeSpacing()) {
784                         continue;
785                 } else if (*cit == '\t') {
786                         if (!par.isFreeSpacing()) {
787                                 // tabs are like spaces here
788                                 par.insertChar(pos, ' ', font, bparams.trackChanges);
789                                 ++pos;
790                                 space_inserted = true;
791                         } else {
792                                 par.insertChar(pos, *cit, font, bparams.trackChanges);
793                                 ++pos;
794                                 space_inserted = true;
795                         }
796                 } else if (!isPrintable(*cit)) {
797                         // Ignore unprintables
798                         continue;
799                 } else {
800                         // just insert the character
801                         par.insertChar(pos, *cit, font, bparams.trackChanges);
802                         ++pos;
803                         space_inserted = (*cit == ' ');
804                 }
805         }
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(DocIterator const & dit, 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(dit, 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 (op == ACCEPT) {
1255                         pars_[pit].acceptChanges(left, right);
1256                 } else {
1257                         pars_[pit].rejectChanges(left, right);
1258                 }
1259         }
1260
1261         // next, accept/reject imaginary end-of-par characters
1262
1263         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1264                 pos_type pos = pars_[pit].size();
1265
1266                 // skip if the selection ends before the end-of-par
1267                 if (pit == endPit && endsBeforeEndOfPar)
1268                         break; // last iteration anyway
1269
1270                 // skip if this is not the last paragraph of the document
1271                 // note: the user should be able to accept/reject the par break of the last par!
1272                 if (pit == endPit && pit + 1 != int(pars_.size()))
1273                         break; // last iteration anway
1274
1275                 if (op == ACCEPT) {
1276                         if (pars_[pit].isInserted(pos)) {
1277                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1278                         } else if (pars_[pit].isDeleted(pos)) {
1279                                 if (pit + 1 == int(pars_.size())) {
1280                                         // we cannot remove a par break at the end of the last paragraph;
1281                                         // instead, we mark it unchanged
1282                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1283                                 } else {
1284                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1285                                         --endPit;
1286                                         --pit;
1287                                 }
1288                         }
1289                 } else {
1290                         if (pars_[pit].isDeleted(pos)) {
1291                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1292                         } else if (pars_[pit].isInserted(pos)) {
1293                                 if (pit + 1 == int(pars_.size())) {
1294                                         // we mark the par break at the end of the last paragraph unchanged
1295                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1296                                 } else {
1297                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1298                                         --endPit;
1299                                         --pit;
1300                                 }
1301                         }
1302                 }
1303         }
1304
1305         // finally, invoke the DEPM
1306
1307         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1308
1309         //
1310
1311         cur.finishUndo();
1312         cur.clearSelection();
1313         setCursorIntern(cur, begPit, begPos);
1314         cur.screenUpdateFlags(Update::Force);
1315         cur.forceBufferUpdate();
1316 }
1317
1318
1319 void Text::acceptChanges()
1320 {
1321         BufferParams const & bparams = owner_->buffer().params();
1322         lyx::acceptChanges(pars_, bparams);
1323         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1324 }
1325
1326
1327 void Text::rejectChanges()
1328 {
1329         BufferParams const & bparams = owner_->buffer().params();
1330         pit_type pars_size = static_cast<pit_type>(pars_.size());
1331
1332         // first, reject changes within each individual paragraph
1333         // (do not consider end-of-par)
1334         for (pit_type pit = 0; pit < pars_size; ++pit) {
1335                 if (!pars_[pit].empty())   // prevent assertion failure
1336                         pars_[pit].rejectChanges(0, pars_[pit].size());
1337         }
1338
1339         // next, reject imaginary end-of-par characters
1340         for (pit_type pit = 0; pit < pars_size; ++pit) {
1341                 pos_type pos = pars_[pit].size();
1342
1343                 if (pars_[pit].isDeleted(pos)) {
1344                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1345                 } else if (pars_[pit].isInserted(pos)) {
1346                         if (pit == pars_size - 1) {
1347                                 // we mark the par break at the end of the last
1348                                 // paragraph unchanged
1349                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1350                         } else {
1351                                 mergeParagraph(bparams, pars_, pit);
1352                                 --pit;
1353                                 --pars_size;
1354                         }
1355                 }
1356         }
1357
1358         // finally, invoke the DEPM
1359         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1360 }
1361
1362
1363 void Text::deleteWordForward(Cursor & cur)
1364 {
1365         LASSERT(this == cur.text(), /**/);
1366         if (cur.lastpos() == 0)
1367                 cursorForward(cur);
1368         else {
1369                 cur.resetAnchor();
1370                 cur.setSelection(true);
1371                 cursorForwardOneWord(cur);
1372                 cur.setSelection();
1373                 cutSelection(cur, true, false);
1374                 cur.checkBufferStructure();
1375         }
1376 }
1377
1378
1379 void Text::deleteWordBackward(Cursor & cur)
1380 {
1381         LASSERT(this == cur.text(), /**/);
1382         if (cur.lastpos() == 0)
1383                 cursorBackward(cur);
1384         else {
1385                 cur.resetAnchor();
1386                 cur.setSelection(true);
1387                 cursorBackwardOneWord(cur);
1388                 cur.setSelection();
1389                 cutSelection(cur, true, false);
1390                 cur.checkBufferStructure();
1391         }
1392 }
1393
1394
1395 // Kill to end of line.
1396 void Text::changeCase(Cursor & cur, TextCase action)
1397 {
1398         LASSERT(this == cur.text(), /**/);
1399         CursorSlice from;
1400         CursorSlice to;
1401
1402         bool gotsel = false;
1403         if (cur.selection()) {
1404                 from = cur.selBegin();
1405                 to = cur.selEnd();
1406                 gotsel = true;
1407         } else {
1408                 from = cur.top();
1409                 getWord(from, to, PARTIAL_WORD);
1410                 cursorForwardOneWord(cur);
1411         }
1412
1413         cur.recordUndoSelection();
1414
1415         pit_type begPit = from.pit();
1416         pit_type endPit = to.pit();
1417
1418         pos_type begPos = from.pos();
1419         pos_type endPos = to.pos();
1420
1421         pos_type right = 0; // needed after the for loop
1422
1423         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1424                 Paragraph & par = pars_[pit];
1425                 pos_type const pos = (pit == begPit ? begPos : 0);
1426                 right = (pit == endPit ? endPos : par.size());
1427                 par.changeCase(cur.buffer()->params(), pos, right, action);
1428         }
1429
1430         // the selection may have changed due to logically-only deleted chars
1431         if (gotsel) {
1432                 setCursor(cur, begPit, begPos);
1433                 cur.resetAnchor();
1434                 setCursor(cur, endPit, right);
1435                 cur.setSelection();
1436         } else
1437                 setCursor(cur, endPit, right);
1438
1439         cur.checkBufferStructure();
1440 }
1441
1442
1443 bool Text::handleBibitems(Cursor & cur)
1444 {
1445         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1446                 return false;
1447
1448         if (cur.pos() != 0)
1449                 return false;
1450
1451         BufferParams const & bufparams = cur.buffer()->params();
1452         Paragraph const & par = cur.paragraph();
1453         Cursor prevcur = cur;
1454         if (cur.pit() > 0) {
1455                 --prevcur.pit();
1456                 prevcur.pos() = prevcur.lastpos();
1457         }
1458         Paragraph const & prevpar = prevcur.paragraph();
1459
1460         // if a bibitem is deleted, merge with previous paragraph
1461         // if this is a bibliography item as well
1462         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1463                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1464                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1465                                                         prevcur.pit());
1466                 cur.forceBufferUpdate();
1467                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1468                 cur.screenUpdateFlags(Update::Force);
1469                 return true;
1470         } 
1471
1472         // otherwise reset to default
1473         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1474         return true;
1475 }
1476
1477
1478 bool Text::erase(Cursor & cur)
1479 {
1480         LASSERT(this == cur.text(), return false);
1481         bool needsUpdate = false;
1482         Paragraph & par = cur.paragraph();
1483
1484         if (cur.pos() != cur.lastpos()) {
1485                 // this is the code for a normal delete, not pasting
1486                 // any paragraphs
1487                 cur.recordUndo(DELETE_UNDO);
1488                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1489                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1490                         // the character has been logically deleted only => skip it
1491                         cur.top().forwardPos();
1492
1493                 if (was_inset)
1494                         cur.forceBufferUpdate();
1495                 else
1496                         cur.checkBufferStructure();
1497                 needsUpdate = true;
1498         } else {
1499                 if (cur.pit() == cur.lastpit())
1500                         return dissolveInset(cur);
1501
1502                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1503                         par.setChange(cur.pos(), Change(Change::DELETED));
1504                         cur.forwardPos();
1505                         needsUpdate = true;
1506                 } else {
1507                         setCursorIntern(cur, cur.pit() + 1, 0);
1508                         needsUpdate = backspacePos0(cur);
1509                 }
1510         }
1511
1512         needsUpdate |= handleBibitems(cur);
1513
1514         if (needsUpdate) {
1515                 // Make sure the cursor is correct. Is this really needed?
1516                 // No, not really... at least not here!
1517                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1518                 cur.checkBufferStructure();
1519         }
1520
1521         return needsUpdate;
1522 }
1523
1524
1525 bool Text::backspacePos0(Cursor & cur)
1526 {
1527         LASSERT(this == cur.text(), /**/);
1528         if (cur.pit() == 0)
1529                 return false;
1530
1531         bool needsUpdate = false;
1532
1533         BufferParams const & bufparams = cur.buffer()->params();
1534         DocumentClass const & tclass = bufparams.documentClass();
1535         ParagraphList & plist = cur.text()->paragraphs();
1536         Paragraph const & par = cur.paragraph();
1537         Cursor prevcur = cur;
1538         --prevcur.pit();
1539         prevcur.pos() = prevcur.lastpos();
1540         Paragraph const & prevpar = prevcur.paragraph();
1541
1542         // is it an empty paragraph?
1543         if (cur.lastpos() == 0
1544             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1545                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1546                 plist.erase(boost::next(plist.begin(), cur.pit()));
1547                 needsUpdate = true;
1548         }
1549         // is previous par empty?
1550         else if (prevcur.lastpos() == 0
1551                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1552                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1553                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1554                 needsUpdate = true;
1555         }
1556         // Pasting is not allowed, if the paragraphs have different
1557         // layouts. I think it is a real bug of all other
1558         // word processors to allow it. It confuses the user.
1559         // Correction: Pasting is always allowed with standard-layout
1560         // or the empty layout.
1561         else if (par.layout() == prevpar.layout()
1562                  || tclass.isDefaultLayout(par.layout())
1563                  || tclass.isPlainLayout(par.layout())) {
1564                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1565                 mergeParagraph(bufparams, plist, prevcur.pit());
1566                 needsUpdate = true;
1567         }
1568
1569         if (needsUpdate) {
1570                 cur.forceBufferUpdate();
1571                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1572         }
1573
1574         return needsUpdate;
1575 }
1576
1577
1578 bool Text::backspace(Cursor & cur)
1579 {
1580         LASSERT(this == cur.text(), /**/);
1581         bool needsUpdate = false;
1582         if (cur.pos() == 0) {
1583                 if (cur.pit() == 0)
1584                         return dissolveInset(cur);
1585
1586                 Paragraph & prev_par = pars_[cur.pit() - 1];
1587
1588                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1589                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1590                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1591                         return true;
1592                 }
1593                 // The cursor is at the beginning of a paragraph, so
1594                 // the backspace will collapse two paragraphs into one.
1595                 needsUpdate = backspacePos0(cur);
1596
1597         } else {
1598                 // this is the code for a normal backspace, not pasting
1599                 // any paragraphs
1600                 cur.recordUndo(DELETE_UNDO);
1601                 // We used to do cursorBackwardIntern() here, but it is
1602                 // not a good idea since it triggers the auto-delete
1603                 // mechanism. So we do a cursorBackwardIntern()-lite,
1604                 // without the dreaded mechanism. (JMarc)
1605                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1606                                 false, cur.boundary());
1607                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1608                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1609                 if (was_inset)
1610                         cur.forceBufferUpdate();
1611                 else
1612                         cur.checkBufferStructure();
1613         }
1614
1615         if (cur.pos() == cur.lastpos())
1616                 cur.setCurrentFont();
1617
1618         needsUpdate |= handleBibitems(cur);
1619
1620         // A singlePar update is not enough in this case.
1621 //              cur.screenUpdateFlags(Update::Force);
1622         setCursor(cur.top(), cur.pit(), cur.pos());
1623
1624         return needsUpdate;
1625 }
1626
1627
1628 bool Text::dissolveInset(Cursor & cur)
1629 {
1630         LASSERT(this == cur.text(), return false);
1631
1632         if (isMainText() || cur.inset().nargs() != 1)
1633                 return false;
1634
1635         cur.recordUndoInset();
1636         cur.setMark(false);
1637         cur.selHandle(false);
1638         // save position
1639         pos_type spos = cur.pos();
1640         pit_type spit = cur.pit();
1641         ParagraphList plist;
1642         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1643                 plist = paragraphs();
1644         cur.popBackward();
1645         // store cursor offset
1646         if (spit == 0)
1647                 spos += cur.pos();
1648         spit += cur.pit();
1649         Buffer & b = *cur.buffer();
1650         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1651
1652         if (!plist.empty()) {
1653                 // see bug 7319
1654                 // we clear the cache so that we won't get conflicts with labels
1655                 // that get pasted into the buffer. we should update this before
1656                 // its being empty matters. if not (i.e., if we encounter bugs),
1657                 // then this should instead be:
1658                 //        cur.buffer().updateBuffer();
1659                 // but we'll try the cheaper solution here.
1660                 cur.buffer()->clearReferenceCache();
1661
1662                 // ERT paragraphs have the Language latex_language.
1663                 // This is invalid outside of ERT, so we need to
1664                 // change it to the buffer language.
1665                 ParagraphList::iterator it = plist.begin();
1666                 ParagraphList::iterator it_end = plist.end();
1667                 for (; it != it_end; it++)
1668                         it->changeLanguage(b.params(), latex_language, b.language());
1669
1670                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1671                                    b.errorList("Paste"));
1672                 // restore position
1673                 cur.pit() = min(cur.lastpit(), spit);
1674                 cur.pos() = min(cur.lastpos(), spos);
1675         }
1676
1677         cur.forceBufferUpdate();
1678
1679         // Ensure the current language is set correctly (bug 6292)
1680         cur.text()->setCursor(cur, cur.pit(), cur.pos());
1681         cur.clearSelection();
1682         cur.resetAnchor();
1683         return true;
1684 }
1685
1686
1687 void Text::getWord(CursorSlice & from, CursorSlice & to,
1688         word_location const loc) const
1689 {
1690         to = from;
1691         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1692 }
1693
1694
1695 void Text::write(ostream & os) const
1696 {
1697         Buffer const & buf = owner_->buffer();
1698         ParagraphList::const_iterator pit = paragraphs().begin();
1699         ParagraphList::const_iterator end = paragraphs().end();
1700         depth_type dth = 0;
1701         for (; pit != end; ++pit)
1702                 pit->write(os, buf.params(), dth);
1703
1704         // Close begin_deeper
1705         for(; dth > 0; --dth)
1706                 os << "\n\\end_deeper";
1707 }
1708
1709
1710 bool Text::read(Lexer & lex, 
1711                 ErrorList & errorList, InsetText * insetPtr)
1712 {
1713         Buffer const & buf = owner_->buffer();
1714         depth_type depth = 0;
1715         bool res = true;
1716
1717         while (lex.isOK()) {
1718                 lex.nextToken();
1719                 string const token = lex.getString();
1720
1721                 if (token.empty())
1722                         continue;
1723
1724                 if (token == "\\end_inset")
1725                         break;
1726
1727                 if (token == "\\end_body")
1728                         continue;
1729
1730                 if (token == "\\begin_body")
1731                         continue;
1732
1733                 if (token == "\\end_document") {
1734                         res = false;
1735                         break;
1736                 }
1737
1738                 if (token == "\\begin_layout") {
1739                         lex.pushToken(token);
1740
1741                         Paragraph par;
1742                         par.setInsetOwner(insetPtr);
1743                         par.params().depth(depth);
1744                         par.setFont(0, Font(inherit_font, buf.params().language));
1745                         pars_.push_back(par);
1746                         readParagraph(pars_.back(), lex, errorList);
1747
1748                         // register the words in the global word list
1749                         pars_.back().updateWords();
1750                 } else if (token == "\\begin_deeper") {
1751                         ++depth;
1752                 } else if (token == "\\end_deeper") {
1753                         if (!depth)
1754                                 lex.printError("\\end_deeper: " "depth is already null");
1755                         else
1756                                 --depth;
1757                 } else {
1758                         LYXERR0("Handling unknown body token: `" << token << '\'');
1759                 }
1760         }
1761
1762         // avoid a crash on weird documents (bug 4859)
1763         if (pars_.empty()) {
1764                 Paragraph par;
1765                 par.setInsetOwner(insetPtr);
1766                 par.params().depth(depth);
1767                 par.setFont(0, Font(inherit_font, 
1768                                     buf.params().language));
1769                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1770                 pars_.push_back(par);
1771         }
1772         
1773         return res;
1774 }
1775
1776 // Returns the current font and depth as a message.
1777 docstring Text::currentState(Cursor const & cur) const
1778 {
1779         LASSERT(this == cur.text(), /**/);
1780         Buffer & buf = *cur.buffer();
1781         Paragraph const & par = cur.paragraph();
1782         odocstringstream os;
1783
1784         if (buf.params().trackChanges)
1785                 os << _("[Change Tracking] ");
1786
1787         Change change = par.lookupChange(cur.pos());
1788
1789         if (change.changed()) {
1790                 Author const & a = buf.params().authors().get(change.author);
1791                 os << _("Change: ") << a.name();
1792                 if (!a.email().empty())
1793                         os << " (" << a.email() << ")";
1794                 // FIXME ctime is english, we should translate that
1795                 os << _(" at ") << ctime(&change.changetime);
1796                 os << " : ";
1797         }
1798
1799         // I think we should only show changes from the default
1800         // font. (Asger)
1801         // No, from the document font (MV)
1802         Font font = cur.real_current_font;
1803         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1804
1805         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1806
1807         // The paragraph depth
1808         int depth = cur.paragraph().getDepth();
1809         if (depth > 0)
1810                 os << bformat(_(", Depth: %1$d"), depth);
1811
1812         // The paragraph spacing, but only if different from
1813         // buffer spacing.
1814         Spacing const & spacing = par.params().spacing();
1815         if (!spacing.isDefault()) {
1816                 os << _(", Spacing: ");
1817                 switch (spacing.getSpace()) {
1818                 case Spacing::Single:
1819                         os << _("Single");
1820                         break;
1821                 case Spacing::Onehalf:
1822                         os << _("OneHalf");
1823                         break;
1824                 case Spacing::Double:
1825                         os << _("Double");
1826                         break;
1827                 case Spacing::Other:
1828                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1829                         break;
1830                 case Spacing::Default:
1831                         // should never happen, do nothing
1832                         break;
1833                 }
1834         }
1835
1836 #ifdef DEVEL_VERSION
1837         os << _(", Inset: ") << &cur.inset();
1838         os << _(", Paragraph: ") << cur.pit();
1839         os << _(", Id: ") << par.id();
1840         os << _(", Position: ") << cur.pos();
1841         // FIXME: Why is the check for par.size() needed?
1842         // We are called with cur.pos() == par.size() quite often.
1843         if (!par.empty() && cur.pos() < par.size()) {
1844                 // Force output of code point, not character
1845                 size_t const c = par.getChar(cur.pos());
1846                 os << _(", Char: 0x") << hex << c;
1847         }
1848         os << _(", Boundary: ") << cur.boundary();
1849 //      Row & row = cur.textRow();
1850 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1851 #endif
1852         return os.str();
1853 }
1854
1855
1856 docstring Text::getPossibleLabel(Cursor const & cur) const
1857 {
1858         pit_type pit = cur.pit();
1859
1860         Layout const * layout = &(pars_[pit].layout());
1861
1862         docstring text;
1863         docstring par_text = pars_[pit].asString();
1864
1865         // The return string of math matrices might contain linebreaks
1866         par_text = subst(par_text, '\n', '-');
1867         int const numwords = 3;
1868         for (int i = 0; i < numwords; ++i) {
1869                 if (par_text.empty())
1870                         break;
1871                 docstring head;
1872                 par_text = split(par_text, head, ' ');
1873                 // Is it legal to use spaces in labels ?
1874                 if (i > 0)
1875                         text += '-';
1876                 text += head;
1877         }
1878         
1879         // Make sure it isn't too long
1880         unsigned int const max_label_length = 32;
1881         if (text.size() > max_label_length)
1882                 text.resize(max_label_length);
1883
1884         // Will contain the label prefix.
1885         docstring name;
1886
1887         // For section, subsection, etc...
1888         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1889                 Layout const * layout2 = &(pars_[pit - 1].layout());
1890                 if (layout2->latextype != LATEX_PARAGRAPH) {
1891                         --pit;
1892                         layout = layout2;
1893                 }
1894         }
1895         if (layout->latextype != LATEX_PARAGRAPH)
1896                 name = layout->refprefix;
1897
1898         // For captions, we just take the caption type
1899         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1900         if (caption_inset) {
1901                 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1902                 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1903                 if (fl.typeExist(ftype)) {
1904                         Floating const & flt = fl.getType(ftype);
1905                         name = from_utf8(flt.refPrefix());
1906                 }
1907                 if (name.empty())
1908                         name = from_utf8(ftype.substr(0,3));
1909         }
1910
1911         // If none of the above worked, see if the inset knows.
1912         if (name.empty()) {
1913                 InsetLayout const & il = cur.inset().getLayout();
1914                 name = il.refprefix();
1915         }
1916
1917         if (!name.empty())
1918                 text = name + ':' + text;
1919
1920         return text;
1921 }
1922
1923
1924 docstring Text::asString(int options) const
1925 {
1926         return asString(0, pars_.size(), options);
1927 }
1928
1929
1930 docstring Text::asString(pit_type beg, pit_type end, int options) const
1931 {
1932         size_t i = size_t(beg);
1933         docstring str = pars_[i].asString(options);
1934         for (++i; i != size_t(end); ++i) {
1935                 str += '\n';
1936                 str += pars_[i].asString(options);
1937         }
1938         return str;
1939 }
1940
1941
1942 void Text::forToc(docstring & os, size_t maxlen, bool shorten) const
1943 {
1944         LASSERT(maxlen > 10, maxlen = 30);
1945         for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
1946                 pars_[i].forToc(os, maxlen);
1947         if (shorten && os.length() >= maxlen)
1948                 os = os.substr(0, maxlen - 3) + from_ascii("...");
1949 }
1950
1951
1952 void Text::charsTranspose(Cursor & cur)
1953 {
1954         LASSERT(this == cur.text(), /**/);
1955
1956         pos_type pos = cur.pos();
1957
1958         // If cursor is at beginning or end of paragraph, do nothing.
1959         if (pos == cur.lastpos() || pos == 0)
1960                 return;
1961
1962         Paragraph & par = cur.paragraph();
1963
1964         // Get the positions of the characters to be transposed.
1965         pos_type pos1 = pos - 1;
1966         pos_type pos2 = pos;
1967
1968         // In change tracking mode, ignore deleted characters.
1969         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1970                 ++pos2;
1971         if (pos2 == cur.lastpos())
1972                 return;
1973
1974         while (pos1 >= 0 && par.isDeleted(pos1))
1975                 --pos1;
1976         if (pos1 < 0)
1977                 return;
1978
1979         // Don't do anything if one of the "characters" is not regular text.
1980         if (par.isInset(pos1) || par.isInset(pos2))
1981                 return;
1982
1983         // Store the characters to be transposed (including font information).
1984         char_type const char1 = par.getChar(pos1);
1985         Font const font1 =
1986                 par.getFontSettings(cur.buffer()->params(), pos1);
1987
1988         char_type const char2 = par.getChar(pos2);
1989         Font const font2 =
1990                 par.getFontSettings(cur.buffer()->params(), pos2);
1991
1992         // And finally, we are ready to perform the transposition.
1993         // Track the changes if Change Tracking is enabled.
1994         bool const trackChanges = cur.buffer()->params().trackChanges;
1995
1996         cur.recordUndo();
1997
1998         par.eraseChar(pos2, trackChanges);
1999         par.eraseChar(pos1, trackChanges);
2000         par.insertChar(pos1, char2, font2, trackChanges);
2001         par.insertChar(pos2, char1, font1, trackChanges);
2002
2003         cur.checkBufferStructure();
2004
2005         // After the transposition, move cursor to after the transposition.
2006         setCursor(cur, cur.pit(), pos2);
2007         cur.forwardPos();
2008 }
2009
2010
2011 DocIterator Text::macrocontextPosition() const
2012 {
2013         return macrocontext_position_;
2014 }
2015
2016
2017 void Text::setMacrocontextPosition(DocIterator const & pos)
2018 {
2019         macrocontext_position_ = pos;
2020 }
2021
2022
2023 docstring Text::previousWord(CursorSlice const & sl) const
2024 {
2025         CursorSlice from = sl;
2026         CursorSlice to = sl;
2027         getWord(from, to, PREVIOUS_WORD);
2028         if (sl == from || to == from)
2029                 return docstring();
2030         
2031         Paragraph const & par = sl.paragraph();
2032         return par.asString(from.pos(), to.pos());
2033 }
2034
2035
2036 bool Text::completionSupported(Cursor const & cur) const
2037 {
2038         Paragraph const & par = cur.paragraph();
2039         return cur.pos() > 0
2040                 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2041                 && !par.isWordSeparator(cur.pos() - 1);
2042 }
2043
2044
2045 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2046 {
2047         WordList const * list = theWordList(*cur.getFont().language());
2048         return new TextCompletionList(cur, list);
2049 }
2050
2051
2052 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2053 {       
2054         LASSERT(cur.bv().cursor() == cur, /**/);
2055         cur.insert(s);
2056         cur.bv().cursor() = cur;
2057         if (!(cur.result().screenUpdate() & Update::Force))
2058                 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2059         return true;
2060 }
2061         
2062         
2063 docstring Text::completionPrefix(Cursor const & cur) const
2064 {
2065         return previousWord(cur.top());
2066 }
2067
2068 } // namespace lyx