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