move LyXerr QString specialisation to support/qstring_helpers
[lyx.git] / src / Text.cpp
blob58c2bb0d660c31b668958848124622f25ed1962c
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.
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
16 * Full author contact details are available in file CREDITS.
19 #include <config.h>
21 #include "Text.h"
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 "Language.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "LyXRC.h"
41 #include "Paragraph.h"
42 #include "paragraph_funcs.h"
43 #include "ParagraphParameters.h"
44 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48 #include "WordLangTuple.h"
49 #include "WordList.h"
51 #include "insets/InsetText.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetCaption.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"
62 #include "support/lassert.h"
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"
70 #include <boost/next_prior.hpp>
72 #include <sstream>
74 using namespace std;
75 using namespace lyx::support;
77 namespace lyx {
79 using cap::cutSelection;
80 using cap::pasteParagraphList;
82 namespace {
84 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
85 string const & token, Font & font, Change & change, ErrorList & errorList)
87 BufferParams const & bp = buf.params();
89 if (token[0] != '\\') {
90 docstring dstr = lex.getDocString();
91 par.appendString(dstr, font, change);
93 } else if (token == "\\begin_layout") {
94 lex.eatLine();
95 docstring layoutname = lex.getDocString();
97 font = Font(inherit_font, bp.language);
98 change = Change(Change::UNCHANGED);
100 DocumentClass const & tclass = bp.documentClass();
102 if (layoutname.empty())
103 layoutname = tclass.defaultLayoutName();
105 if (par.forcePlainLayout()) {
106 // in this case only the empty layout is allowed
107 layoutname = tclass.emptyLayoutName();
108 } else if (par.usePlainLayout()) {
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();
118 // When we apply an unknown layout to a document, we add this layout to the textclass
119 // of this document. For example, when you apply class article to a beamer document,
120 // all unknown layouts such as frame will be added to document class article so that
121 // these layouts can keep their original names.
122 tclass.addLayoutIfNeeded(layoutname);
124 par.setLayout(bp.documentClass()[layoutname]);
126 // Test whether the layout is obsolete.
127 Layout const & layout = par.layout();
128 if (!layout.obsoleted_by().empty())
129 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
131 par.params().read(lex);
133 } else if (token == "\\end_layout") {
134 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
135 << "Missing \\begin_layout ?");
136 } else if (token == "\\end_inset") {
137 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
138 << "Missing \\begin_inset ?");
139 } else if (token == "\\begin_inset") {
140 Inset * inset = readInset(lex, buf);
141 if (inset)
142 par.insertInset(par.size(), inset, font, change);
143 else {
144 lex.eatLine();
145 docstring line = lex.getDocString();
146 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
147 par.id(), 0, par.size()));
149 } else if (token == "\\family") {
150 lex.next();
151 setLyXFamily(lex.getString(), font.fontInfo());
152 } else if (token == "\\series") {
153 lex.next();
154 setLyXSeries(lex.getString(), font.fontInfo());
155 } else if (token == "\\shape") {
156 lex.next();
157 setLyXShape(lex.getString(), font.fontInfo());
158 } else if (token == "\\size") {
159 lex.next();
160 setLyXSize(lex.getString(), font.fontInfo());
161 } else if (token == "\\lang") {
162 lex.next();
163 string const tok = lex.getString();
164 Language const * lang = languages.getLanguage(tok);
165 if (lang) {
166 font.setLanguage(lang);
167 } else {
168 font.setLanguage(bp.language);
169 lex.printError("Unknown language `$$Token'");
171 } else if (token == "\\numeric") {
172 lex.next();
173 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
174 } else if (token == "\\emph") {
175 lex.next();
176 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
177 } else if (token == "\\bar") {
178 lex.next();
179 string const tok = lex.getString();
181 if (tok == "under")
182 font.fontInfo().setUnderbar(FONT_ON);
183 else if (tok == "no")
184 font.fontInfo().setUnderbar(FONT_OFF);
185 else if (tok == "default")
186 font.fontInfo().setUnderbar(FONT_INHERIT);
187 else
188 lex.printError("Unknown bar font flag "
189 "`$$Token'");
190 } else if (token == "\\noun") {
191 lex.next();
192 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
193 } else if (token == "\\color") {
194 lex.next();
195 setLyXColor(lex.getString(), font.fontInfo());
196 } else if (token == "\\SpecialChar") {
197 auto_ptr<Inset> inset;
198 inset.reset(new InsetSpecialChar);
199 inset->read(lex);
200 par.insertInset(par.size(), inset.release(),
201 font, change);
202 } else if (token == "\\backslash") {
203 par.appendChar('\\', font, change);
204 } else if (token == "\\LyXTable") {
205 auto_ptr<Inset> inset(new InsetTabular(buf));
206 inset->read(lex);
207 par.insertInset(par.size(), inset.release(), font, change);
208 } else if (token == "\\lyxline") {
209 par.insertInset(par.size(), new InsetLine, font, change);
210 } else if (token == "\\change_unchanged") {
211 change = Change(Change::UNCHANGED);
212 } else if (token == "\\change_inserted") {
213 lex.eatLine();
214 istringstream is(lex.getString());
215 unsigned int aid;
216 time_t ct;
217 is >> aid >> ct;
218 if (aid >= bp.author_map.size()) {
219 errorList.push_back(ErrorItem(_("Change tracking error"),
220 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
221 par.id(), 0, par.size()));
222 change = Change(Change::UNCHANGED);
223 } else
224 change = Change(Change::INSERTED, bp.author_map[aid], ct);
225 } else if (token == "\\change_deleted") {
226 lex.eatLine();
227 istringstream is(lex.getString());
228 unsigned int aid;
229 time_t ct;
230 is >> aid >> ct;
231 if (aid >= bp.author_map.size()) {
232 errorList.push_back(ErrorItem(_("Change tracking error"),
233 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
234 par.id(), 0, par.size()));
235 change = Change(Change::UNCHANGED);
236 } else
237 change = Change(Change::DELETED, bp.author_map[aid], ct);
238 } else {
239 lex.eatLine();
240 errorList.push_back(ErrorItem(_("Unknown token"),
241 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
242 lex.getDocString()),
243 par.id(), 0, par.size()));
248 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
249 ErrorList & errorList)
251 lex.nextToken();
252 string token = lex.getString();
253 Font font;
254 Change change(Change::UNCHANGED);
256 while (lex.isOK()) {
257 readParToken(buf, par, lex, token, font, change, errorList);
259 lex.nextToken();
260 token = lex.getString();
262 if (token.empty())
263 continue;
265 if (token == "\\end_layout") {
266 //Ok, paragraph finished
267 break;
270 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
271 if (token == "\\begin_layout" || token == "\\end_document"
272 || token == "\\end_inset" || token == "\\begin_deeper"
273 || token == "\\end_deeper") {
274 lex.pushToken(token);
275 lyxerr << "Paragraph ended in line "
276 << lex.lineNumber() << "\n"
277 << "Missing \\end_layout.\n";
278 break;
281 // Final change goes to paragraph break:
282 par.setChange(par.size(), change);
284 // Initialize begin_of_body_ on load; redoParagraph maintains
285 par.setBeginOfBody();
289 } // namespace anon
291 class TextCompletionList : public CompletionList
293 public:
295 TextCompletionList(Cursor const & cur)
296 : buf_(cur.buffer()), pos_(0) {}
298 virtual ~TextCompletionList() {}
301 virtual bool sorted() const { return true; }
303 virtual size_t size() const
305 return theWordList().size();
308 virtual docstring const & data(size_t idx) const
310 return theWordList().word(idx);
313 private:
315 Buffer const & buf_;
317 size_t pos_;
321 bool Text::empty() const
323 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
324 // FIXME: Should we consider the labeled type as empty too?
325 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
329 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
331 if (par.params().spacing().isDefault())
332 return buffer.params().spacing().getValue();
333 return par.params().spacing().getValue();
337 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
339 LASSERT(this == cur.text(), /**/);
341 Paragraph & cpar = cur.paragraph();
342 pit_type cpit = cur.pit();
344 DocumentClass const & tclass = cur.buffer().params().documentClass();
345 Layout const & layout = cpar.layout();
347 // this is only allowed, if the current paragraph is not empty
348 // or caption and if it has not the keepempty flag active
349 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
350 layout.labeltype != LABEL_SENSITIVE)
351 return;
353 // a layout change may affect also the following paragraph
354 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
356 // Always break behind a space
357 // It is better to erase the space (Dekel)
358 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
359 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
361 // What should the layout for the new paragraph be?
362 bool keep_layout = inverse_logic ?
363 !layout.isEnvironment()
364 : layout.isEnvironment();
366 // We need to remember this before we break the paragraph, because
367 // that invalidates the layout variable
368 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
370 // we need to set this before we insert the paragraph.
371 bool const isempty = cpar.allowEmpty() && cpar.empty();
373 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
374 cur.pos(), keep_layout);
376 // After this, neither paragraph contains any rows!
378 cpit = cur.pit();
379 pit_type next_par = cpit + 1;
381 // well this is the caption hack since one caption is really enough
382 if (sensitive) {
383 if (cur.pos() == 0)
384 // set to standard-layout
385 //FIXME Check if this should be emptyLayout() in some cases
386 pars_[cpit].applyLayout(tclass.defaultLayout());
387 else
388 // set to standard-layout
389 //FIXME Check if this should be emptyLayout() in some cases
390 pars_[next_par].applyLayout(tclass.defaultLayout());
393 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
394 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
395 break; // the character couldn't be deleted physically due to change tracking
398 updateLabels(cur.buffer());
400 // A singlePar update is not enough in this case.
401 cur.updateFlags(Update::Force);
403 // This check is necessary. Otherwise the new empty paragraph will
404 // be deleted automatically. And it is more friendly for the user!
405 if (cur.pos() != 0 || isempty)
406 setCursor(cur, cur.pit() + 1, 0);
407 else
408 setCursor(cur, cur.pit(), 0);
412 // insert a character, moves all the following breaks in the
413 // same Paragraph one to the right and make a rebreak
414 void Text::insertChar(Cursor & cur, char_type c)
416 LASSERT(this == cur.text(), /**/);
418 cur.recordUndo(INSERT_UNDO);
420 TextMetrics const & tm = cur.bv().textMetrics(this);
421 Buffer const & buffer = cur.buffer();
422 Paragraph & par = cur.paragraph();
423 // try to remove this
424 pit_type const pit = cur.pit();
426 bool const freeSpacing = par.layout().free_spacing ||
427 par.isFreeSpacing();
429 if (lyxrc.auto_number) {
430 static docstring const number_operators = from_ascii("+-/*");
431 static docstring const number_unary_operators = from_ascii("+-");
432 static docstring const number_seperators = from_ascii(".,:");
434 if (cur.current_font.fontInfo().number() == FONT_ON) {
435 if (!isDigit(c) && !contains(number_operators, c) &&
436 !(contains(number_seperators, c) &&
437 cur.pos() != 0 &&
438 cur.pos() != cur.lastpos() &&
439 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
440 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
442 number(cur); // Set current_font.number to OFF
443 } else if (isDigit(c) &&
444 cur.real_current_font.isVisibleRightToLeft()) {
445 number(cur); // Set current_font.number to ON
447 if (cur.pos() != 0) {
448 char_type const c = par.getChar(cur.pos() - 1);
449 if (contains(number_unary_operators, c) &&
450 (cur.pos() == 1
451 || par.isSeparator(cur.pos() - 2)
452 || par.isNewline(cur.pos() - 2))
454 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
455 tm.font_);
456 } else if (contains(number_seperators, c)
457 && cur.pos() >= 2
458 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
459 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
460 tm.font_);
466 // In Bidi text, we want spaces to be treated in a special way: spaces
467 // which are between words in different languages should get the
468 // paragraph's language; otherwise, spaces should keep the language
469 // they were originally typed in. This is only in effect while typing;
470 // after the text is already typed in, the user can always go back and
471 // explicitly set the language of a space as desired. But 99.9% of the
472 // time, what we're doing here is what the user actually meant.
474 // The following cases are the ones in which the language of the space
475 // should be changed to match that of the containing paragraph. In the
476 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
477 // represents a space, pipe (|) represents the cursor position (so the
478 // character before it is the one just typed in). The different cases
479 // are depicted logically (not visually), from left to right:
481 // 1. A_a|
482 // 2. a_A|
484 // Theoretically, there are other situations that we should, perhaps, deal
485 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
486 // point (to understand why, just try to create this situation...).
488 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
489 // get font in front and behind the space in question. But do NOT
490 // use getFont(cur.pos()) because the character c is not inserted yet
491 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
492 Font const & post_space_font = cur.real_current_font;
493 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
494 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
496 if (pre_space_rtl != post_space_rtl) {
497 // Set the space's language to match the language of the
498 // adjacent character whose direction is the paragraph's
499 // direction; don't touch other properties of the font
500 Language const * lang =
501 (pre_space_rtl == par.isRTL(buffer.params())) ?
502 pre_space_font.language() : post_space_font.language();
504 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
505 space_font.setLanguage(lang);
506 par.setFont(cur.pos() - 1, space_font);
510 // Next check, if there will be two blanks together or a blank at
511 // the beginning of a paragraph.
512 // I decided to handle blanks like normal characters, the main
513 // difference are the special checks when calculating the row.fill
514 // (blank does not count at the end of a row) and the check here
516 // When the free-spacing option is set for the current layout,
517 // disable the double-space checking
518 if (!freeSpacing && isLineSeparatorChar(c)) {
519 if (cur.pos() == 0) {
520 static bool sent_space_message = false;
521 if (!sent_space_message) {
522 cur.message(_("You cannot insert a space at the "
523 "beginning of a paragraph. Please read the Tutorial."));
524 sent_space_message = true;
526 return;
528 LASSERT(cur.pos() > 0, /**/);
529 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
530 && !par.isDeleted(cur.pos() - 1)) {
531 static bool sent_space_message = false;
532 if (!sent_space_message) {
533 cur.message(_("You cannot type two spaces this way. "
534 "Please read the Tutorial."));
535 sent_space_message = true;
537 return;
541 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
542 cur.checkBufferStructure();
544 // cur.updateFlags(Update::Force);
545 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
546 charInserted(cur);
550 void Text::charInserted(Cursor & cur)
552 Paragraph & par = cur.paragraph();
554 // Here we call finishUndo for every 20 characters inserted.
555 // This is from my experience how emacs does it. (Lgb)
556 static unsigned int counter;
557 if (counter < 20) {
558 ++counter;
559 } else {
560 cur.finishUndo();
561 counter = 0;
564 // register word if a non-letter was entered
565 if (cur.pos() > 1
566 && par.isLetter(cur.pos() - 2)
567 && !par.isLetter(cur.pos() - 1)) {
568 // get the word in front of cursor
569 LASSERT(this == cur.text(), /**/);
570 cur.paragraph().updateWords(cur.top());
575 // the cursor set functions have a special mechanism. When they
576 // realize, that you left an empty paragraph, they will delete it.
578 bool Text::cursorForwardOneWord(Cursor & cur)
580 LASSERT(this == cur.text(), /**/);
582 pos_type const lastpos = cur.lastpos();
583 pit_type pit = cur.pit();
584 pos_type pos = cur.pos();
585 Paragraph const & par = cur.paragraph();
587 // Paragraph boundary is a word boundary
588 if (pos == lastpos) {
589 if (pit != cur.lastpit())
590 return setCursor(cur, pit + 1, 0);
591 else
592 return false;
595 if (lyxrc.mac_like_word_movement) {
596 // Skip through trailing punctuation and spaces.
597 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
598 ++pos;
600 // Skip over either a non-char inset or a full word
601 if (pos != lastpos && !par.isLetter(pos))
602 ++pos;
603 else while (pos != lastpos && par.isLetter(pos))
604 ++pos;
605 } else {
606 LASSERT(pos < lastpos, /**/); // see above
607 if (par.isLetter(pos))
608 while (pos != lastpos && par.isLetter(pos))
609 ++pos;
610 else if (par.isChar(pos))
611 while (pos != lastpos && par.isChar(pos))
612 ++pos;
613 else if (!par.isSpace(pos)) // non-char inset
614 ++pos;
616 // Skip over white space
617 while (pos != lastpos && par.isSpace(pos))
618 ++pos;
621 return setCursor(cur, pit, pos);
625 bool Text::cursorBackwardOneWord(Cursor & cur)
627 LASSERT(this == cur.text(), /**/);
629 pit_type pit = cur.pit();
630 pos_type pos = cur.pos();
631 Paragraph & par = cur.paragraph();
633 // Paragraph boundary is a word boundary
634 if (pos == 0 && pit != 0)
635 return setCursor(cur, pit - 1, getPar(pit - 1).size());
637 if (lyxrc.mac_like_word_movement) {
638 // Skip through punctuation and spaces.
639 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
640 --pos;
642 // Skip over either a non-char inset or a full word
643 if (pos != 0 && !par.isLetter(pos - 1) && !par.isChar(pos - 1))
644 --pos;
645 else while (pos != 0 && par.isLetter(pos - 1))
646 --pos;
647 } else {
648 // Skip over white space
649 while (pos != 0 && par.isSpace(pos - 1))
650 --pos;
652 if (pos != 0 && par.isLetter(pos - 1))
653 while (pos != 0 && par.isLetter(pos - 1))
654 --pos;
655 else if (pos != 0 && par.isChar(pos - 1))
656 while (pos != 0 && par.isChar(pos - 1))
657 --pos;
658 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
659 --pos;
662 return setCursor(cur, pit, pos);
666 bool Text::cursorVisLeftOneWord(Cursor & cur)
668 LASSERT(this == cur.text(), /**/);
670 pos_type left_pos, right_pos;
671 bool left_is_letter, right_is_letter;
673 Cursor temp_cur = cur;
675 // always try to move at least once...
676 while (temp_cur.posVisLeft(true /* skip_inset */)) {
678 // collect some information about current cursor position
679 temp_cur.getSurroundingPos(left_pos, right_pos);
680 left_is_letter =
681 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
682 right_is_letter =
683 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
685 // if we're not at a letter/non-letter boundary, continue moving
686 if (left_is_letter == right_is_letter)
687 continue;
689 // we should stop when we have an LTR word on our right or an RTL word
690 // on our left
691 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
692 temp_cur.bv().buffer().params(),
693 left_pos).isRightToLeft())
694 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
695 temp_cur.bv().buffer().params(),
696 right_pos).isRightToLeft()))
697 break;
700 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
701 true, temp_cur.boundary());
705 bool Text::cursorVisRightOneWord(Cursor & cur)
707 LASSERT(this == cur.text(), /**/);
709 pos_type left_pos, right_pos;
710 bool left_is_letter, right_is_letter;
712 Cursor temp_cur = cur;
714 // always try to move at least once...
715 while (temp_cur.posVisRight(true /* skip_inset */)) {
717 // collect some information about current cursor position
718 temp_cur.getSurroundingPos(left_pos, right_pos);
719 left_is_letter =
720 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
721 right_is_letter =
722 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
724 // if we're not at a letter/non-letter boundary, continue moving
725 if (left_is_letter == right_is_letter)
726 continue;
728 // we should stop when we have an LTR word on our right or an RTL word
729 // on our left
730 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
731 temp_cur.bv().buffer().params(),
732 left_pos).isRightToLeft())
733 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
734 temp_cur.bv().buffer().params(),
735 right_pos).isRightToLeft()))
736 break;
739 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
740 true, temp_cur.boundary());
744 void Text::selectWord(Cursor & cur, word_location loc)
746 LASSERT(this == cur.text(), /**/);
747 CursorSlice from = cur.top();
748 CursorSlice to = cur.top();
749 getWord(from, to, loc);
750 if (cur.top() != from)
751 setCursor(cur, from.pit(), from.pos());
752 if (to == from)
753 return;
754 cur.resetAnchor();
755 setCursor(cur, to.pit(), to.pos());
756 cur.setSelection();
760 // Select the word currently under the cursor when no
761 // selection is currently set
762 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
764 LASSERT(this == cur.text(), /**/);
765 if (cur.selection())
766 return false;
767 selectWord(cur, loc);
768 return cur.selection();
772 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
774 LASSERT(this == cur.text(), /**/);
776 if (!cur.selection())
777 return;
779 cur.recordUndoSelection();
781 pit_type begPit = cur.selectionBegin().pit();
782 pit_type endPit = cur.selectionEnd().pit();
784 pos_type begPos = cur.selectionBegin().pos();
785 pos_type endPos = cur.selectionEnd().pos();
787 // keep selection info, because endPos becomes invalid after the first loop
788 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
790 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
792 for (pit_type pit = begPit; pit <= endPit; ++pit) {
793 pos_type parSize = pars_[pit].size();
795 // ignore empty paragraphs; otherwise, an assertion will fail for
796 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
797 if (parSize == 0)
798 continue;
800 // do not consider first paragraph if the cursor starts at pos size()
801 if (pit == begPit && begPos == parSize)
802 continue;
804 // do not consider last paragraph if the cursor ends at pos 0
805 if (pit == endPit && endPos == 0)
806 break; // last iteration anyway
808 pos_type left = (pit == begPit ? begPos : 0);
809 pos_type right = (pit == endPit ? endPos : parSize);
811 if (op == ACCEPT) {
812 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
813 } else {
814 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
818 // next, accept/reject imaginary end-of-par characters
820 for (pit_type pit = begPit; pit <= endPit; ++pit) {
821 pos_type pos = pars_[pit].size();
823 // skip if the selection ends before the end-of-par
824 if (pit == endPit && endsBeforeEndOfPar)
825 break; // last iteration anyway
827 // skip if this is not the last paragraph of the document
828 // note: the user should be able to accept/reject the par break of the last par!
829 if (pit == endPit && pit + 1 != int(pars_.size()))
830 break; // last iteration anway
832 if (op == ACCEPT) {
833 if (pars_[pit].isInserted(pos)) {
834 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
835 } else if (pars_[pit].isDeleted(pos)) {
836 if (pit + 1 == int(pars_.size())) {
837 // we cannot remove a par break at the end of the last paragraph;
838 // instead, we mark it unchanged
839 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
840 } else {
841 mergeParagraph(cur.buffer().params(), pars_, pit);
842 --endPit;
843 --pit;
846 } else {
847 if (pars_[pit].isDeleted(pos)) {
848 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
849 } else if (pars_[pit].isInserted(pos)) {
850 if (pit + 1 == int(pars_.size())) {
851 // we mark the par break at the end of the last paragraph unchanged
852 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
853 } else {
854 mergeParagraph(cur.buffer().params(), pars_, pit);
855 --endPit;
856 --pit;
862 // finally, invoke the DEPM
864 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
868 cur.finishUndo();
869 cur.clearSelection();
870 setCursorIntern(cur, begPit, begPos);
871 cur.updateFlags(Update::Force);
872 updateLabels(cur.buffer());
876 void Text::acceptChanges(BufferParams const & bparams)
878 lyx::acceptChanges(pars_, bparams);
879 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
883 void Text::rejectChanges(BufferParams const & bparams)
885 pit_type pars_size = static_cast<pit_type>(pars_.size());
887 // first, reject changes within each individual paragraph
888 // (do not consider end-of-par)
889 for (pit_type pit = 0; pit < pars_size; ++pit) {
890 if (!pars_[pit].empty()) // prevent assertion failure
891 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
894 // next, reject imaginary end-of-par characters
895 for (pit_type pit = 0; pit < pars_size; ++pit) {
896 pos_type pos = pars_[pit].size();
898 if (pars_[pit].isDeleted(pos)) {
899 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
900 } else if (pars_[pit].isInserted(pos)) {
901 if (pit == pars_size - 1) {
902 // we mark the par break at the end of the last
903 // paragraph unchanged
904 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
905 } else {
906 mergeParagraph(bparams, pars_, pit);
907 --pit;
908 --pars_size;
913 // finally, invoke the DEPM
914 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
918 void Text::deleteWordForward(Cursor & cur)
920 LASSERT(this == cur.text(), /**/);
921 if (cur.lastpos() == 0)
922 cursorForward(cur);
923 else {
924 cur.resetAnchor();
925 cur.selection() = true;
926 cursorForwardOneWord(cur);
927 cur.setSelection();
928 cutSelection(cur, true, false);
929 cur.checkBufferStructure();
934 void Text::deleteWordBackward(Cursor & cur)
936 LASSERT(this == cur.text(), /**/);
937 if (cur.lastpos() == 0)
938 cursorBackward(cur);
939 else {
940 cur.resetAnchor();
941 cur.selection() = true;
942 cursorBackwardOneWord(cur);
943 cur.setSelection();
944 cutSelection(cur, true, false);
945 cur.checkBufferStructure();
950 // Kill to end of line.
951 void Text::changeCase(Cursor & cur, TextCase action)
953 LASSERT(this == cur.text(), /**/);
954 CursorSlice from;
955 CursorSlice to;
957 bool gotsel = false;
958 if (cur.selection()) {
959 from = cur.selBegin();
960 to = cur.selEnd();
961 gotsel = true;
962 } else {
963 from = cur.top();
964 getWord(from, to, PARTIAL_WORD);
965 cursorForwardOneWord(cur);
968 cur.recordUndoSelection();
970 pit_type begPit = from.pit();
971 pit_type endPit = to.pit();
973 pos_type begPos = from.pos();
974 pos_type endPos = to.pos();
976 pos_type right = 0; // needed after the for loop
978 for (pit_type pit = begPit; pit <= endPit; ++pit) {
979 Paragraph & par = pars_[pit];
980 pos_type const pos = (pit == begPit ? begPos : 0);
981 right = (pit == endPit ? endPos : par.size());
982 par.changeCase(cur.buffer().params(), pos, right, action);
985 // the selection may have changed due to logically-only deleted chars
986 if (gotsel) {
987 setCursor(cur, begPit, begPos);
988 cur.resetAnchor();
989 setCursor(cur, endPit, right);
990 cur.setSelection();
991 } else
992 setCursor(cur, endPit, right);
994 cur.checkBufferStructure();
998 bool Text::handleBibitems(Cursor & cur)
1000 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1001 return false;
1003 if (cur.pos() != 0)
1004 return false;
1006 BufferParams const & bufparams = cur.buffer().params();
1007 Paragraph const & par = cur.paragraph();
1008 Cursor prevcur = cur;
1009 if (cur.pit() > 0) {
1010 --prevcur.pit();
1011 prevcur.pos() = prevcur.lastpos();
1013 Paragraph const & prevpar = prevcur.paragraph();
1015 // if a bibitem is deleted, merge with previous paragraph
1016 // if this is a bibliography item as well
1017 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1018 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1019 mergeParagraph(bufparams, cur.text()->paragraphs(),
1020 prevcur.pit());
1021 updateLabels(cur.buffer());
1022 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1023 cur.updateFlags(Update::Force);
1024 return true;
1027 // otherwise reset to default
1028 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1029 return true;
1033 bool Text::erase(Cursor & cur)
1035 LASSERT(this == cur.text(), /**/);
1036 bool needsUpdate = false;
1037 Paragraph & par = cur.paragraph();
1039 if (cur.pos() != cur.lastpos()) {
1040 // this is the code for a normal delete, not pasting
1041 // any paragraphs
1042 cur.recordUndo(DELETE_UNDO);
1043 bool const was_inset = cur.paragraph().isInset(cur.pos());
1044 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges))
1045 // the character has been logically deleted only => skip it
1046 cur.top().forwardPos();
1048 if (was_inset)
1049 updateLabels(cur.buffer());
1050 else
1051 cur.checkBufferStructure();
1052 needsUpdate = true;
1053 } else {
1054 if (cur.pit() == cur.lastpit())
1055 return dissolveInset(cur);
1057 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1058 par.setChange(cur.pos(), Change(Change::DELETED));
1059 cur.forwardPos();
1060 needsUpdate = true;
1061 } else {
1062 setCursorIntern(cur, cur.pit() + 1, 0);
1063 needsUpdate = backspacePos0(cur);
1067 needsUpdate |= handleBibitems(cur);
1069 if (needsUpdate) {
1070 // Make sure the cursor is correct. Is this really needed?
1071 // No, not really... at least not here!
1072 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1073 cur.checkBufferStructure();
1076 return needsUpdate;
1080 bool Text::backspacePos0(Cursor & cur)
1082 LASSERT(this == cur.text(), /**/);
1083 if (cur.pit() == 0)
1084 return false;
1086 bool needsUpdate = false;
1088 BufferParams const & bufparams = cur.buffer().params();
1089 DocumentClass const & tclass = bufparams.documentClass();
1090 ParagraphList & plist = cur.text()->paragraphs();
1091 Paragraph const & par = cur.paragraph();
1092 Cursor prevcur = cur;
1093 --prevcur.pit();
1094 prevcur.pos() = prevcur.lastpos();
1095 Paragraph const & prevpar = prevcur.paragraph();
1097 // is it an empty paragraph?
1098 if (cur.lastpos() == 0
1099 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1100 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1101 plist.erase(boost::next(plist.begin(), cur.pit()));
1102 needsUpdate = true;
1104 // is previous par empty?
1105 else if (prevcur.lastpos() == 0
1106 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1107 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1108 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1109 needsUpdate = true;
1111 // Pasting is not allowed, if the paragraphs have different
1112 // layouts. I think it is a real bug of all other
1113 // word processors to allow it. It confuses the user.
1114 // Correction: Pasting is always allowed with standard-layout
1115 // or the empty layout.
1116 else if (par.layout() == prevpar.layout()
1117 || tclass.isDefaultLayout(par.layout())
1118 || tclass.isPlainLayout(par.layout())) {
1119 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1120 mergeParagraph(bufparams, plist, prevcur.pit());
1121 needsUpdate = true;
1124 if (needsUpdate) {
1125 updateLabels(cur.buffer());
1126 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1129 return needsUpdate;
1133 bool Text::backspace(Cursor & cur)
1135 LASSERT(this == cur.text(), /**/);
1136 bool needsUpdate = false;
1137 if (cur.pos() == 0) {
1138 if (cur.pit() == 0)
1139 return dissolveInset(cur);
1141 Paragraph & prev_par = pars_[cur.pit() - 1];
1143 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1144 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1145 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1146 return true;
1148 // The cursor is at the beginning of a paragraph, so
1149 // the backspace will collapse two paragraphs into one.
1150 needsUpdate = backspacePos0(cur);
1152 } else {
1153 // this is the code for a normal backspace, not pasting
1154 // any paragraphs
1155 cur.recordUndo(DELETE_UNDO);
1156 // We used to do cursorBackwardIntern() here, but it is
1157 // not a good idea since it triggers the auto-delete
1158 // mechanism. So we do a cursorBackwardIntern()-lite,
1159 // without the dreaded mechanism. (JMarc)
1160 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1161 false, cur.boundary());
1162 bool const was_inset = cur.paragraph().isInset(cur.pos());
1163 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1164 if (was_inset)
1165 updateLabels(cur.buffer());
1166 else
1167 cur.checkBufferStructure();
1170 if (cur.pos() == cur.lastpos())
1171 cur.setCurrentFont();
1173 needsUpdate |= handleBibitems(cur);
1175 // A singlePar update is not enough in this case.
1176 // cur.updateFlags(Update::Force);
1177 setCursor(cur.top(), cur.pit(), cur.pos());
1179 return needsUpdate;
1183 bool Text::dissolveInset(Cursor & cur) {
1184 LASSERT(this == cur.text(), /**/);
1186 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1187 return false;
1189 cur.recordUndoInset();
1190 cur.mark() = false;
1191 cur.selHandle(false);
1192 // save position
1193 pos_type spos = cur.pos();
1194 pit_type spit = cur.pit();
1195 ParagraphList plist;
1196 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1197 plist = paragraphs();
1198 cur.popBackward();
1199 // store cursor offset
1200 if (spit == 0)
1201 spos += cur.pos();
1202 spit += cur.pit();
1203 Buffer & b = cur.buffer();
1204 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1205 if (!plist.empty()) {
1206 // ERT paragraphs have the Language latex_language.
1207 // This is invalid outside of ERT, so we need to
1208 // change it to the buffer language.
1209 ParagraphList::iterator it = plist.begin();
1210 ParagraphList::iterator it_end = plist.end();
1211 for (; it != it_end; it++)
1212 it->changeLanguage(b.params(), latex_language, b.language());
1214 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1215 b.errorList("Paste"));
1216 // restore position
1217 cur.pit() = min(cur.lastpit(), spit);
1218 cur.pos() = min(cur.lastpos(), spos);
1220 cur.clearSelection();
1221 cur.resetAnchor();
1222 return true;
1226 void Text::getWord(CursorSlice & from, CursorSlice & to,
1227 word_location const loc) const
1229 Paragraph const & from_par = pars_[from.pit()];
1230 switch (loc) {
1231 case WHOLE_WORD_STRICT:
1232 if (from.pos() == 0 || from.pos() == from_par.size()
1233 || !from_par.isLetter(from.pos())
1234 || !from_par.isLetter(from.pos() - 1)) {
1235 to = from;
1236 return;
1238 // no break here, we go to the next
1240 case WHOLE_WORD:
1241 // If we are already at the beginning of a word, do nothing
1242 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1243 break;
1244 // no break here, we go to the next
1246 case PREVIOUS_WORD:
1247 // always move the cursor to the beginning of previous word
1248 while (from.pos() && from_par.isLetter(from.pos() - 1))
1249 --from.pos();
1250 break;
1251 case NEXT_WORD:
1252 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1253 break;
1254 case PARTIAL_WORD:
1255 // no need to move the 'from' cursor
1256 break;
1258 to = from;
1259 Paragraph const & to_par = pars_[to.pit()];
1260 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1261 ++to.pos();
1265 void Text::write(Buffer const & buf, ostream & os) const
1267 ParagraphList::const_iterator pit = paragraphs().begin();
1268 ParagraphList::const_iterator end = paragraphs().end();
1269 depth_type dth = 0;
1270 for (; pit != end; ++pit)
1271 pit->write(os, buf.params(), dth);
1273 // Close begin_deeper
1274 for(; dth > 0; --dth)
1275 os << "\n\\end_deeper";
1279 bool Text::read(Buffer const & buf, Lexer & lex,
1280 ErrorList & errorList, InsetText * insetPtr)
1282 depth_type depth = 0;
1284 while (lex.isOK()) {
1285 lex.nextToken();
1286 string const token = lex.getString();
1288 if (token.empty())
1289 continue;
1291 if (token == "\\end_inset")
1292 break;
1294 if (token == "\\end_body")
1295 continue;
1297 if (token == "\\begin_body")
1298 continue;
1300 if (token == "\\end_document")
1301 return false;
1303 if (token == "\\begin_layout") {
1304 lex.pushToken(token);
1306 Paragraph par;
1307 par.params().depth(depth);
1308 par.setFont(0, Font(inherit_font, buf.params().language));
1309 par.setInsetOwner(insetPtr);
1310 pars_.push_back(par);
1312 // FIXME: goddamn InsetTabular makes us pass a Buffer
1313 // not BufferParams
1314 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1316 // register the words in the global word list
1317 CursorSlice sl = CursorSlice(*insetPtr);
1318 sl.pit() = pars_.size() - 1;
1319 pars_.back().updateWords(sl);
1320 } else if (token == "\\begin_deeper") {
1321 ++depth;
1322 } else if (token == "\\end_deeper") {
1323 if (!depth)
1324 lex.printError("\\end_deeper: " "depth is already null");
1325 else
1326 --depth;
1327 } else {
1328 LYXERR0("Handling unknown body token: `" << token << '\'');
1331 return true;
1334 // Returns the current font and depth as a message.
1335 docstring Text::currentState(Cursor & cur)
1337 LASSERT(this == cur.text(), /**/);
1338 Buffer & buf = cur.buffer();
1339 Paragraph const & par = cur.paragraph();
1340 odocstringstream os;
1342 if (buf.params().trackChanges)
1343 os << _("[Change Tracking] ");
1345 Change change = par.lookupChange(cur.pos());
1347 if (change.type != Change::UNCHANGED) {
1348 Author const & a = buf.params().authors().get(change.author);
1349 os << _("Change: ") << a.name();
1350 if (!a.email().empty())
1351 os << " (" << a.email() << ")";
1352 // FIXME ctime is english, we should translate that
1353 os << _(" at ") << ctime(&change.changetime);
1354 os << " : ";
1357 // I think we should only show changes from the default
1358 // font. (Asger)
1359 // No, from the document font (MV)
1360 Font font = cur.real_current_font;
1361 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1363 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1365 // The paragraph depth
1366 int depth = cur.paragraph().getDepth();
1367 if (depth > 0)
1368 os << bformat(_(", Depth: %1$d"), depth);
1370 // The paragraph spacing, but only if different from
1371 // buffer spacing.
1372 Spacing const & spacing = par.params().spacing();
1373 if (!spacing.isDefault()) {
1374 os << _(", Spacing: ");
1375 switch (spacing.getSpace()) {
1376 case Spacing::Single:
1377 os << _("Single");
1378 break;
1379 case Spacing::Onehalf:
1380 os << _("OneHalf");
1381 break;
1382 case Spacing::Double:
1383 os << _("Double");
1384 break;
1385 case Spacing::Other:
1386 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1387 break;
1388 case Spacing::Default:
1389 // should never happen, do nothing
1390 break;
1394 #ifdef DEVEL_VERSION
1395 os << _(", Inset: ") << &cur.inset();
1396 os << _(", Paragraph: ") << cur.pit();
1397 os << _(", Id: ") << par.id();
1398 os << _(", Position: ") << cur.pos();
1399 // FIXME: Why is the check for par.size() needed?
1400 // We are called with cur.pos() == par.size() quite often.
1401 if (!par.empty() && cur.pos() < par.size()) {
1402 // Force output of code point, not character
1403 size_t const c = par.getChar(cur.pos());
1404 os << _(", Char: 0x") << hex << c;
1406 os << _(", Boundary: ") << cur.boundary();
1407 // Row & row = cur.textRow();
1408 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1409 #endif
1410 return os.str();
1414 docstring Text::getPossibleLabel(Cursor & cur) const
1416 pit_type pit = cur.pit();
1418 Layout const * layout = &(pars_[pit].layout());
1420 docstring text;
1421 docstring par_text = pars_[pit].asString();
1422 string piece;
1423 // the return string of math matrices might contain linebreaks
1424 par_text = subst(par_text, '\n', '-');
1425 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1426 if (par_text.empty())
1427 break;
1428 docstring head;
1429 par_text = split(par_text, head, ' ');
1430 // Is it legal to use spaces in labels ?
1431 if (i > 0)
1432 text += '-';
1433 text += head;
1436 // No need for a prefix if the user said so.
1437 if (lyxrc.label_init_length <= 0)
1438 return text;
1440 // Will contain the label type.
1441 docstring name;
1443 // For section, subsection, etc...
1444 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1445 Layout const * layout2 = &(pars_[pit - 1].layout());
1446 if (layout2->latextype != LATEX_PARAGRAPH) {
1447 --pit;
1448 layout = layout2;
1451 if (layout->latextype != LATEX_PARAGRAPH)
1452 name = from_ascii(layout->latexname());
1454 // for captions, we just take the caption type
1455 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1456 if (caption_inset)
1457 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1459 // If none of the above worked, we'll see if we're inside various
1460 // types of insets and take our abbreviation from them.
1461 if (name.empty()) {
1462 InsetCode const codes[] = {
1463 FLOAT_CODE,
1464 WRAP_CODE,
1465 FOOT_CODE
1467 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1468 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1469 if (float_inset) {
1470 name = float_inset->name();
1471 break;
1476 // Create a correct prefix for prettyref
1477 if (name == "theorem")
1478 name = from_ascii("thm");
1479 else if (name == "Foot")
1480 name = from_ascii("fn");
1481 else if (name == "listing")
1482 name = from_ascii("lst");
1484 if (!name.empty())
1485 text = name.substr(0, 3) + ':' + text;
1487 return text;
1491 void Text::charsTranspose(Cursor & cur)
1493 LASSERT(this == cur.text(), /**/);
1495 pos_type pos = cur.pos();
1497 // If cursor is at beginning or end of paragraph, do nothing.
1498 if (pos == cur.lastpos() || pos == 0)
1499 return;
1501 Paragraph & par = cur.paragraph();
1503 // Get the positions of the characters to be transposed.
1504 pos_type pos1 = pos - 1;
1505 pos_type pos2 = pos;
1507 // In change tracking mode, ignore deleted characters.
1508 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1509 ++pos2;
1510 if (pos2 == cur.lastpos())
1511 return;
1513 while (pos1 >= 0 && par.isDeleted(pos1))
1514 --pos1;
1515 if (pos1 < 0)
1516 return;
1518 // Don't do anything if one of the "characters" is not regular text.
1519 if (par.isInset(pos1) || par.isInset(pos2))
1520 return;
1522 // Store the characters to be transposed (including font information).
1523 char_type char1 = par.getChar(pos1);
1524 Font const font1 =
1525 par.getFontSettings(cur.buffer().params(), pos1);
1527 char_type char2 = par.getChar(pos2);
1528 Font const font2 =
1529 par.getFontSettings(cur.buffer().params(), pos2);
1531 // And finally, we are ready to perform the transposition.
1532 // Track the changes if Change Tracking is enabled.
1533 bool const trackChanges = cur.buffer().params().trackChanges;
1535 cur.recordUndo();
1537 par.eraseChar(pos2, trackChanges);
1538 par.eraseChar(pos1, trackChanges);
1539 par.insertChar(pos1, char2, font2, trackChanges);
1540 par.insertChar(pos2, char1, font1, trackChanges);
1542 cur.checkBufferStructure();
1544 // After the transposition, move cursor to after the transposition.
1545 setCursor(cur, cur.pit(), pos2);
1546 cur.forwardPos();
1550 DocIterator Text::macrocontextPosition() const
1552 return macrocontext_position_;
1556 void Text::setMacrocontextPosition(DocIterator const & pos)
1558 macrocontext_position_ = pos;
1562 docstring Text::previousWord(CursorSlice const & sl) const
1564 CursorSlice from = sl;
1565 CursorSlice to = sl;
1566 getWord(from, to, PREVIOUS_WORD);
1567 if (sl == from || to == from)
1568 return docstring();
1570 Paragraph const & par = sl.paragraph();
1571 return par.asString(from.pos(), to.pos());
1575 bool Text::completionSupported(Cursor const & cur) const
1577 Paragraph const & par = cur.paragraph();
1578 return cur.pos() > 0
1579 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1580 && par.isLetter(cur.pos() - 1);
1584 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1586 return new TextCompletionList(cur);
1590 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1592 LASSERT(cur.bv().cursor() == cur, /**/);
1593 cur.insert(s);
1594 cur.bv().cursor() = cur;
1595 if (!(cur.disp_.update() & Update::Force))
1596 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1597 return true;
1601 docstring Text::completionPrefix(Cursor const & cur) const
1603 return previousWord(cur.top());
1606 } // namespace lyx