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