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