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