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