]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
8b7457108de3a337874d9f052424b36594cabb8a
[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 "Language.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "LyXRC.h"
41 #include "Paragraph.h"
42 #include "paragraph_funcs.h"
43 #include "ParagraphParameters.h"
44 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48 #include "WordLangTuple.h"
49 #include "WordList.h"
50
51 #include "insets/InsetText.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetCaption.h"
54 #include "insets/InsetLine.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetOptArg.h"
58 #include "insets/InsetSpace.h"
59 #include "insets/InsetSpecialChar.h"
60 #include "insets/InsetTabular.h"
61
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
68
69 #include <boost/next_prior.hpp>
70
71 #include <sstream>
72
73 using namespace std;
74 using namespace lyx::support;
75
76 namespace lyx {
77
78 using cap::cutSelection;
79 using cap::pasteParagraphList;
80
81 namespace {
82
83 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
84         string const & token, Font & font, Change & change, ErrorList & errorList)
85 {
86         BufferParams const & bp = buf.params();
87
88         if (token[0] != '\\') {
89                 docstring dstr = lex.getDocString();
90                 par.appendString(dstr, font, change);
91
92         } else if (token == "\\begin_layout") {
93                 lex.eatLine();
94                 docstring layoutname = lex.getDocString();
95
96                 font = Font(inherit_font, bp.language);
97                 change = Change(Change::UNCHANGED);
98
99                 DocumentClass const & tclass = bp.documentClass();
100
101                 if (layoutname.empty())
102                         layoutname = tclass.defaultLayoutName();
103
104                 if (par.forceEmptyLayout()) {
105                         // in this case only the empty layout is allowed
106                         layoutname = tclass.emptyLayoutName();
107                 } else if (par.useEmptyLayout()) {
108                         // in this case, default layout maps to empty layout 
109                         if (layoutname == tclass.defaultLayoutName())
110                                 layoutname = tclass.emptyLayoutName();
111                 } else { 
112                         // otherwise, the empty layout maps to the default
113                         if (layoutname == tclass.emptyLayoutName())
114                                 layoutname = tclass.defaultLayoutName();
115                 }
116
117                 bool hasLayout = tclass.hasLayout(layoutname);
118
119                 if (!hasLayout) {
120                         errorList.push_back(ErrorItem(_("Unknown layout"),
121                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
122                         layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
123                         layoutname = par.useEmptyLayout() ? 
124                                         tclass.emptyLayoutName() :
125                                         tclass.defaultLayoutName();
126                 }
127
128                 par.setLayout(bp.documentClass()[layoutname]);
129
130                 // Test whether the layout is obsolete.
131                 Layout const & layout = par.layout();
132                 if (!layout.obsoleted_by().empty())
133                         par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
134
135                 par.params().read(lex);
136
137         } else if (token == "\\end_layout") {
138                 LYXERR0("Solitary \\end_layout in line " << lex.getLineNo() << "\n"
139                        << "Missing \\begin_layout ?");
140         } else if (token == "\\end_inset") {
141                 LYXERR0("Solitary \\end_inset in line " << lex.getLineNo() << "\n"
142                        << "Missing \\begin_inset ?");
143         } else if (token == "\\begin_inset") {
144                 Inset * inset = readInset(lex, buf);
145                 if (inset)
146                         par.insertInset(par.size(), inset, font, change);
147                 else {
148                         lex.eatLine();
149                         docstring line = lex.getDocString();
150                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
151                                             par.id(), 0, par.size()));
152                 }
153         } else if (token == "\\family") {
154                 lex.next();
155                 setLyXFamily(lex.getString(), font.fontInfo());
156         } else if (token == "\\series") {
157                 lex.next();
158                 setLyXSeries(lex.getString(), font.fontInfo());
159         } else if (token == "\\shape") {
160                 lex.next();
161                 setLyXShape(lex.getString(), font.fontInfo());
162         } else if (token == "\\size") {
163                 lex.next();
164                 setLyXSize(lex.getString(), font.fontInfo());
165         } else if (token == "\\lang") {
166                 lex.next();
167                 string const tok = lex.getString();
168                 Language const * lang = languages.getLanguage(tok);
169                 if (lang) {
170                         font.setLanguage(lang);
171                 } else {
172                         font.setLanguage(bp.language);
173                         lex.printError("Unknown language `$$Token'");
174                 }
175         } else if (token == "\\numeric") {
176                 lex.next();
177                 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
178         } else if (token == "\\emph") {
179                 lex.next();
180                 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
181         } else if (token == "\\bar") {
182                 lex.next();
183                 string const tok = lex.getString();
184
185                 if (tok == "under")
186                         font.fontInfo().setUnderbar(FONT_ON);
187                 else if (tok == "no")
188                         font.fontInfo().setUnderbar(FONT_OFF);
189                 else if (tok == "default")
190                         font.fontInfo().setUnderbar(FONT_INHERIT);
191                 else
192                         lex.printError("Unknown bar font flag "
193                                        "`$$Token'");
194         } else if (token == "\\noun") {
195                 lex.next();
196                 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
197         } else if (token == "\\color") {
198                 lex.next();
199                 setLyXColor(lex.getString(), font.fontInfo());
200         } else if (token == "\\SpecialChar") {
201                         auto_ptr<Inset> inset;
202                         inset.reset(new InsetSpecialChar);
203                         inset->read(lex);
204                         par.insertInset(par.size(), inset.release(),
205                                         font, change);
206         } else if (token == "\\backslash") {
207                 par.appendChar('\\', font, change);
208         } else if (token == "\\LyXTable") {
209                 auto_ptr<Inset> inset(new InsetTabular(buf));
210                 inset->read(lex);
211                 par.insertInset(par.size(), inset.release(), font, change);
212         } else if (token == "\\lyxline") {
213                 par.insertInset(par.size(), new InsetLine, font, change);
214         } else if (token == "\\change_unchanged") {
215                 change = Change(Change::UNCHANGED);
216         } else if (token == "\\change_inserted") {
217                 lex.eatLine();
218                 istringstream is(lex.getString());
219                 unsigned int aid;
220                 time_t ct;
221                 is >> aid >> ct;
222                 if (aid >= bp.author_map.size()) {
223                         errorList.push_back(ErrorItem(_("Change tracking error"),
224                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
225                                             par.id(), 0, par.size()));
226                         change = Change(Change::UNCHANGED);
227                 } else
228                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
229         } else if (token == "\\change_deleted") {
230                 lex.eatLine();
231                 istringstream is(lex.getString());
232                 unsigned int aid;
233                 time_t ct;
234                 is >> aid >> ct;
235                 if (aid >= bp.author_map.size()) {
236                         errorList.push_back(ErrorItem(_("Change tracking error"),
237                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
238                                             par.id(), 0, par.size()));
239                         change = Change(Change::UNCHANGED);
240                 } else
241                         change = Change(Change::DELETED, bp.author_map[aid], ct);
242         } else {
243                 lex.eatLine();
244                 errorList.push_back(ErrorItem(_("Unknown token"),
245                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
246                         lex.getDocString()),
247                         par.id(), 0, par.size()));
248         }
249 }
250
251
252 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
253         ErrorList & errorList)
254 {
255         lex.nextToken();
256         string token = lex.getString();
257         Font font;
258         Change change(Change::UNCHANGED);
259
260         while (lex.isOK()) {
261                 readParToken(buf, par, lex, token, font, change, errorList);
262
263                 lex.nextToken();
264                 token = lex.getString();
265
266                 if (token.empty())
267                         continue;
268
269                 if (token == "\\end_layout") {
270                         //Ok, paragraph finished
271                         break;
272                 }
273
274                 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
275                 if (token == "\\begin_layout" || token == "\\end_document"
276                     || token == "\\end_inset" || token == "\\begin_deeper"
277                     || token == "\\end_deeper") {
278                         lex.pushToken(token);
279                         lyxerr << "Paragraph ended in line "
280                                << lex.getLineNo() << "\n"
281                                << "Missing \\end_layout.\n";
282                         break;
283                 }
284         }
285         // Final change goes to paragraph break:
286         par.setChange(par.size(), change);
287
288         // Initialize begin_of_body_ on load; redoParagraph maintains
289         par.setBeginOfBody();
290 }
291
292
293 } // namespace anon
294
295 class TextCompletionList : public CompletionList
296 {
297 public:
298         ///
299         TextCompletionList(Cursor const & cur)
300         : buf_(cur.buffer()), pos_(0) {}
301         ///
302         virtual ~TextCompletionList() {}
303         
304         ///
305         virtual bool sorted() const { return true; }
306         ///
307         virtual size_t size() const
308         {
309                 return theWordList().size();
310         }
311         ///
312         virtual docstring const & data(size_t idx) const
313         {
314                 return theWordList().word(idx);
315         }
316         
317 private:
318         ///
319         Buffer const & buf_;
320         ///
321         size_t pos_;
322 };
323
324
325 bool Text::empty() const
326 {
327         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
328                 // FIXME: Should we consider the labeled type as empty too? 
329                 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
330 }
331
332
333 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
334 {
335         if (par.params().spacing().isDefault())
336                 return buffer.params().spacing().getValue();
337         return par.params().spacing().getValue();
338 }
339
340
341 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
342 {
343         BOOST_ASSERT(this == cur.text());
344
345         Paragraph & cpar = cur.paragraph();
346         pit_type cpit = cur.pit();
347
348         DocumentClass const & tclass = cur.buffer().params().documentClass();
349         Layout const & layout = cpar.layout();
350
351         // this is only allowed, if the current paragraph is not empty
352         // or caption and if it has not the keepempty flag active
353         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
354             layout.labeltype != LABEL_SENSITIVE)
355                 return;
356
357         // a layout change may affect also the following paragraph
358         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
359
360         // Always break behind a space
361         // It is better to erase the space (Dekel)
362         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
363                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
364
365         // What should the layout for the new paragraph be?
366         bool keep_layout = inverse_logic ? 
367                 !layout.isEnvironment() 
368                 : layout.isEnvironment();
369
370         // We need to remember this before we break the paragraph, because
371         // that invalidates the layout variable
372         bool sensitive = layout.labeltype == LABEL_SENSITIVE;
373
374         // we need to set this before we insert the paragraph.
375         bool const isempty = cpar.allowEmpty() && cpar.empty();
376
377         lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
378                          cur.pos(), keep_layout);
379
380         // After this, neither paragraph contains any rows!
381
382         cpit = cur.pit();
383         pit_type next_par = cpit + 1;
384
385         // well this is the caption hack since one caption is really enough
386         if (sensitive) {
387                 if (cur.pos() == 0)
388                         // set to standard-layout
389                 //FIXME Check if this should be emptyLayout() in some cases
390                         pars_[cpit].applyLayout(tclass.defaultLayout());
391                 else
392                         // set to standard-layout
393                         //FIXME Check if this should be emptyLayout() in some cases
394                         pars_[next_par].applyLayout(tclass.defaultLayout());
395         }
396
397         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
398                 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
399                         break; // the character couldn't be deleted physically due to change tracking
400         }
401
402         updateLabels(cur.buffer());
403
404         // A singlePar update is not enough in this case.
405         cur.updateFlags(Update::Force);
406
407         // This check is necessary. Otherwise the new empty paragraph will
408         // be deleted automatically. And it is more friendly for the user!
409         if (cur.pos() != 0 || isempty)
410                 setCursor(cur, cur.pit() + 1, 0);
411         else
412                 setCursor(cur, cur.pit(), 0);
413 }
414
415
416 // insert a character, moves all the following breaks in the
417 // same Paragraph one to the right and make a rebreak
418 void Text::insertChar(Cursor & cur, char_type c)
419 {
420         BOOST_ASSERT(this == cur.text());
421
422         cur.recordUndo(INSERT_UNDO);
423
424         TextMetrics const & tm = cur.bv().textMetrics(this);
425         Buffer const & buffer = cur.buffer();
426         Paragraph & par = cur.paragraph();
427         // try to remove this
428         pit_type const pit = cur.pit();
429
430         bool const freeSpacing = par.layout().free_spacing ||
431                 par.isFreeSpacing();
432
433         if (lyxrc.auto_number) {
434                 static docstring const number_operators = from_ascii("+-/*");
435                 static docstring const number_unary_operators = from_ascii("+-");
436                 static docstring const number_seperators = from_ascii(".,:");
437
438                 if (cur.current_font.fontInfo().number() == FONT_ON) {
439                         if (!isDigit(c) && !contains(number_operators, c) &&
440                             !(contains(number_seperators, c) &&
441                               cur.pos() != 0 &&
442                               cur.pos() != cur.lastpos() &&
443                               tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
444                               tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
445                            )
446                                 number(cur); // Set current_font.number to OFF
447                 } else if (isDigit(c) &&
448                            cur.real_current_font.isVisibleRightToLeft()) {
449                         number(cur); // Set current_font.number to ON
450
451                         if (cur.pos() != 0) {
452                                 char_type const c = par.getChar(cur.pos() - 1);
453                                 if (contains(number_unary_operators, c) &&
454                                     (cur.pos() == 1
455                                      || par.isSeparator(cur.pos() - 2)
456                                      || par.isNewline(cur.pos() - 2))
457                                   ) {
458                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
459                                                 tm.font_);
460                                 } else if (contains(number_seperators, c)
461                                      && cur.pos() >= 2
462                                      && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
463                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
464                                                 tm.font_);
465                                 }
466                         }
467                 }
468         }
469
470         // In Bidi text, we want spaces to be treated in a special way: spaces
471         // which are between words in different languages should get the 
472         // paragraph's language; otherwise, spaces should keep the language 
473         // they were originally typed in. This is only in effect while typing;
474         // after the text is already typed in, the user can always go back and
475         // explicitly set the language of a space as desired. But 99.9% of the
476         // time, what we're doing here is what the user actually meant.
477         // 
478         // The following cases are the ones in which the language of the space
479         // should be changed to match that of the containing paragraph. In the
480         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
481         // represents a space, pipe (|) represents the cursor position (so the
482         // character before it is the one just typed in). The different cases
483         // are depicted logically (not visually), from left to right:
484         // 
485         // 1. A_a|
486         // 2. a_A|
487         //
488         // Theoretically, there are other situations that we should, perhaps, deal
489         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
490         // point (to understand why, just try to create this situation...).
491
492         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
493                 // get font in front and behind the space in question. But do NOT 
494                 // use getFont(cur.pos()) because the character c is not inserted yet
495                 Font const pre_space_font  = tm.displayFont(cur.pit(), cur.pos() - 2);
496                 Font const & post_space_font = cur.real_current_font;
497                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
498                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
499                 
500                 if (pre_space_rtl != post_space_rtl) {
501                         // Set the space's language to match the language of the 
502                         // adjacent character whose direction is the paragraph's
503                         // direction; don't touch other properties of the font
504                         Language const * lang = 
505                                 (pre_space_rtl == par.isRTL(buffer.params())) ?
506                                 pre_space_font.language() : post_space_font.language();
507
508                         Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
509                         space_font.setLanguage(lang);
510                         par.setFont(cur.pos() - 1, space_font);
511                 }
512         }
513         
514         // Next check, if there will be two blanks together or a blank at
515         // the beginning of a paragraph.
516         // I decided to handle blanks like normal characters, the main
517         // difference are the special checks when calculating the row.fill
518         // (blank does not count at the end of a row) and the check here
519
520         // When the free-spacing option is set for the current layout,
521         // disable the double-space checking
522         if (!freeSpacing && isLineSeparatorChar(c)) {
523                 if (cur.pos() == 0) {
524                         static bool sent_space_message = false;
525                         if (!sent_space_message) {
526                                 cur.message(_("You cannot insert a space at the "
527                                                            "beginning of a paragraph. Please read the Tutorial."));
528                                 sent_space_message = true;
529                         }
530                         return;
531                 }
532                 BOOST_ASSERT(cur.pos() > 0);
533                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
534                     && !par.isDeleted(cur.pos() - 1)) {
535                         static bool sent_space_message = false;
536                         if (!sent_space_message) {
537                                 cur.message(_("You cannot type two spaces this way. "
538                                                            "Please read the Tutorial."));
539                                 sent_space_message = true;
540                         }
541                         return;
542                 }
543         }
544
545         par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
546         cur.checkBufferStructure();
547
548 //              cur.updateFlags(Update::Force);
549         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
550         charInserted(cur);
551 }
552
553
554 void Text::charInserted(Cursor & cur)
555 {
556         Paragraph & par = cur.paragraph();
557
558         // Here we call finishUndo for every 20 characters inserted.
559         // This is from my experience how emacs does it. (Lgb)
560         static unsigned int counter;
561         if (counter < 20) {
562                 ++counter;
563         } else {
564                 cur.finishUndo();
565                 counter = 0;
566         }
567
568         // register word if a non-letter was entered
569         if (cur.pos() > 1
570             && par.isLetter(cur.pos() - 2)
571             && !par.isLetter(cur.pos() - 1)) {
572                 // get the word in front of cursor
573                 BOOST_ASSERT(this == cur.text());
574                 cur.paragraph().updateWords(cur.top());
575         }
576 }
577
578
579 // the cursor set functions have a special mechanism. When they
580 // realize, that you left an empty paragraph, they will delete it.
581
582 bool Text::cursorForwardOneWord(Cursor & cur)
583 {
584         BOOST_ASSERT(this == cur.text());
585
586         Cursor old = cur;
587
588         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
589                 ++old.pit();
590                 old.pos() = 0;
591         } else {
592                 // Advance through word.
593                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
594                         ++old.pos();
595                 // Skip through trailing nonword stuff.
596                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
597                         ++old.pos();
598         }
599         return setCursor(cur, old.pit(), old.pos());
600 }
601
602
603 bool Text::cursorBackwardOneWord(Cursor & cur)
604 {
605         BOOST_ASSERT(this == cur.text());
606
607         Cursor old = cur;
608
609         if (old.pos() == 0 && old.pit() != 0) {
610                 --old.pit();
611                 old.pos() = old.lastpos();
612         } else {
613                 // Skip through initial nonword stuff.
614                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
615                         --old.pos();
616                 // Advance through word.
617                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
618                         --old.pos();
619         }
620         return setCursor(cur, old.pit(), old.pos());
621 }
622
623
624 void Text::selectWord(Cursor & cur, word_location loc)
625 {
626         BOOST_ASSERT(this == cur.text());
627         CursorSlice from = cur.top();
628         CursorSlice to = cur.top();
629         getWord(from, to, loc);
630         if (cur.top() != from)
631                 setCursor(cur, from.pit(), from.pos());
632         if (to == from)
633                 return;
634         cur.resetAnchor();
635         setCursor(cur, to.pit(), to.pos());
636         cur.setSelection();
637 }
638
639
640 // Select the word currently under the cursor when no
641 // selection is currently set
642 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
643 {
644         BOOST_ASSERT(this == cur.text());
645         if (cur.selection())
646                 return false;
647         selectWord(cur, loc);
648         return cur.selection();
649 }
650
651
652 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
653 {
654         BOOST_ASSERT(this == cur.text());
655
656         if (!cur.selection())
657                 return;
658
659         cur.recordUndoSelection();
660
661         pit_type begPit = cur.selectionBegin().pit();
662         pit_type endPit = cur.selectionEnd().pit();
663
664         pos_type begPos = cur.selectionBegin().pos();
665         pos_type endPos = cur.selectionEnd().pos();
666
667         // keep selection info, because endPos becomes invalid after the first loop
668         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
669
670         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
671
672         for (pit_type pit = begPit; pit <= endPit; ++pit) {
673                 pos_type parSize = pars_[pit].size();
674
675                 // ignore empty paragraphs; otherwise, an assertion will fail for
676                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
677                 if (parSize == 0)
678                         continue;
679
680                 // do not consider first paragraph if the cursor starts at pos size()
681                 if (pit == begPit && begPos == parSize)
682                         continue;
683
684                 // do not consider last paragraph if the cursor ends at pos 0
685                 if (pit == endPit && endPos == 0)
686                         break; // last iteration anyway
687
688                 pos_type left  = (pit == begPit ? begPos : 0);
689                 pos_type right = (pit == endPit ? endPos : parSize);
690
691                 if (op == ACCEPT) {
692                         pars_[pit].acceptChanges(cur.buffer().params(), left, right);
693                 } else {
694                         pars_[pit].rejectChanges(cur.buffer().params(), left, right);
695                 }
696         }
697
698         // next, accept/reject imaginary end-of-par characters
699
700         for (pit_type pit = begPit; pit <= endPit; ++pit) {
701                 pos_type pos = pars_[pit].size();
702
703                 // skip if the selection ends before the end-of-par
704                 if (pit == endPit && endsBeforeEndOfPar)
705                         break; // last iteration anyway
706
707                 // skip if this is not the last paragraph of the document
708                 // note: the user should be able to accept/reject the par break of the last par!
709                 if (pit == endPit && pit + 1 != int(pars_.size()))
710                         break; // last iteration anway
711
712                 if (op == ACCEPT) {
713                         if (pars_[pit].isInserted(pos)) {
714                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
715                         } else if (pars_[pit].isDeleted(pos)) {
716                                 if (pit + 1 == int(pars_.size())) {
717                                         // we cannot remove a par break at the end of the last paragraph;
718                                         // instead, we mark it unchanged
719                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
720                                 } else {
721                                         mergeParagraph(cur.buffer().params(), pars_, pit);
722                                         --endPit;
723                                         --pit;
724                                 }
725                         }
726                 } else {
727                         if (pars_[pit].isDeleted(pos)) {
728                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
729                         } else if (pars_[pit].isInserted(pos)) {
730                                 if (pit + 1 == int(pars_.size())) {
731                                         // we mark the par break at the end of the last paragraph unchanged
732                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
733                                 } else {
734                                         mergeParagraph(cur.buffer().params(), pars_, pit);
735                                         --endPit;
736                                         --pit;
737                                 }
738                         }
739                 }
740         }
741
742         // finally, invoke the DEPM
743
744         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
745
746         //
747
748         cur.finishUndo();
749         cur.clearSelection();
750         setCursorIntern(cur, begPit, begPos);
751         cur.updateFlags(Update::Force);
752         updateLabels(cur.buffer());
753 }
754
755
756 void Text::acceptChanges(BufferParams const & bparams)
757 {
758         lyx::acceptChanges(pars_, bparams);
759         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
760 }
761
762
763 void Text::rejectChanges(BufferParams const & bparams)
764 {
765         pit_type pars_size = static_cast<pit_type>(pars_.size());
766
767         // first, reject changes within each individual paragraph
768         // (do not consider end-of-par)
769         for (pit_type pit = 0; pit < pars_size; ++pit) {
770                 if (!pars_[pit].empty())   // prevent assertion failure
771                         pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
772         }
773
774         // next, reject imaginary end-of-par characters
775         for (pit_type pit = 0; pit < pars_size; ++pit) {
776                 pos_type pos = pars_[pit].size();
777
778                 if (pars_[pit].isDeleted(pos)) {
779                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
780                 } else if (pars_[pit].isInserted(pos)) {
781                         if (pit == pars_size - 1) {
782                                 // we mark the par break at the end of the last
783                                 // paragraph unchanged
784                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
785                         } else {
786                                 mergeParagraph(bparams, pars_, pit);
787                                 --pit;
788                                 --pars_size;
789                         }
790                 }
791         }
792
793         // finally, invoke the DEPM
794         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
795 }
796
797
798 void Text::deleteWordForward(Cursor & cur)
799 {
800         BOOST_ASSERT(this == cur.text());
801         if (cur.lastpos() == 0)
802                 cursorForward(cur);
803         else {
804                 cur.resetAnchor();
805                 cur.selection() = true;
806                 cursorForwardOneWord(cur);
807                 cur.setSelection();
808                 cutSelection(cur, true, false);
809                 cur.checkBufferStructure();
810         }
811 }
812
813
814 void Text::deleteWordBackward(Cursor & cur)
815 {
816         BOOST_ASSERT(this == cur.text());
817         if (cur.lastpos() == 0)
818                 cursorBackward(cur);
819         else {
820                 cur.resetAnchor();
821                 cur.selection() = true;
822                 cursorBackwardOneWord(cur);
823                 cur.setSelection();
824                 cutSelection(cur, true, false);
825                 cur.checkBufferStructure();
826         }
827 }
828
829
830 // Kill to end of line.
831 void Text::changeCase(Cursor & cur, TextCase action)
832 {
833         BOOST_ASSERT(this == cur.text());
834         CursorSlice from;
835         CursorSlice to;
836
837         bool gotsel = false;
838         if (cur.selection()) {
839                 from = cur.selBegin();
840                 to = cur.selEnd();
841                 gotsel = true;
842         } else {
843                 from = cur.top();
844                 getWord(from, to, PARTIAL_WORD);
845                 cursorForwardOneWord(cur);
846         }
847
848         cur.recordUndoSelection();
849
850         pit_type begPit = from.pit();
851         pit_type endPit = to.pit();
852
853         pos_type begPos = from.pos();
854         pos_type endPos = to.pos();
855
856         pos_type right = 0; // needed after the for loop
857
858         for (pit_type pit = begPit; pit <= endPit; ++pit) {
859                 Paragraph & par = pars_[pit];
860                 pos_type const pos = (pit == begPit ? begPos : 0);
861                 right = (pit == endPit ? endPos : par.size());
862                 par.changeCase(cur.buffer().params(), pos, right, action);
863         }
864
865         // the selection may have changed due to logically-only deleted chars
866         if (gotsel) {
867                 setCursor(cur, begPit, begPos);
868                 cur.resetAnchor();
869                 setCursor(cur, endPit, right);
870                 cur.setSelection();
871         } else
872                 setCursor(cur, endPit, right);
873
874         cur.checkBufferStructure();
875 }
876
877
878 bool Text::handleBibitems(Cursor & cur)
879 {
880         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
881                 return false;
882
883         if (cur.pos() != 0)
884                 return false;
885
886         BufferParams const & bufparams = cur.buffer().params();
887         Paragraph const & par = cur.paragraph();
888         Cursor prevcur = cur;
889         if (cur.pit() > 0) {
890                 --prevcur.pit();
891                 prevcur.pos() = prevcur.lastpos();
892         }
893         Paragraph const & prevpar = prevcur.paragraph();
894
895         // if a bibitem is deleted, merge with previous paragraph
896         // if this is a bibliography item as well
897         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
898                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
899                 mergeParagraph(bufparams, cur.text()->paragraphs(),
900                                                         prevcur.pit());
901                 updateLabels(cur.buffer());
902                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
903                 cur.updateFlags(Update::Force);
904                 return true;
905         } 
906
907         // otherwise reset to default
908         cur.paragraph().setEmptyOrDefaultLayout(bufparams.documentClass());
909         return true;
910 }
911
912
913 bool Text::erase(Cursor & cur)
914 {
915         BOOST_ASSERT(this == cur.text());
916         bool needsUpdate = false;
917         Paragraph & par = cur.paragraph();
918
919         if (cur.pos() != cur.lastpos()) {
920                 // this is the code for a normal delete, not pasting
921                 // any paragraphs
922                 cur.recordUndo(DELETE_UNDO);
923                 bool const was_inset = cur.paragraph().isInset(cur.pos());
924                 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges))
925                         // the character has been logically deleted only => skip it
926                         cur.top().forwardPos();
927
928                 if (was_inset)
929                         updateLabels(cur.buffer());
930                 else
931                         cur.checkBufferStructure();
932                 needsUpdate = true;
933         } else {
934                 if (cur.pit() == cur.lastpit())
935                         return dissolveInset(cur);
936
937                 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
938                         par.setChange(cur.pos(), Change(Change::DELETED));
939                         cur.forwardPos();
940                         needsUpdate = true;
941                 } else {
942                         setCursorIntern(cur, cur.pit() + 1, 0);
943                         needsUpdate = backspacePos0(cur);
944                 }
945         }
946
947         needsUpdate |= handleBibitems(cur);
948
949         if (needsUpdate) {
950                 // Make sure the cursor is correct. Is this really needed?
951                 // No, not really... at least not here!
952                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
953                 cur.checkBufferStructure();
954         }
955
956         return needsUpdate;
957 }
958
959
960 bool Text::backspacePos0(Cursor & cur)
961 {
962         BOOST_ASSERT(this == cur.text());
963         if (cur.pit() == 0)
964                 return false;
965
966         bool needsUpdate = false;
967
968         BufferParams const & bufparams = cur.buffer().params();
969         DocumentClass const & tclass = bufparams.documentClass();
970         ParagraphList & plist = cur.text()->paragraphs();
971         Paragraph const & par = cur.paragraph();
972         Cursor prevcur = cur;
973         --prevcur.pit();
974         prevcur.pos() = prevcur.lastpos();
975         Paragraph const & prevpar = prevcur.paragraph();
976
977         // is it an empty paragraph?
978         if (cur.lastpos() == 0
979             || (cur.lastpos() == 1 && par.isSeparator(0))) {
980                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
981                 plist.erase(boost::next(plist.begin(), cur.pit()));
982                 needsUpdate = true;
983         }
984         // is previous par empty?
985         else if (prevcur.lastpos() == 0
986                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
987                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
988                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
989                 needsUpdate = true;
990         }
991         // Pasting is not allowed, if the paragraphs have different
992         // layouts. I think it is a real bug of all other
993         // word processors to allow it. It confuses the user.
994         // Correction: Pasting is always allowed with standard-layout
995         // or the empty layout.
996         else if (par.layout() == prevpar.layout()
997                  || tclass.isDefaultLayout(par.layout())
998                  || tclass.isEmptyLayout(par.layout())) {
999                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1000                 mergeParagraph(bufparams, plist, prevcur.pit());
1001                 needsUpdate = true;
1002         }
1003
1004         if (needsUpdate) {
1005                 updateLabels(cur.buffer());
1006                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1007         }
1008
1009         return needsUpdate;
1010 }
1011
1012
1013 bool Text::backspace(Cursor & cur)
1014 {
1015         BOOST_ASSERT(this == cur.text());
1016         bool needsUpdate = false;
1017         if (cur.pos() == 0) {
1018                 if (cur.pit() == 0)
1019                         return dissolveInset(cur);
1020
1021                 Paragraph & prev_par = pars_[cur.pit() - 1];
1022
1023                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1024                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1025                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1026                         return true;
1027                 }
1028                 // The cursor is at the beginning of a paragraph, so
1029                 // the backspace will collapse two paragraphs into one.
1030                 needsUpdate = backspacePos0(cur);
1031
1032         } else {
1033                 // this is the code for a normal backspace, not pasting
1034                 // any paragraphs
1035                 cur.recordUndo(DELETE_UNDO);
1036                 // We used to do cursorBackwardIntern() here, but it is
1037                 // not a good idea since it triggers the auto-delete
1038                 // mechanism. So we do a cursorBackwardIntern()-lite,
1039                 // without the dreaded mechanism. (JMarc)
1040                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1041                                 false, cur.boundary());
1042                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1043                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1044                 if (was_inset)
1045                         updateLabels(cur.buffer());
1046                 else
1047                         cur.checkBufferStructure();
1048         }
1049
1050         if (cur.pos() == cur.lastpos())
1051                 cur.setCurrentFont();
1052
1053         needsUpdate |= handleBibitems(cur);
1054
1055         // A singlePar update is not enough in this case.
1056 //              cur.updateFlags(Update::Force);
1057         setCursor(cur.top(), cur.pit(), cur.pos());
1058
1059         return needsUpdate;
1060 }
1061
1062
1063 bool Text::dissolveInset(Cursor & cur) {
1064         BOOST_ASSERT(this == cur.text());
1065
1066         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1067                 return false;
1068
1069         cur.recordUndoInset();
1070         cur.mark() = false;
1071         cur.selHandle(false);
1072         // save position
1073         pos_type spos = cur.pos();
1074         pit_type spit = cur.pit();
1075         ParagraphList plist;
1076         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1077                 plist = paragraphs();
1078         cur.popBackward();
1079         // store cursor offset
1080         if (spit == 0)
1081                 spos += cur.pos();
1082         spit += cur.pit();
1083         Buffer & b = cur.buffer();
1084         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1085         if (!plist.empty()) {
1086                 // ERT paragraphs have the Language latex_language.
1087                 // This is invalid outside of ERT, so we need to
1088                 // change it to the buffer language.
1089                 ParagraphList::iterator it = plist.begin();
1090                 ParagraphList::iterator it_end = plist.end();
1091                 for (; it != it_end; it++)
1092                         it->changeLanguage(b.params(), latex_language, b.language());
1093
1094                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1095                                    b.errorList("Paste"));
1096                 // restore position
1097                 cur.pit() = min(cur.lastpit(), spit);
1098                 cur.pos() = min(cur.lastpos(), spos);
1099         }
1100         cur.clearSelection();
1101         cur.resetAnchor();
1102         return true;
1103 }
1104
1105
1106 void Text::getWord(CursorSlice & from, CursorSlice & to,
1107         word_location const loc) const
1108 {
1109         Paragraph const & from_par = pars_[from.pit()];
1110         switch (loc) {
1111         case WHOLE_WORD_STRICT:
1112                 if (from.pos() == 0 || from.pos() == from_par.size()
1113                     || !from_par.isLetter(from.pos())
1114                     || !from_par.isLetter(from.pos() - 1)) {
1115                         to = from;
1116                         return;
1117                 }
1118                 // no break here, we go to the next
1119
1120         case WHOLE_WORD:
1121                 // If we are already at the beginning of a word, do nothing
1122                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1123                         break;
1124                 // no break here, we go to the next
1125
1126         case PREVIOUS_WORD:
1127                 // always move the cursor to the beginning of previous word
1128                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1129                         --from.pos();
1130                 break;
1131         case NEXT_WORD:
1132                 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1133                 break;
1134         case PARTIAL_WORD:
1135                 // no need to move the 'from' cursor
1136                 break;
1137         }
1138         to = from;
1139         Paragraph const & to_par = pars_[to.pit()];
1140         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1141                 ++to.pos();
1142 }
1143
1144
1145 void Text::write(Buffer const & buf, ostream & os) const
1146 {
1147         ParagraphList::const_iterator pit = paragraphs().begin();
1148         ParagraphList::const_iterator end = paragraphs().end();
1149         depth_type dth = 0;
1150         for (; pit != end; ++pit)
1151                 pit->write(os, buf.params(), dth);
1152
1153         // Close begin_deeper
1154         for(; dth > 0; --dth)
1155                 os << "\n\\end_deeper";
1156 }
1157
1158
1159 bool Text::read(Buffer const & buf, Lexer & lex, 
1160                 ErrorList & errorList, InsetText * insetPtr)
1161 {
1162         depth_type depth = 0;
1163
1164         while (lex.isOK()) {
1165                 lex.nextToken();
1166                 string const token = lex.getString();
1167
1168                 if (token.empty())
1169                         continue;
1170
1171                 if (token == "\\end_inset")
1172                         break;
1173
1174                 if (token == "\\end_body")
1175                         continue;
1176
1177                 if (token == "\\begin_body")
1178                         continue;
1179
1180                 if (token == "\\end_document")
1181                         return false;
1182
1183                 if (token == "\\begin_layout") {
1184                         lex.pushToken(token);
1185
1186                         Paragraph par;
1187                         par.params().depth(depth);
1188                         par.setFont(0, Font(inherit_font, buf.params().language));
1189                         par.setInsetOwner(insetPtr);
1190                         pars_.push_back(par);
1191
1192                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1193                         // not BufferParams
1194                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1195
1196                         // register the words in the global word list
1197                         CursorSlice sl = CursorSlice(*insetPtr);
1198                         sl.pit() = pars_.size() - 1;
1199                         pars_.back().updateWords(sl);
1200                 } else if (token == "\\begin_deeper") {
1201                         ++depth;
1202                 } else if (token == "\\end_deeper") {
1203                         if (!depth)
1204                                 lex.printError("\\end_deeper: " "depth is already null");
1205                         else
1206                                 --depth;
1207                 } else {
1208                         LYXERR0("Handling unknown body token: `" << token << '\'');
1209                 }
1210         }
1211         return true;
1212 }
1213
1214 // Returns the current font and depth as a message.
1215 docstring Text::currentState(Cursor & cur)
1216 {
1217         BOOST_ASSERT(this == cur.text());
1218         Buffer & buf = cur.buffer();
1219         Paragraph const & par = cur.paragraph();
1220         odocstringstream os;
1221
1222         if (buf.params().trackChanges)
1223                 os << _("[Change Tracking] ");
1224
1225         Change change = par.lookupChange(cur.pos());
1226
1227         if (change.type != Change::UNCHANGED) {
1228                 Author const & a = buf.params().authors().get(change.author);
1229                 os << _("Change: ") << a.name();
1230                 if (!a.email().empty())
1231                         os << " (" << a.email() << ")";
1232                 // FIXME ctime is english, we should translate that
1233                 os << _(" at ") << ctime(&change.changetime);
1234                 os << " : ";
1235         }
1236
1237         // I think we should only show changes from the default
1238         // font. (Asger)
1239         // No, from the document font (MV)
1240         Font font = cur.real_current_font;
1241         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1242
1243         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1244
1245         // The paragraph depth
1246         int depth = cur.paragraph().getDepth();
1247         if (depth > 0)
1248                 os << bformat(_(", Depth: %1$d"), depth);
1249
1250         // The paragraph spacing, but only if different from
1251         // buffer spacing.
1252         Spacing const & spacing = par.params().spacing();
1253         if (!spacing.isDefault()) {
1254                 os << _(", Spacing: ");
1255                 switch (spacing.getSpace()) {
1256                 case Spacing::Single:
1257                         os << _("Single");
1258                         break;
1259                 case Spacing::Onehalf:
1260                         os << _("OneHalf");
1261                         break;
1262                 case Spacing::Double:
1263                         os << _("Double");
1264                         break;
1265                 case Spacing::Other:
1266                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1267                         break;
1268                 case Spacing::Default:
1269                         // should never happen, do nothing
1270                         break;
1271                 }
1272         }
1273
1274 #ifdef DEVEL_VERSION
1275         os << _(", Inset: ") << &cur.inset();
1276         os << _(", Paragraph: ") << cur.pit();
1277         os << _(", Id: ") << par.id();
1278         os << _(", Position: ") << cur.pos();
1279         // FIXME: Why is the check for par.size() needed?
1280         // We are called with cur.pos() == par.size() quite often.
1281         if (!par.empty() && cur.pos() < par.size()) {
1282                 // Force output of code point, not character
1283                 size_t const c = par.getChar(cur.pos());
1284                 os << _(", Char: 0x") << hex << c;
1285         }
1286         os << _(", Boundary: ") << cur.boundary();
1287 //      Row & row = cur.textRow();
1288 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1289 #endif
1290         return os.str();
1291 }
1292
1293
1294 docstring Text::getPossibleLabel(Cursor & cur) const
1295 {
1296         pit_type pit = cur.pit();
1297
1298         Layout const * layout = &(pars_[pit].layout());
1299
1300         docstring text;
1301         docstring par_text = pars_[pit].asString(false);
1302         string piece;
1303         // the return string of math matrices might contain linebreaks
1304         par_text = subst(par_text, '\n', '-');
1305         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1306                 if (par_text.empty())
1307                         break;
1308                 docstring head;
1309                 par_text = split(par_text, head, ' ');
1310                 // Is it legal to use spaces in labels ?
1311                 if (i > 0)
1312                         text += '-';
1313                 text += head;
1314         }
1315
1316         // No need for a prefix if the user said so.
1317         if (lyxrc.label_init_length <= 0)
1318                 return text;
1319
1320         // Will contain the label type.
1321         docstring name;
1322
1323         // For section, subsection, etc...
1324         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1325                 Layout const * layout2 = &(pars_[pit - 1].layout());
1326                 if (layout2->latextype != LATEX_PARAGRAPH) {
1327                         --pit;
1328                         layout = layout2;
1329                 }
1330         }
1331         if (layout->latextype != LATEX_PARAGRAPH)
1332                 name = from_ascii(layout->latexname());
1333
1334         // for captions, we just take the caption type
1335         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1336         if (caption_inset)
1337                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1338
1339         // If none of the above worked, we'll see if we're inside various
1340         // types of insets and take our abbreviation from them.
1341         if (name.empty()) {
1342                 InsetCode const codes[] = {
1343                         FLOAT_CODE,
1344                         WRAP_CODE,
1345                         FOOT_CODE
1346                 };
1347                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1348                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1349                         if (float_inset) {
1350                                 name = float_inset->name();
1351                                 break;
1352                         }
1353                 }
1354         }
1355
1356         // Create a correct prefix for prettyref
1357         if (name == "theorem")
1358                 name = from_ascii("thm");
1359         else if (name == "Foot")
1360                 name = from_ascii("fn");
1361         else if (name == "listing")
1362                 name = from_ascii("lst");
1363
1364         if (!name.empty())
1365                 text = name.substr(0, 3) + ':' + text;
1366
1367         return text;
1368 }
1369
1370
1371 void Text::charsTranspose(Cursor & cur)
1372 {
1373         BOOST_ASSERT(this == cur.text());
1374
1375         pos_type pos = cur.pos();
1376
1377         // If cursor is at beginning or end of paragraph, do nothing.
1378         if (pos == cur.lastpos() || pos == 0)
1379                 return;
1380
1381         Paragraph & par = cur.paragraph();
1382
1383         // Get the positions of the characters to be transposed.
1384         pos_type pos1 = pos - 1;
1385         pos_type pos2 = pos;
1386
1387         // In change tracking mode, ignore deleted characters.
1388         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1389                 ++pos2;
1390         if (pos2 == cur.lastpos())
1391                 return;
1392
1393         while (pos1 >= 0 && par.isDeleted(pos1))
1394                 --pos1;
1395         if (pos1 < 0)
1396                 return;
1397
1398         // Don't do anything if one of the "characters" is not regular text.
1399         if (par.isInset(pos1) || par.isInset(pos2))
1400                 return;
1401
1402         // Store the characters to be transposed (including font information).
1403         char_type char1 = par.getChar(pos1);
1404         Font const font1 =
1405                 par.getFontSettings(cur.buffer().params(), pos1);
1406
1407         char_type char2 = par.getChar(pos2);
1408         Font const font2 =
1409                 par.getFontSettings(cur.buffer().params(), pos2);
1410
1411         // And finally, we are ready to perform the transposition.
1412         // Track the changes if Change Tracking is enabled.
1413         bool const trackChanges = cur.buffer().params().trackChanges;
1414
1415         cur.recordUndo();
1416
1417         par.eraseChar(pos2, trackChanges);
1418         par.eraseChar(pos1, trackChanges);
1419         par.insertChar(pos1, char2, font2, trackChanges);
1420         par.insertChar(pos2, char1, font1, trackChanges);
1421
1422         cur.checkBufferStructure();
1423
1424         // After the transposition, move cursor to after the transposition.
1425         setCursor(cur, cur.pit(), pos2);
1426         cur.forwardPos();
1427 }
1428
1429
1430 DocIterator Text::macrocontextPosition() const
1431 {
1432         return macrocontext_position_;
1433 }
1434
1435
1436 void Text::setMacrocontextPosition(DocIterator const & pos)
1437 {
1438         macrocontext_position_ = pos;
1439 }
1440
1441
1442 docstring Text::previousWord(CursorSlice const & sl) const
1443 {
1444         CursorSlice from = sl;
1445         CursorSlice to = sl;
1446         getWord(from, to, PREVIOUS_WORD);
1447         if (sl == from || to == from)
1448                 return docstring();
1449         
1450         Paragraph const & par = sl.paragraph();
1451         return par.asString(from.pos(), to.pos(), false);
1452 }
1453
1454
1455 bool Text::completionSupported(Cursor const & cur) const
1456 {
1457         Paragraph const & par = cur.paragraph();
1458         return cur.pos() > 0
1459                 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1460                 && par.isLetter(cur.pos() - 1);
1461 }
1462
1463
1464 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1465 {
1466         return new TextCompletionList(cur);
1467 }
1468
1469
1470 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1471 {       
1472         BOOST_ASSERT(cur.bv().cursor() == cur);
1473         cur.insert(s);
1474         cur.bv().cursor() = cur;
1475         if (!(cur.disp_.update() & Update::Force))
1476                 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1477         return true;
1478 }
1479         
1480         
1481 docstring Text::completionPrefix(Cursor const & cur) const
1482 {
1483         return previousWord(cur.top());
1484 }
1485
1486 } // namespace lyx