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