]> git.lyx.org Git - features.git/blob - src/Text3.cpp
Greyedouts can be inserted in commands/description
[features.git] / src / Text3.cpp
1 /**
2  * \file Text3.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 Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "BranchList.h"
21 #include "FloatList.h"
22 #include "FuncStatus.h"
23 #include "Buffer.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "Changes.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyX.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "ParagraphParameters.h"
44 #include "SpellChecker.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "Thesaurus.h"
48 #include "WordLangTuple.h"
49
50 #include "frontends/alert.h"
51 #include "frontends/Application.h"
52 #include "frontends/Clipboard.h"
53 #include "frontends/Selection.h"
54
55 #include "insets/InsetArgument.h"
56 #include "insets/InsetCollapsible.h"
57 #include "insets/InsetCommand.h"
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetFloat.h"
60 #include "insets/InsetFloatList.h"
61 #include "insets/InsetGraphics.h"
62 #include "insets/InsetGraphicsParams.h"
63 #include "insets/InsetIPAMacro.h"
64 #include "insets/InsetNewline.h"
65 #include "insets/InsetQuotes.h"
66 #include "insets/InsetSpecialChar.h"
67 #include "insets/InsetText.h"
68 #include "insets/InsetWrap.h"
69
70 #include "support/convert.h"
71 #include "support/debug.h"
72 #include "support/gettext.h"
73 #include "support/lassert.h"
74 #include "support/lstrings.h"
75 #include "support/lyxalgo.h"
76 #include "support/lyxtime.h"
77 #include "support/os.h"
78 #include "support/regex.h"
79
80 #include "mathed/InsetMathHull.h"
81 #include "mathed/InsetMathMacroTemplate.h"
82
83 #include <clocale>
84 #include <sstream>
85
86 using namespace std;
87 using namespace lyx::support;
88
89 namespace lyx {
90
91 using cap::copySelection;
92 using cap::cutSelection;
93 using cap::cutSelectionToTemp;
94 using cap::pasteFromStack;
95 using cap::pasteFromTemp;
96 using cap::pasteClipboardText;
97 using cap::pasteClipboardGraphics;
98 using cap::replaceSelection;
99 using cap::grabAndEraseSelection;
100 using cap::selClearOrDel;
101 using cap::pasteSimpleText;
102 using frontend::Clipboard;
103
104 // globals...
105 static Font freefont(ignore_font, ignore_language);
106 static bool toggleall = false;
107
108 static void toggleAndShow(Cursor & cur, Text * text,
109         Font const & font, bool togall = true)
110 {
111         text->toggleFree(cur, font, togall);
112
113         if (font.language() != ignore_language ||
114             font.fontInfo().number() != FONT_IGNORE) {
115                 TextMetrics const & tm = cur.bv().textMetrics(text);
116                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
117                                                        cur.real_current_font))
118                         text->setCursor(cur, cur.pit(), cur.pos(),
119                                         false, !cur.boundary());
120         }
121 }
122
123
124 static void moveCursor(Cursor & cur, bool selecting)
125 {
126         if (selecting || cur.mark())
127                 cur.setSelection();
128 }
129
130
131 static void finishChange(Cursor & cur, bool selecting)
132 {
133         cur.finishUndo();
134         moveCursor(cur, selecting);
135 }
136
137
138 static void mathDispatch(Cursor & cur, FuncRequest const & cmd)
139 {
140         cur.recordUndo();
141         docstring sel = cur.selectionAsString(false);
142
143         // It may happen that sel is empty but there is a selection
144         replaceSelection(cur);
145
146         // Is this a valid formula?
147         bool valid = true;
148
149         if (sel.empty()) {
150 #ifdef ENABLE_ASSERTIONS
151                 const int old_pos = cur.pos();
152 #endif
153                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
154 #ifdef ENABLE_ASSERTIONS
155                 LATTEST(old_pos == cur.pos());
156 #endif
157                 cur.nextInset()->edit(cur, true);
158                 if (cmd.action() != LFUN_MATH_MODE)
159                         // LFUN_MATH_MODE has a different meaning in math mode
160                         cur.dispatch(cmd);
161         } else {
162                 InsetMathHull * formula = new InsetMathHull(cur.buffer());
163                 string const selstr = to_utf8(sel);
164                 istringstream is(selstr);
165                 Lexer lex;
166                 lex.setStream(is);
167                 if (!formula->readQuiet(lex)) {
168                         // No valid formula, let's try with delims
169                         is.str("$" + selstr + "$");
170                         lex.setStream(is);
171                         if (!formula->readQuiet(lex)) {
172                                 // Still not valid, leave it as is
173                                 valid = false;
174                                 delete formula;
175                                 cur.insert(sel);
176                         }
177                 }
178                 if (valid) {
179                         cur.insert(formula);
180                         cur.nextInset()->edit(cur, true);
181                         LASSERT(cur.inMathed(), return);
182                         cur.pos() = 0;
183                         cur.resetAnchor();
184                         cur.selection(true);
185                         cur.pos() = cur.lastpos();
186                         if (cmd.action() != LFUN_MATH_MODE)
187                                 // LFUN_MATH_MODE has a different meaning in math mode
188                                 cur.dispatch(cmd);
189                         cur.clearSelection();
190                         cur.pos() = cur.lastpos();
191                 }
192         }
193         if (valid)
194                 cur.message(from_utf8(N_("Math editor mode")));
195         else
196                 cur.message(from_utf8(N_("No valid math formula")));
197 }
198
199
200 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
201 {
202         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
203         if (cur.inRegexped()) {
204                 cur.message(_("Already in regular expression mode"));
205                 return;
206         }
207         cur.recordUndo();
208         docstring sel = cur.selectionAsString(false);
209
210         // It may happen that sel is empty but there is a selection
211         replaceSelection(cur);
212
213         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
214         cur.nextInset()->edit(cur, true);
215         cur.niceInsert(sel);
216
217         cur.message(_("Regexp editor mode"));
218 }
219
220
221 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
222 {
223         cur.recordUndo();
224         cap::replaceSelection(cur);
225         cur.insert(new InsetSpecialChar(kind));
226         cur.posForward();
227 }
228
229
230 static void ipaChar(Cursor & cur, InsetIPAChar::Kind kind)
231 {
232         cur.recordUndo();
233         cap::replaceSelection(cur);
234         cur.insert(new InsetIPAChar(kind));
235         cur.posForward();
236 }
237
238
239 static bool doInsertInset(Cursor & cur, Text * text,
240         FuncRequest const & cmd, bool edit, bool pastesel)
241 {
242         Buffer & buffer = cur.bv().buffer();
243         BufferParams const & bparams = buffer.params();
244         Inset * inset = createInset(&buffer, cmd);
245         if (!inset)
246                 return false;
247
248         if (InsetCollapsible * ci = inset->asInsetCollapsible())
249                 ci->setButtonLabel();
250
251         cur.recordUndo();
252         if (cmd.action() == LFUN_INDEX_INSERT) {
253                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
254                 text->insertInset(cur, inset);
255                 if (edit)
256                         inset->edit(cur, true);
257                 // Now put this into inset
258                 Font const f(inherit_font, cur.current_font.language());
259                 if (!ds.empty()) {
260                         cur.text()->insertStringAsLines(cur, ds, f);
261                         cur.leaveInset(*inset);
262                 }
263                 return true;
264         }
265         else if (cmd.action() == LFUN_ARGUMENT_INSERT) {
266                 bool cotextinsert = false;
267                 InsetArgument const * const ia = static_cast<InsetArgument const *>(inset);
268                 Layout const & lay = cur.paragraph().layout();
269                 Layout::LaTeXArgMap args = lay.args();
270                 Layout::LaTeXArgMap::const_iterator const lait = args.find(ia->name());
271                 if (lait != args.end())
272                         cotextinsert = (*lait).second.insertcotext;
273                 else {
274                         InsetLayout const & il = cur.inset().getLayout();
275                         args = il.args();
276                         Layout::LaTeXArgMap::const_iterator const ilait = args.find(ia->name());
277                         if (ilait != args.end())
278                                 cotextinsert = (*ilait).second.insertcotext;
279                 }
280                 // The argument requests to insert a copy of the co-text to the inset
281                 if (cotextinsert) {
282                         docstring ds;
283                         // If we have a selection within a paragraph, use this
284                         if (cur.selection() && cur.selBegin().pit() == cur.selEnd().pit())
285                                 ds = cur.selectionAsString(false);
286                         // else use the whole paragraph
287                         else
288                                 ds = cur.paragraph().asString();
289                         text->insertInset(cur, inset);
290                         if (edit)
291                                 inset->edit(cur, true);
292                         // Now put co-text into inset
293                         Font const f(inherit_font, cur.current_font.language());
294                         if (!ds.empty()) {
295                                 cur.text()->insertStringAsLines(cur, ds, f);
296                                 cur.leaveInset(*inset);
297                         }
298                         return true;
299                 }
300         }
301
302         bool gotsel = false;
303         if (cur.selection()) {
304                 cutSelectionToTemp(cur, false, pastesel);
305                 cur.clearSelection();
306                 gotsel = true;
307         }
308         text->insertInset(cur, inset);
309
310         if (edit)
311                 inset->edit(cur, true);
312
313         if (!gotsel || !pastesel)
314                 return true;
315
316         pasteFromTemp(cur, cur.buffer()->errorList("Paste"));
317         cur.buffer()->errors("Paste");
318         cur.clearSelection(); // bug 393
319         cur.finishUndo();
320         InsetText * inset_text = inset->asInsetText();
321         if (inset_text) {
322                 inset_text->fixParagraphsFont();
323                 if (!inset_text->allowMultiPar() || cur.lastpit() == 0) {
324                         // reset first par to default
325                         cur.text()->paragraphs().begin()
326                                 ->setPlainOrDefaultLayout(bparams.documentClass());
327                         cur.pos() = 0;
328                         cur.pit() = 0;
329                         // Merge multiple paragraphs -- hack
330                         while (cur.lastpit() > 0)
331                                 mergeParagraph(bparams, cur.text()->paragraphs(), 0);
332                         if (cmd.action() == LFUN_FLEX_INSERT)
333                                 return true;
334                         Cursor old = cur;
335                         cur.leaveInset(*inset);
336                         if (cmd.action() == LFUN_PREVIEW_INSERT
337                             || cmd.action() == LFUN_IPA_INSERT)
338                                 // trigger preview
339                                 notifyCursorLeavesOrEnters(old, cur);
340                 }
341         } else {
342                 cur.leaveInset(*inset);
343                 // reset surrounding par to default
344                 DocumentClass const & dc = bparams.documentClass();
345                 docstring const layoutname = inset->usePlainLayout()
346                         ? dc.plainLayoutName()
347                         : dc.defaultLayoutName();
348                 text->setLayout(cur, layoutname);
349         }
350         return true;
351 }
352
353
354 string const freefont2string()
355 {
356         return freefont.toString(toggleall);
357 }
358
359
360 /// the type of outline operation
361 enum OutlineOp {
362         OutlineUp, // Move this header with text down
363         OutlineDown,   // Move this header with text up
364         OutlineIn, // Make this header deeper
365         OutlineOut // Make this header shallower
366 };
367
368
369 static void insertSeparator(Cursor & cur, depth_type const depth)
370 {
371         Buffer & buf = *cur.buffer();
372         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
373         DocumentClass const & tc = buf.params().documentClass();
374         lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
375                                   + from_ascii("\" ignoreautonests")));
376         // FIXME: Bibitem mess!
377         if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
378                 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
379         lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
380         while (cur.paragraph().params().depth() > depth)
381                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
382 }
383
384
385 static void outline(OutlineOp mode, Cursor & cur, Text * text)
386 {
387         Buffer & buf = *cur.buffer();
388         pit_type & pit = cur.pit();
389         ParagraphList & pars = buf.text().paragraphs();
390         ParagraphList::iterator const bgn = pars.begin();
391         // The first paragraph of the area to be copied:
392         ParagraphList::iterator start = lyx::next(bgn, pit);
393         // The final paragraph of area to be copied:
394         ParagraphList::iterator finish = start;
395         ParagraphList::iterator const end = pars.end();
396         depth_type const current_depth = cur.paragraph().params().depth();
397
398         int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
399         int toclevel;
400
401         // Move out (down) from this section header
402         if (finish != end)
403                 ++finish;
404
405         // Seek the one (on same level) below
406         for (; finish != end; ++finish) {
407                 toclevel = buf.text().getTocLevel(distance(bgn, finish));
408                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
409                         break;
410         }
411
412         switch (mode) {
413                 case OutlineUp: {
414                         if (start == pars.begin())
415                                 // Nothing to move.
416                                 return;
417                         ParagraphList::iterator dest = start;
418                         // Move out (up) from this header
419                         if (dest == bgn)
420                                 return;
421                         // Search previous same-level header above
422                         do {
423                                 --dest;
424                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
425                         } while(dest != bgn
426                                 && (toclevel == Layout::NOT_IN_TOC
427                                     || toclevel > thistoclevel));
428                         // Not found; do nothing
429                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
430                                 return;
431                         pit_type newpit = distance(bgn, dest);
432                         pit_type const len = distance(start, finish);
433                         pit_type const deletepit = pit + len;
434                         buf.undo().recordUndo(cur, newpit, deletepit - 1);
435                         // If we move an environment upwards, make sure it is
436                         // separated from its new neighbour below:
437                         // If an environment of the same layout follows, and the moved
438                         // paragraph sequence does not end with a separator, insert one.
439                         ParagraphList::iterator lastmoved = finish;
440                         --lastmoved;
441                         if (start->layout().isEnvironment()
442                             && dest->layout() == start->layout()
443                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
444                                 cur.pit() = distance(bgn, lastmoved);
445                                 cur.pos() = cur.lastpos();
446                                 insertSeparator(cur, current_depth);
447                                 cur.pit() = pit;
448                         }
449                         // Likewise, if we moved an environment upwards, make sure it
450                         // is separated from its new neighbour above.
451                         // The paragraph before the target of movement
452                         if (dest != bgn) {
453                                 ParagraphList::iterator before = dest;
454                                 --before;
455                                 // Get the parent paragraph (outer in nested context)
456                                 pit_type const parent =
457                                         before->params().depth() > current_depth
458                                                 ? text->depthHook(distance(bgn, before), current_depth)
459                                                 : distance(bgn, before);
460                                 // If a environment with same layout preceeds the moved one in the new
461                                 // position, and there is no separator yet, insert one.
462                                 if (start->layout().isEnvironment()
463                                     && pars[parent].layout() == start->layout()
464                                     && !before->isEnvSeparator(before->beginOfBody())) {
465                                         cur.pit() = distance(bgn, before);
466                                         cur.pos() = cur.lastpos();
467                                         insertSeparator(cur, current_depth);
468                                         cur.pit() = pit;
469                                 }
470                         }
471                         newpit = distance(bgn, dest);
472                         pars.splice(dest, start, finish);
473                         cur.pit() = newpit;
474                         break;
475                 }
476                 case OutlineDown: {
477                         if (finish == end)
478                                 // Nothing to move.
479                                 return;
480                         // Go one down from *this* header:
481                         ParagraphList::iterator dest = next(finish, 1);
482                         // Go further down to find header to insert in front of:
483                         for (; dest != end; ++dest) {
484                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
485                                 if (toclevel != Layout::NOT_IN_TOC
486                                       && toclevel <= thistoclevel)
487                                         break;
488                         }
489                         // One such was found, so go on...
490                         // If we move an environment downwards, make sure it is
491                         // separated from its new neighbour above.
492                         pit_type newpit = distance(bgn, dest);
493                         buf.undo().recordUndo(cur, pit, newpit - 1);
494                         // The paragraph before the target of movement
495                         ParagraphList::iterator before = dest;
496                         --before;
497                         // Get the parent paragraph (outer in nested context)
498                         pit_type const parent =
499                                 before->params().depth() > current_depth
500                                         ? text->depthHook(distance(bgn, before), current_depth)
501                                         : distance(bgn, before);
502                         // If a environment with same layout preceeds the moved one in the new
503                         // position, and there is no separator yet, insert one.
504                         if (start->layout().isEnvironment()
505                             && pars[parent].layout() == start->layout()
506                             && !before->isEnvSeparator(before->beginOfBody())) {
507                                 cur.pit() = distance(bgn, before);
508                                 cur.pos() = cur.lastpos();
509                                 insertSeparator(cur, current_depth);
510                                 cur.pit() = pit;
511                         }
512                         // Likewise, make sure moved environments are separated
513                         // from their new neighbour below:
514                         // If an environment of the same layout follows, and the moved
515                         // paragraph sequence does not end with a separator, insert one.
516                         ParagraphList::iterator lastmoved = finish;
517                         --lastmoved;
518                         if (dest != end
519                             && start->layout().isEnvironment()
520                             && dest->layout() == start->layout()
521                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
522                                 cur.pit() = distance(bgn, lastmoved);
523                                 cur.pos() = cur.lastpos();
524                                 insertSeparator(cur, current_depth);
525                                 cur.pit() = pit;
526                         }
527                         newpit = distance(bgn, dest);
528                         pit_type const len = distance(start, finish);
529                         pars.splice(dest, start, finish);
530                         cur.pit() = newpit - len;
531                         break;
532                 }
533                 case OutlineIn:
534                 case OutlineOut: {
535                         pit_type const len = distance(start, finish);
536                         buf.undo().recordUndo(cur, pit, pit + len - 1);
537                         for (; start != finish; ++start) {
538                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
539                                 if (toclevel == Layout::NOT_IN_TOC)
540                                         continue;
541
542                                 DocumentClass const & tc = buf.params().documentClass();
543                                 DocumentClass::const_iterator lit = tc.begin();
544                                 DocumentClass::const_iterator len = tc.end();
545                                 int const newtoclevel =
546                                         (mode == OutlineIn ? toclevel + 1 : toclevel - 1);
547                                 LabelType const oldlabeltype = start->layout().labeltype;
548
549                                 for (; lit != len; ++lit) {
550                                         if (lit->toclevel ==  newtoclevel &&
551                                              lit->labeltype == oldlabeltype) {
552                                                 start->setLayout(*lit);
553                                                 break;
554                                         }
555                                 }
556                         }
557                         break;
558                 }
559         }
560 }
561
562
563 void Text::number(Cursor & cur)
564 {
565         FontInfo font = ignore_font;
566         font.setNumber(FONT_TOGGLE);
567         toggleAndShow(cur, this, Font(font, ignore_language));
568 }
569
570
571 bool Text::isRTL(Paragraph const & par) const
572 {
573         Buffer const & buffer = owner_->buffer();
574         return par.isRTL(buffer.params());
575 }
576
577
578 namespace {
579
580         Language const * getLanguage(Cursor const & cur, string const & lang) {
581                 return lang.empty() ? cur.getFont().language() : languages.getLanguage(lang);
582         }
583
584 } // namespace
585
586
587 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
588 {
589         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
590
591         // Dispatch if the cursor is inside the text. It is not the
592         // case for context menus (bug 5797).
593         if (cur.text() != this) {
594                 cur.undispatched();
595                 return;
596         }
597
598         BufferView * bv = &cur.bv();
599         TextMetrics * tm = &bv->textMetrics(this);
600         if (!tm->contains(cur.pit())) {
601                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
602                 tm = &bv->textMetrics(this);
603         }
604
605         // FIXME: We use the update flag to indicates wether a singlePar or a
606         // full screen update is needed. We reset it here but shall we restore it
607         // at the end?
608         cur.noScreenUpdate();
609
610         LBUFERR(this == cur.text());
611
612         // NOTE: This should NOT be a reference. See commit 94a5481a.
613         CursorSlice const oldTopSlice = cur.top();
614         bool const oldBoundary = cur.boundary();
615         bool const oldSelection = cur.selection();
616         // Signals that, even if needsUpdate == false, an update of the
617         // cursor paragraph is required
618         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
619                 LyXAction::SingleParUpdate);
620         // Signals that a full-screen update is required
621         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
622                 LyXAction::NoUpdate) || singleParUpdate);
623         bool const last_misspelled = lyxrc.spellcheck_continuously
624                 && cur.paragraph().isMisspelled(cur.pos(), true);
625
626         FuncCode const act = cmd.action();
627         switch (act) {
628
629         case LFUN_PARAGRAPH_MOVE_DOWN: {
630                 pit_type const pit = cur.pit();
631                 cur.recordUndo(pit, pit + 1);
632                 cur.finishUndo();
633                 pars_.swap(pit, pit + 1);
634                 needsUpdate = true;
635                 cur.forceBufferUpdate();
636                 ++cur.pit();
637                 break;
638         }
639
640         case LFUN_PARAGRAPH_MOVE_UP: {
641                 pit_type const pit = cur.pit();
642                 cur.recordUndo(pit - 1, pit);
643                 cur.finishUndo();
644                 pars_.swap(pit, pit - 1);
645                 --cur.pit();
646                 needsUpdate = true;
647                 cur.forceBufferUpdate();
648                 break;
649         }
650
651         case LFUN_APPENDIX: {
652                 Paragraph & par = cur.paragraph();
653                 bool start = !par.params().startOfAppendix();
654
655 // FIXME: The code below only makes sense at top level.
656 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
657                 // ensure that we have only one start_of_appendix in this document
658                 // FIXME: this don't work for multipart document!
659                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
660                         if (pars_[tmp].params().startOfAppendix()) {
661                                 cur.recordUndo(tmp, tmp);
662                                 pars_[tmp].params().startOfAppendix(false);
663                                 break;
664                         }
665                 }
666
667                 cur.recordUndo();
668                 par.params().startOfAppendix(start);
669
670                 // we can set the refreshing parameters now
671                 cur.forceBufferUpdate();
672                 break;
673         }
674
675         case LFUN_WORD_DELETE_FORWARD:
676                 if (cur.selection())
677                         cutSelection(cur, true, false);
678                 else
679                         deleteWordForward(cur, cmd.getArg(0) == "force");
680                 finishChange(cur, false);
681                 break;
682
683         case LFUN_WORD_DELETE_BACKWARD:
684                 if (cur.selection())
685                         cutSelection(cur, true, false);
686                 else
687                         deleteWordBackward(cur, cmd.getArg(0) == "force");
688                 finishChange(cur, false);
689                 break;
690
691         case LFUN_LINE_DELETE_FORWARD:
692                 if (cur.selection())
693                         cutSelection(cur, true, false);
694                 else
695                         tm->deleteLineForward(cur);
696                 finishChange(cur, false);
697                 break;
698
699         case LFUN_BUFFER_BEGIN:
700         case LFUN_BUFFER_BEGIN_SELECT:
701                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
702                 if (cur.depth() == 1)
703                         needsUpdate |= cursorTop(cur);
704                 else
705                         cur.undispatched();
706                 cur.screenUpdateFlags(Update::FitCursor);
707                 break;
708
709         case LFUN_BUFFER_END:
710         case LFUN_BUFFER_END_SELECT:
711                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
712                 if (cur.depth() == 1)
713                         needsUpdate |= cursorBottom(cur);
714                 else
715                         cur.undispatched();
716                 cur.screenUpdateFlags(Update::FitCursor);
717                 break;
718
719         case LFUN_INSET_BEGIN:
720         case LFUN_INSET_BEGIN_SELECT:
721                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
722                 if (cur.depth() == 1 || !cur.top().at_begin())
723                         needsUpdate |= cursorTop(cur);
724                 else
725                         cur.undispatched();
726                 cur.screenUpdateFlags(Update::FitCursor);
727                 break;
728
729         case LFUN_INSET_END:
730         case LFUN_INSET_END_SELECT:
731                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
732                 if (cur.depth() == 1 || !cur.top().at_end())
733                         needsUpdate |= cursorBottom(cur);
734                 else
735                         cur.undispatched();
736                 cur.screenUpdateFlags(Update::FitCursor);
737                 break;
738
739         case LFUN_CHAR_FORWARD:
740         case LFUN_CHAR_FORWARD_SELECT: {
741                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
742                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
743                 bool const cur_moved = cursorForward(cur);
744                 needsUpdate |= cur_moved;
745
746                 if (!cur_moved && oldTopSlice == cur.top()
747                                && cur.boundary() == oldBoundary) {
748                         cur.undispatched();
749                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
750
751                         // we will probably be moving out the inset, so we should execute
752                         // the depm-mechanism, but only when the cursor has a place to
753                         // go outside this inset, i.e. in a slice above.
754                         if (cur.depth() > 1 && cur.pos() == cur.lastpos()
755                                   && cur.pit() == cur.lastpit()) {
756                                 // The cursor hasn't changed yet. To give the
757                                 // DEPM the possibility of doing something we must
758                                 // provide it with two different cursors.
759                                 Cursor dummy = cur;
760                                 dummy.pos() = dummy.pit() = 0;
761                                 if (cur.bv().checkDepm(dummy, cur))
762                                         cur.forceBufferUpdate();
763                         }
764                 }
765                 break;
766         }
767
768         case LFUN_CHAR_BACKWARD:
769         case LFUN_CHAR_BACKWARD_SELECT: {
770                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
771                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
772                 bool const cur_moved = cursorBackward(cur);
773                 needsUpdate |= cur_moved;
774
775                 if (!cur_moved && oldTopSlice == cur.top()
776                                && cur.boundary() == oldBoundary) {
777                         cur.undispatched();
778                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
779
780                         // we will probably be moving out the inset, so we should execute
781                         // the depm-mechanism, but only when the cursor has a place to
782                         // go outside this inset, i.e. in a slice above.
783                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
784                                 // The cursor hasn't changed yet. To give the
785                                 // DEPM the possibility of doing something we must
786                                 // provide it with two different cursors.
787                                 Cursor dummy = cur;
788                                 dummy.pos() = cur.lastpos();
789                                 dummy.pit() = cur.lastpit();
790                                 if (cur.bv().checkDepm(dummy, cur))
791                                         cur.forceBufferUpdate();
792                         }
793                 }
794                 break;
795         }
796
797         case LFUN_CHAR_LEFT:
798         case LFUN_CHAR_LEFT_SELECT:
799                 if (lyxrc.visual_cursor) {
800                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
801                         bool const cur_moved = cursorVisLeft(cur);
802                         needsUpdate |= cur_moved;
803                         if (!cur_moved && oldTopSlice == cur.top()
804                                        && cur.boundary() == oldBoundary) {
805                                 cur.undispatched();
806                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
807                         }
808                 } else {
809                         if (cur.reverseDirectionNeeded()) {
810                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
811                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
812                         } else {
813                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
814                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
815                         }
816                         dispatch(cur, cmd);
817                         return;
818                 }
819                 break;
820
821         case LFUN_CHAR_RIGHT:
822         case LFUN_CHAR_RIGHT_SELECT:
823                 if (lyxrc.visual_cursor) {
824                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
825                         bool const cur_moved = cursorVisRight(cur);
826                         needsUpdate |= cur_moved;
827                         if (!cur_moved && oldTopSlice == cur.top()
828                                        && cur.boundary() == oldBoundary) {
829                                 cur.undispatched();
830                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
831                         }
832                 } else {
833                         if (cur.reverseDirectionNeeded()) {
834                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
835                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
836                         } else {
837                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
838                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
839                         }
840                         dispatch(cur, cmd);
841                         return;
842                 }
843                 break;
844
845
846         case LFUN_UP_SELECT:
847         case LFUN_DOWN_SELECT:
848         case LFUN_UP:
849         case LFUN_DOWN: {
850                 // stop/start the selection
851                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
852                         cmd.action() == LFUN_UP_SELECT;
853
854                 // move cursor up/down
855                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
856                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
857
858                 if (!atFirstOrLastRow) {
859                         needsUpdate |= cur.selHandle(select);
860                         cur.upDownInText(up, needsUpdate);
861                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
862                 } else {
863                         pos_type newpos = up ? 0 : cur.lastpos();
864                         if (lyxrc.mac_like_cursor_movement && cur.pos() != newpos) {
865                                 needsUpdate |= cur.selHandle(select);
866                                 // we do not reset the targetx of the cursor
867                                 cur.pos() = newpos;
868                                 needsUpdate |= bv->checkDepm(cur, bv->cursor());
869                                 cur.updateTextTargetOffset();
870                                 if (needsUpdate)
871                                         cur.forceBufferUpdate();
872                                 break;
873                         }
874
875                         // if the cursor cannot be moved up or down do not remove
876                         // the selection right now, but wait for the next dispatch.
877                         if (select)
878                                 needsUpdate |= cur.selHandle(select);
879                         cur.upDownInText(up, needsUpdate);
880                         cur.undispatched();
881                 }
882
883                 break;
884         }
885
886         case LFUN_PARAGRAPH_UP:
887         case LFUN_PARAGRAPH_UP_SELECT:
888                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
889                 needsUpdate |= cursorUpParagraph(cur);
890                 break;
891
892         case LFUN_PARAGRAPH_DOWN:
893         case LFUN_PARAGRAPH_DOWN_SELECT:
894                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
895                 needsUpdate |= cursorDownParagraph(cur);
896                 break;
897
898         case LFUN_LINE_BEGIN:
899         case LFUN_LINE_BEGIN_SELECT:
900                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
901                 needsUpdate |= tm->cursorHome(cur);
902                 break;
903
904         case LFUN_LINE_END:
905         case LFUN_LINE_END_SELECT:
906                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
907                 needsUpdate |= tm->cursorEnd(cur);
908                 break;
909
910         case LFUN_SECTION_SELECT: {
911                 Buffer const & buf = *cur.buffer();
912                 pit_type const pit = cur.pit();
913                 ParagraphList & pars = buf.text().paragraphs();
914                 ParagraphList::iterator bgn = pars.begin();
915                 // The first paragraph of the area to be selected:
916                 ParagraphList::iterator start = lyx::next(bgn, pit);
917                 // The final paragraph of area to be selected:
918                 ParagraphList::iterator finish = start;
919                 ParagraphList::iterator end = pars.end();
920
921                 int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
922                 if (thistoclevel == Layout::NOT_IN_TOC)
923                         break;
924
925                 cur.pos() = 0;
926                 Cursor const old_cur = cur;
927                 needsUpdate |= cur.selHandle(true);
928
929                 // Move out (down) from this section header
930                 if (finish != end)
931                         ++finish;
932
933                 // Seek the one (on same level) below
934                 for (; finish != end; ++finish, ++cur.pit()) {
935                         int const toclevel = buf.text().getTocLevel(distance(bgn, finish));
936                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
937                                 break;
938                 }
939                 cur.pos() = cur.lastpos();
940                 cur.boundary(false);
941                 cur.setCurrentFont();
942
943                 needsUpdate |= cur != old_cur;
944                 break;
945         }
946
947         case LFUN_WORD_RIGHT:
948         case LFUN_WORD_RIGHT_SELECT:
949                 if (lyxrc.visual_cursor) {
950                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
951                         bool const cur_moved = cursorVisRightOneWord(cur);
952                         needsUpdate |= cur_moved;
953                         if (!cur_moved && oldTopSlice == cur.top()
954                                        && cur.boundary() == oldBoundary) {
955                                 cur.undispatched();
956                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
957                         }
958                 } else {
959                         if (cur.reverseDirectionNeeded()) {
960                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
961                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
962                         } else {
963                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
964                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
965                         }
966                         dispatch(cur, cmd);
967                         return;
968                 }
969                 break;
970
971         case LFUN_WORD_FORWARD:
972         case LFUN_WORD_FORWARD_SELECT: {
973                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
974                 bool const cur_moved = cursorForwardOneWord(cur);
975                 needsUpdate |= cur_moved;
976
977                 if (!cur_moved && oldTopSlice == cur.top()
978                                && cur.boundary() == oldBoundary) {
979                         cur.undispatched();
980                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
981
982                         // we will probably be moving out the inset, so we should execute
983                         // the depm-mechanism, but only when the cursor has a place to
984                         // go outside this inset, i.e. in a slice above.
985                         if (cur.depth() > 1 && cur.pos() == cur.lastpos()
986                                   && cur.pit() == cur.lastpit()) {
987                                 // The cursor hasn't changed yet. To give the
988                                 // DEPM the possibility of doing something we must
989                                 // provide it with two different cursors.
990                                 Cursor dummy = cur;
991                                 dummy.pos() = dummy.pit() = 0;
992                                 if (cur.bv().checkDepm(dummy, cur))
993                                         cur.forceBufferUpdate();
994                         }
995                 }
996                 break;
997         }
998
999         case LFUN_WORD_LEFT:
1000         case LFUN_WORD_LEFT_SELECT:
1001                 if (lyxrc.visual_cursor) {
1002                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
1003                         bool const cur_moved = cursorVisLeftOneWord(cur);
1004                         needsUpdate |= cur_moved;
1005                         if (!cur_moved && oldTopSlice == cur.top()
1006                                        && cur.boundary() == oldBoundary) {
1007                                 cur.undispatched();
1008                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
1009                         }
1010                 } else {
1011                         if (cur.reverseDirectionNeeded()) {
1012                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
1013                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
1014                         } else {
1015                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
1016                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
1017                         }
1018                         dispatch(cur, cmd);
1019                         return;
1020                 }
1021                 break;
1022
1023         case LFUN_WORD_BACKWARD:
1024         case LFUN_WORD_BACKWARD_SELECT: {
1025                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
1026                 bool const cur_moved = cursorBackwardOneWord(cur);
1027                 needsUpdate |= cur_moved;
1028
1029                 if (!cur_moved && oldTopSlice == cur.top()
1030                                && cur.boundary() == oldBoundary) {
1031                         cur.undispatched();
1032                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1033
1034                         // we will probably be moving out the inset, so we should execute
1035                         // the depm-mechanism, but only when the cursor has a place to
1036                         // go outside this inset, i.e. in a slice above.
1037                         if (cur.depth() > 1 && cur.pos() == 0
1038                                   && cur.pit() == 0) {
1039                                 // The cursor hasn't changed yet. To give the
1040                                 // DEPM the possibility of doing something we must
1041                                 // provide it with two different cursors.
1042                                 Cursor dummy = cur;
1043                                 dummy.pos() = cur.lastpos();
1044                                 dummy.pit() = cur.lastpit();
1045                                 if (cur.bv().checkDepm(dummy, cur))
1046                                         cur.forceBufferUpdate();
1047                         }
1048                 }
1049                 break;
1050         }
1051
1052         case LFUN_WORD_SELECT: {
1053                 selectWord(cur, WHOLE_WORD);
1054                 finishChange(cur, true);
1055                 break;
1056         }
1057
1058         case LFUN_NEWLINE_INSERT: {
1059                 InsetNewlineParams inp;
1060                 docstring arg = cmd.argument();
1061                 if (arg == "linebreak")
1062                         inp.kind = InsetNewlineParams::LINEBREAK;
1063                 else
1064                         inp.kind = InsetNewlineParams::NEWLINE;
1065                 cap::replaceSelection(cur);
1066                 cur.recordUndo();
1067                 cur.insert(new InsetNewline(inp));
1068                 cur.posForward();
1069                 moveCursor(cur, false);
1070                 break;
1071         }
1072
1073         case LFUN_TAB_INSERT: {
1074                 bool const multi_par_selection = cur.selection() &&
1075                         cur.selBegin().pit() != cur.selEnd().pit();
1076                 if (multi_par_selection) {
1077                         // If there is a multi-paragraph selection, a tab is inserted
1078                         // at the beginning of each paragraph.
1079                         cur.recordUndoSelection();
1080                         pit_type const pit_end = cur.selEnd().pit();
1081                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1082                                 pars_[pit].insertChar(0, '\t',
1083                                                       bv->buffer().params().track_changes);
1084                                 // Update the selection pos to make sure the selection does not
1085                                 // change as the inserted tab will increase the logical pos.
1086                                 if (cur.realAnchor().pit() == pit)
1087                                         cur.realAnchor().forwardPos();
1088                                 if (cur.pit() == pit)
1089                                         cur.forwardPos();
1090                         }
1091                         cur.finishUndo();
1092                 } else {
1093                         // Maybe we shouldn't allow tabs within a line, because they
1094                         // are not (yet) aligned as one might do expect.
1095                         FuncRequest ncmd(LFUN_SELF_INSERT, from_ascii("\t"));
1096                         dispatch(cur, ncmd);
1097                 }
1098                 break;
1099         }
1100
1101         case LFUN_TAB_DELETE: {
1102                 bool const tc = bv->buffer().params().track_changes;
1103                 if (cur.selection()) {
1104                         // If there is a selection, a tab (if present) is removed from
1105                         // the beginning of each paragraph.
1106                         cur.recordUndoSelection();
1107                         pit_type const pit_end = cur.selEnd().pit();
1108                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1109                                 Paragraph & par = paragraphs()[pit];
1110                                 if (par.empty())
1111                                         continue;
1112                                 char_type const c = par.getChar(0);
1113                                 if (c == '\t' || c == ' ') {
1114                                         // remove either 1 tab or 4 spaces.
1115                                         int const n = (c == ' ' ? 4 : 1);
1116                                         for (int i = 0; i < n
1117                                                   && !par.empty() && par.getChar(0) == c; ++i) {
1118                                                 if (cur.pit() == pit)
1119                                                         cur.posBackward();
1120                                                 if (cur.realAnchor().pit() == pit
1121                                                           && cur.realAnchor().pos() > 0 )
1122                                                         cur.realAnchor().backwardPos();
1123                                                 par.eraseChar(0, tc);
1124                                         }
1125                                 }
1126                         }
1127                         cur.finishUndo();
1128                 } else {
1129                         // If there is no selection, try to remove a tab or some spaces
1130                         // before the position of the cursor.
1131                         Paragraph & par = paragraphs()[cur.pit()];
1132                         pos_type const pos = cur.pos();
1133
1134                         if (pos == 0)
1135                                 break;
1136
1137                         char_type const c = par.getChar(pos - 1);
1138                         cur.recordUndo();
1139                         if (c == '\t') {
1140                                 cur.posBackward();
1141                                 par.eraseChar(cur.pos(), tc);
1142                         } else
1143                                 for (int n_spaces = 0;
1144                                      cur.pos() > 0
1145                                              && par.getChar(cur.pos() - 1) == ' '
1146                                              && n_spaces < 4;
1147                                      ++n_spaces) {
1148                                         cur.posBackward();
1149                                         par.eraseChar(cur.pos(), tc);
1150                                 }
1151                         cur.finishUndo();
1152                 }
1153                 break;
1154         }
1155
1156         case LFUN_CHAR_DELETE_FORWARD:
1157                 if (!cur.selection()) {
1158                         if (cur.pos() == cur.paragraph().size())
1159                                 // Par boundary, force full-screen update
1160                                 singleParUpdate = false;
1161                         else if (cmd.getArg(0) != "force" && cur.confirmDeletion()) {
1162                                 cur.resetAnchor();
1163                                 cur.selection(true);
1164                                 cur.posForward();
1165                                 cur.setSelection();
1166                                 break;
1167                         }
1168                         needsUpdate |= erase(cur);
1169                         cur.resetAnchor();
1170                 } else {
1171                         cutSelection(cur, true, false);
1172                         singleParUpdate = false;
1173                 }
1174                 moveCursor(cur, false);
1175                 break;
1176
1177         case LFUN_CHAR_DELETE_BACKWARD:
1178                 if (!cur.selection()) {
1179                         if (bv->getIntl().getTransManager().backspace()) {
1180                                 bool par_boundary = cur.pos() == 0;
1181                                 bool first_par = cur.pit() == 0;
1182                                 // Par boundary, full-screen update
1183                                 if (par_boundary)
1184                                         singleParUpdate = false;
1185                                 else if (cmd.getArg(0) != "force" && cur.confirmDeletion(true)) {
1186                                         cur.resetAnchor();
1187                                         cur.selection(true);
1188                                         cur.posBackward();
1189                                         cur.setSelection();
1190                                         break;
1191                                 }
1192                                 needsUpdate |= backspace(cur);
1193                                 cur.resetAnchor();
1194                                 if (par_boundary && !first_par && cur.pos() > 0
1195                                     && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
1196                                         needsUpdate |= backspace(cur);
1197                                         cur.resetAnchor();
1198                                 }
1199                         }
1200                 } else {
1201                         cutSelection(cur, true, false);
1202                         singleParUpdate = false;
1203                 }
1204                 break;
1205
1206         case LFUN_PARAGRAPH_BREAK: {
1207                 cap::replaceSelection(cur);
1208                 pit_type pit = cur.pit();
1209                 Paragraph const & par = pars_[pit];
1210                 bool lastpar = (pit == pit_type(pars_.size() - 1));
1211                 Paragraph const & nextpar = lastpar ? par : pars_[pit + 1];
1212                 pit_type prev = pit > 0 ? depthHook(pit, par.getDepth()) : pit;
1213                 if (prev < pit && cur.pos() == par.beginOfBody()
1214                     && !par.size() && !par.isEnvSeparator(cur.pos())
1215                     && !par.layout().isCommand()
1216                     && pars_[prev].layout() != par.layout()
1217                     && pars_[prev].layout().isEnvironment()
1218                     && !nextpar.isEnvSeparator(nextpar.beginOfBody())) {
1219                         if (par.layout().isEnvironment()
1220                             && pars_[prev].getDepth() == par.getDepth()) {
1221                                 docstring const layout = par.layout().name();
1222                                 DocumentClass const & tc = bv->buffer().params().documentClass();
1223                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1224                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1225                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1226                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1227                         } else {
1228                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1229                                 breakParagraph(cur);
1230                         }
1231                         Font const f(inherit_font, cur.current_font.language());
1232                         pars_[cur.pit() - 1].resetFonts(f);
1233                 } else {
1234                         if (par.isEnvSeparator(cur.pos()) && cmd.getArg(1) != "ignoresep")
1235                                 cur.posForward();
1236                         breakParagraph(cur, cmd.getArg(0) == "inverse");
1237                 }
1238                 cur.resetAnchor();
1239                 // If we have a list and autoinsert item insets,
1240                 // insert them now.
1241                 Layout::LaTeXArgMap args = par.layout().args();
1242                 for (auto const & thearg : args) {
1243                         Layout::latexarg arg = thearg.second;
1244                         if (arg.autoinsert && prefixIs(thearg.first, "item:")) {
1245                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, thearg.first);
1246                                 lyx::dispatch(cmd2);
1247                         }
1248                 }
1249                 break;
1250         }
1251
1252         case LFUN_INSET_INSERT: {
1253                 cur.recordUndo();
1254
1255                 // We have to avoid triggering InstantPreview loading
1256                 // before inserting into the document. See bug #5626.
1257                 bool loaded = bv->buffer().isFullyLoaded();
1258                 bv->buffer().setFullyLoaded(false);
1259                 Inset * inset = createInset(&bv->buffer(), cmd);
1260                 bv->buffer().setFullyLoaded(loaded);
1261
1262                 if (inset) {
1263                         // FIXME (Abdel 01/02/2006):
1264                         // What follows would be a partial fix for bug 2154:
1265                         //   http://www.lyx.org/trac/ticket/2154
1266                         // This automatically put the label inset _after_ a
1267                         // numbered section. It should be possible to extend the mechanism
1268                         // to any kind of LateX environement.
1269                         // The correct way to fix that bug would be at LateX generation.
1270                         // I'll let the code here for reference as it could be used for some
1271                         // other feature like "automatic labelling".
1272                         /*
1273                         Paragraph & par = pars_[cur.pit()];
1274                         if (inset->lyxCode() == LABEL_CODE
1275                                 && !par.layout().counter.empty()) {
1276                                 // Go to the end of the paragraph
1277                                 // Warning: Because of Change-Tracking, the last
1278                                 // position is 'size()' and not 'size()-1':
1279                                 cur.pos() = par.size();
1280                                 // Insert a new paragraph
1281                                 FuncRequest fr(LFUN_PARAGRAPH_BREAK);
1282                                 dispatch(cur, fr);
1283                         }
1284                         */
1285                         if (cur.selection())
1286                                 cutSelection(cur, true, false);
1287                         cur.insert(inset);
1288                         cur.forceBufferUpdate();
1289                         if (inset->editable() && inset->asInsetText())
1290                                 inset->edit(cur, true);
1291                         else
1292                                 cur.posForward();
1293
1294                         // trigger InstantPreview now
1295                         if (inset->lyxCode() == EXTERNAL_CODE) {
1296                                 InsetExternal & ins =
1297                                         static_cast<InsetExternal &>(*inset);
1298                                 ins.updatePreview();
1299                         }
1300                 }
1301
1302                 break;
1303         }
1304
1305         case LFUN_INSET_DISSOLVE: {
1306                 if (dissolveInset(cur)) {
1307                         needsUpdate = true;
1308                         cur.forceBufferUpdate();
1309                 }
1310                 break;
1311         }
1312
1313         case LFUN_GRAPHICS_SET_GROUP: {
1314                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1315                 if (!ins)
1316                         break;
1317
1318                 cur.recordUndo();
1319
1320                 string id = to_utf8(cmd.argument());
1321                 string grp = graphics::getGroupParams(bv->buffer(), id);
1322                 InsetGraphicsParams tmp, inspar = ins->getParams();
1323
1324                 if (id.empty())
1325                         inspar.groupId = to_utf8(cmd.argument());
1326                 else {
1327                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1328                         tmp.filename = inspar.filename;
1329                         inspar = tmp;
1330                 }
1331
1332                 ins->setParams(inspar);
1333                 break;
1334         }
1335
1336         case LFUN_SPACE_INSERT:
1337                 if (cur.paragraph().layout().free_spacing)
1338                         insertChar(cur, ' ');
1339                 else {
1340                         doInsertInset(cur, this, cmd, false, false);
1341                         cur.posForward();
1342                 }
1343                 moveCursor(cur, false);
1344                 break;
1345
1346         case LFUN_SPECIALCHAR_INSERT: {
1347                 string const name = to_utf8(cmd.argument());
1348                 if (name == "hyphenation")
1349                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1350                 else if (name == "allowbreak")
1351                         specialChar(cur, InsetSpecialChar::ALLOWBREAK);
1352                 else if (name == "ligature-break")
1353                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1354                 else if (name == "slash")
1355                         specialChar(cur, InsetSpecialChar::SLASH);
1356                 else if (name == "nobreakdash")
1357                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1358                 else if (name == "dots")
1359                         specialChar(cur, InsetSpecialChar::LDOTS);
1360                 else if (name == "end-of-sentence")
1361                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1362                 else if (name == "menu-separator")
1363                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1364                 else if (name == "lyx")
1365                         specialChar(cur, InsetSpecialChar::PHRASE_LYX);
1366                 else if (name == "tex")
1367                         specialChar(cur, InsetSpecialChar::PHRASE_TEX);
1368                 else if (name == "latex")
1369                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX);
1370                 else if (name == "latex2e")
1371                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX2E);
1372                 else if (name.empty())
1373                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1374                 else
1375                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1376                 break;
1377         }
1378
1379         case LFUN_IPAMACRO_INSERT: {
1380                 string const arg = cmd.getArg(0);
1381                 if (arg == "deco") {
1382                         // Open the inset, and move the current selection
1383                         // inside it.
1384                         doInsertInset(cur, this, cmd, true, true);
1385                         cur.posForward();
1386                         // Some insets are numbered, others are shown in the outline pane so
1387                         // let's update the labels and the toc backend.
1388                         cur.forceBufferUpdate();
1389                         break;
1390                 }
1391                 if (arg == "tone-falling")
1392                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1393                 else if (arg == "tone-rising")
1394                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1395                 else if (arg == "tone-high-rising")
1396                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1397                 else if (arg == "tone-low-rising")
1398                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1399                 else if (arg == "tone-high-rising-falling")
1400                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1401                 else if (arg.empty())
1402                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1403                 else
1404                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1405                 break;
1406         }
1407
1408         case LFUN_WORD_UPCASE:
1409                 changeCase(cur, text_uppercase, cmd.getArg(0) == "partial");
1410                 break;
1411
1412         case LFUN_WORD_LOWCASE:
1413                 changeCase(cur, text_lowercase, cmd.getArg(0) == "partial");
1414                 break;
1415
1416         case LFUN_WORD_CAPITALIZE:
1417                 changeCase(cur, text_capitalization, cmd.getArg(0) == "partial");
1418                 break;
1419
1420         case LFUN_CHARS_TRANSPOSE:
1421                 charsTranspose(cur);
1422                 break;
1423
1424         case LFUN_PASTE: {
1425                 cur.message(_("Paste"));
1426                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), break);
1427                 cap::replaceSelection(cur);
1428
1429                 // without argument?
1430                 string const arg = to_utf8(cmd.argument());
1431                 if (arg.empty()) {
1432                         bool tryGraphics = true;
1433                         if (theClipboard().isInternal())
1434                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1435                         else if (theClipboard().hasTextContents()) {
1436                                 if (pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1437                                                        true, Clipboard::AnyTextType))
1438                                         tryGraphics = false;
1439                         }
1440                         if (tryGraphics && theClipboard().hasGraphicsContents())
1441                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1442                 } else if (isStrUnsignedInt(arg)) {
1443                         // we have a numerical argument
1444                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1445                                        convert<unsigned int>(arg));
1446                 } else if (arg == "html" || arg == "latex") {
1447                         Clipboard::TextType type = (arg == "html") ?
1448                                 Clipboard::HtmlTextType : Clipboard::LaTeXTextType;
1449                         pasteClipboardText(cur, bv->buffer().errorList("Paste"), true, type);
1450                 } else {
1451                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1452                         if (arg == "pdf")
1453                                 type = Clipboard::PdfGraphicsType;
1454                         else if (arg == "png")
1455                                 type = Clipboard::PngGraphicsType;
1456                         else if (arg == "jpeg")
1457                                 type = Clipboard::JpegGraphicsType;
1458                         else if (arg == "linkback")
1459                                 type = Clipboard::LinkBackGraphicsType;
1460                         else if (arg == "emf")
1461                                 type = Clipboard::EmfGraphicsType;
1462                         else if (arg == "wmf")
1463                                 type = Clipboard::WmfGraphicsType;
1464                         else
1465                                 // we also check in getStatus()
1466                                 LYXERR0("Unrecognized graphics type: " << arg);
1467
1468                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1469                 }
1470
1471                 bv->buffer().errors("Paste");
1472                 cur.clearSelection(); // bug 393
1473                 cur.finishUndo();
1474                 break;
1475         }
1476
1477         case LFUN_CUT:
1478                 cutSelection(cur, true, true);
1479                 cur.message(_("Cut"));
1480                 break;
1481
1482         case LFUN_COPY:
1483                 copySelection(cur);
1484                 cur.message(_("Copy"));
1485                 break;
1486
1487         case LFUN_SERVER_GET_XY:
1488                 cur.message(from_utf8(
1489                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1490                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1491                 break;
1492
1493         case LFUN_SERVER_SET_XY: {
1494                 int x = 0;
1495                 int y = 0;
1496                 istringstream is(to_utf8(cmd.argument()));
1497                 is >> x >> y;
1498                 if (!is)
1499                         lyxerr << "SETXY: Could not parse coordinates in '"
1500                                << to_utf8(cmd.argument()) << endl;
1501                 else
1502                         tm->setCursorFromCoordinates(cur, x, y);
1503                 break;
1504         }
1505
1506         case LFUN_SERVER_GET_LAYOUT:
1507                 cur.message(cur.paragraph().layout().name());
1508                 break;
1509
1510         case LFUN_LAYOUT: {
1511                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
1512                 docstring layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
1513                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1514
1515                 Paragraph const & para = cur.paragraph();
1516                 docstring const old_layout = para.layout().name();
1517                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1518
1519                 if (layout.empty())
1520                         layout = tclass.defaultLayoutName();
1521
1522                 if (owner_->forcePlainLayout())
1523                         // in this case only the empty layout is allowed
1524                         layout = tclass.plainLayoutName();
1525                 else if (para.usePlainLayout()) {
1526                         // in this case, default layout maps to empty layout
1527                         if (layout == tclass.defaultLayoutName())
1528                                 layout = tclass.plainLayoutName();
1529                 } else {
1530                         // otherwise, the empty layout maps to the default
1531                         if (layout == tclass.plainLayoutName())
1532                                 layout = tclass.defaultLayoutName();
1533                 }
1534
1535                 bool hasLayout = tclass.hasLayout(layout);
1536
1537                 // If the entry is obsolete, use the new one instead.
1538                 if (hasLayout) {
1539                         docstring const & obs = tclass[layout].obsoleted_by();
1540                         if (!obs.empty())
1541                                 layout = obs;
1542                 }
1543
1544                 if (!hasLayout) {
1545                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1546                                 from_utf8(N_(" not known")));
1547                         break;
1548                 }
1549
1550                 bool change_layout = (old_layout != layout);
1551
1552                 if (!change_layout && cur.selection() &&
1553                         cur.selBegin().pit() != cur.selEnd().pit())
1554                 {
1555                         pit_type spit = cur.selBegin().pit();
1556                         pit_type epit = cur.selEnd().pit() + 1;
1557                         while (spit != epit) {
1558                                 if (pars_[spit].layout().name() != old_layout) {
1559                                         change_layout = true;
1560                                         break;
1561                                 }
1562                                 ++spit;
1563                         }
1564                 }
1565
1566                 if (change_layout) {
1567                         setLayout(cur, layout);
1568                         if (cur.pit() > 0 && !ignoreautonests) {
1569                                 set<docstring> const & autonests =
1570                                                 pars_[cur.pit() - 1].layout().autonests();
1571                                 set<docstring> const & autonested =
1572                                                 pars_[cur.pit()].layout().isAutonestedBy();
1573                                 if (autonests.find(layout) != autonests.end()
1574                                                 || autonested.find(old_layout) != autonested.end())
1575                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1576                         }
1577                 }
1578
1579                 Layout::LaTeXArgMap args = tclass[layout].args();
1580                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1581                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1582                 for (; lait != laend; ++lait) {
1583                         Layout::latexarg arg = (*lait).second;
1584                         if (arg.autoinsert) {
1585                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, (*lait).first);
1586                                 lyx::dispatch(cmd2);
1587                         }
1588                 }
1589
1590                 break;
1591         }
1592
1593         case LFUN_ENVIRONMENT_SPLIT: {
1594                 bool const outer = cmd.argument() == "outer";
1595                 bool const previous = cmd.argument() == "previous";
1596                 bool const before = cmd.argument() == "before";
1597                 bool const normal = cmd.argument().empty();
1598                 Paragraph const & para = cur.paragraph();
1599                 docstring layout;
1600                 if (para.layout().isEnvironment())
1601                         layout = para.layout().name();
1602                 depth_type split_depth = cur.paragraph().params().depth();
1603                 depth_type nextpar_depth = 0;
1604                 if (outer || previous) {
1605                         // check if we have an environment in our scope
1606                         pit_type pit = cur.pit();
1607                         Paragraph cpar = pars_[pit];
1608                         while (true) {
1609                                 if (pit == 0)
1610                                         break;
1611                                 --pit;
1612                                 cpar = pars_[pit];
1613                                 if (layout.empty() && previous
1614                                     && cpar.layout().isEnvironment()
1615                                     && cpar.params().depth() <= split_depth)
1616                                         layout = cpar.layout().name();
1617                                 if (cpar.params().depth() < split_depth
1618                                     && cpar.layout().isEnvironment()) {
1619                                                 if (!previous)
1620                                                         layout = cpar.layout().name();
1621                                                 split_depth = cpar.params().depth();
1622                                 }
1623                                 if (cpar.params().depth() == 0)
1624                                         break;
1625                         }
1626                 }
1627                 if ((outer || normal) && cur.pit() < cur.lastpit()) {
1628                         // save nesting of following paragraph
1629                         Paragraph cpar = pars_[cur.pit() + 1];
1630                         nextpar_depth = cpar.params().depth();
1631                 }
1632                 if (before)
1633                         cur.top().setPitPos(cur.pit(), 0);
1634                 if (before || cur.pos() > 0)
1635                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1636                 else if (previous && cur.nextInset() && cur.nextInset()->lyxCode() == SEPARATOR_CODE)
1637                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1638                 if (outer) {
1639                         while (cur.paragraph().params().depth() > split_depth)
1640                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1641                 }
1642                 DocumentClass const & tc = bv->buffer().params().documentClass();
1643                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
1644                                           + from_ascii("\" ignoreautonests")));
1645                 // FIXME: Bibitem mess!
1646                 if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
1647                         lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
1648                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1649                 if (before) {
1650                         cur.backwardPos();
1651                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1652                         while (cur.paragraph().params().depth() < split_depth)
1653                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1654                 }
1655                 else
1656                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1657                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1658                 if ((outer || normal) && nextpar_depth > 0) {
1659                         // restore nesting of following paragraph
1660                         DocIterator scur = cur;
1661                         depth_type const max_depth = cur.paragraph().params().depth() + 1;
1662                         cur.forwardPar();
1663                         while (cur.paragraph().params().depth() < min(nextpar_depth, max_depth))
1664                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1665                         cur.setCursor(scur);
1666                 }
1667
1668                 break;
1669         }
1670
1671         case LFUN_CLIPBOARD_PASTE:
1672                 cap::replaceSelection(cur);
1673                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1674                                cmd.argument() == "paragraph");
1675                 bv->buffer().errors("Paste");
1676                 break;
1677
1678         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1679                 cap::replaceSelection(cur);
1680                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1681                 break;
1682
1683         case LFUN_PRIMARY_SELECTION_PASTE:
1684                 cap::replaceSelection(cur);
1685                 pasteString(cur, theSelection().get(),
1686                             cmd.argument() == "paragraph");
1687                 break;
1688
1689         case LFUN_SELECTION_PASTE:
1690                 // Copy the selection buffer to the clipboard stack,
1691                 // because we want it to appear in the "Edit->Paste
1692                 // recent" menu.
1693                 cap::replaceSelection(cur);
1694                 cap::copySelectionToStack();
1695                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1696                 bv->buffer().errors("Paste");
1697                 break;
1698
1699         case LFUN_QUOTE_INSERT: {
1700                 cap::replaceSelection(cur);
1701                 cur.recordUndo();
1702
1703                 Paragraph const & par = cur.paragraph();
1704                 pos_type pos = cur.pos();
1705                 // Ignore deleted text before cursor
1706                 while (pos > 0 && par.isDeleted(pos - 1))
1707                         --pos;
1708
1709                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1710
1711                 // Guess quote side.
1712                 // A space triggers an opening quote. This is passed if the preceding
1713                 // char/inset is a space or at paragraph start.
1714                 char_type c = ' ';
1715                 if (pos > 0 && !par.isSpace(pos - 1)) {
1716                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1717                                 // If an opening double quotation mark precedes, and this
1718                                 // is a single quote, make it opening as well
1719                                 InsetQuotes & ins =
1720                                         static_cast<InsetQuotes &>(*cur.prevInset());
1721                                 string const type = ins.getType();
1722                                 if (!suffixIs(type, "ld") || !inner)
1723                                         c = par.getChar(pos - 1);
1724                         }
1725                         else if (!cur.prevInset()
1726                             || (cur.prevInset() && cur.prevInset()->isChar()))
1727                                 // If a char precedes, pass that and let InsetQuote decide
1728                                 c = par.getChar(pos - 1);
1729                         else {
1730                                 while (pos > 0) {
1731                                         if (par.getInset(pos - 1)
1732                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1733                                                 // skip "invisible" insets
1734                                                 --pos;
1735                                                 continue;
1736                                         }
1737                                         c = par.getChar(pos - 1);
1738                                         break;
1739                                 }
1740                         }
1741                 }
1742                 InsetQuotesParams::QuoteLevel const quote_level = inner
1743                                 ? InsetQuotesParams::SecondaryQuotes : InsetQuotesParams::PrimaryQuotes;
1744                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1745                 cur.buffer()->updateBuffer();
1746                 cur.posForward();
1747                 break;
1748         }
1749
1750         case LFUN_DATE_INSERT: {
1751                 string const format = cmd.argument().empty()
1752                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1753                 string const time = formatted_time(current_time(), format);
1754                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1755                 break;
1756         }
1757
1758         case LFUN_MOUSE_TRIPLE:
1759                 if (cmd.button() == mouse_button::button1) {
1760                         tm->cursorHome(cur);
1761                         cur.resetAnchor();
1762                         tm->cursorEnd(cur);
1763                         cur.setSelection();
1764                         bv->cursor() = cur;
1765                 }
1766                 break;
1767
1768         case LFUN_MOUSE_DOUBLE:
1769                 if (cmd.button() == mouse_button::button1) {
1770                         selectWord(cur, WHOLE_WORD);
1771                         bv->cursor() = cur;
1772                 }
1773                 break;
1774
1775         // Single-click on work area
1776         case LFUN_MOUSE_PRESS: {
1777                 // We are not marking a selection with the keyboard in any case.
1778                 Cursor & bvcur = cur.bv().cursor();
1779                 bvcur.setMark(false);
1780                 switch (cmd.button()) {
1781                 case mouse_button::button1:
1782                         if (!bvcur.selection())
1783                                 // Set the cursor
1784                                 bvcur.resetAnchor();
1785                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1786                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1787                         if (bvcur.wordSelection())
1788                                 selectWord(bvcur, WHOLE_WORD);
1789                         break;
1790
1791                 case mouse_button::button2:
1792                         if (lyxrc.mouse_middlebutton_paste) {
1793                                 // Middle mouse pasting.
1794                                 bv->mouseSetCursor(cur);
1795                                 lyx::dispatch(
1796                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1797                                                     "selection-paste ; primary-selection-paste paragraph"));
1798                         }
1799                         cur.noScreenUpdate();
1800                         break;
1801
1802                 case mouse_button::button3: {
1803                         // Don't do anything if we right-click a
1804                         // selection, a context menu will popup.
1805                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1806                             && cur < bvcur.selectionEnd()) {
1807                                 cur.noScreenUpdate();
1808                                 return;
1809                         }
1810                         if (!bv->mouseSetCursor(cur, false))
1811                                 cur.screenUpdateFlags(Update::FitCursor);
1812                         break;
1813                 }
1814
1815                 default:
1816                         break;
1817                 } // switch (cmd.button())
1818                 break;
1819         }
1820         case LFUN_MOUSE_MOTION: {
1821                 // Mouse motion with right or middle mouse do nothing for now.
1822                 if (cmd.button() != mouse_button::button1) {
1823                         cur.noScreenUpdate();
1824                         return;
1825                 }
1826                 // ignore motions deeper nested than the real anchor
1827                 Cursor & bvcur = cur.bv().cursor();
1828                 if (!bvcur.realAnchor().hasPart(cur)) {
1829                         cur.undispatched();
1830                         break;
1831                 }
1832                 CursorSlice old = bvcur.top();
1833
1834                 int const wh = bv->workHeight();
1835                 int const y = max(0, min(wh - 1, cmd.y()));
1836
1837                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1838                 cur.setTargetX(cmd.x());
1839                 // Don't allow selecting a separator inset
1840                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1841                         cur.posBackward();
1842                 if (cmd.y() >= wh)
1843                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1844                 else if (cmd.y() < 0)
1845                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1846                 // This is to allow jumping over large insets
1847                 if (cur.top() == old) {
1848                         if (cmd.y() >= wh)
1849                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1850                         else if (cmd.y() < 0)
1851                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1852                 }
1853                 // We continue with our existing selection or start a new one, so don't
1854                 // reset the anchor.
1855                 bvcur.setCursor(cur);
1856                 bvcur.selection(true);
1857                 bvcur.setCurrentFont();
1858                 if (cur.top() == old) {
1859                         // We didn't move one iota, so no need to update the screen.
1860                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1861                         //cur.noScreenUpdate();
1862                         return;
1863                 }
1864                 break;
1865         }
1866
1867         case LFUN_MOUSE_RELEASE:
1868                 switch (cmd.button()) {
1869                 case mouse_button::button1:
1870                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1871                         // If there is a new selection, update persistent selection;
1872                         // otherwise, single click does not clear persistent selection
1873                         // buffer.
1874                         if (cur.selection()) {
1875                                 // Finish selection. If double click,
1876                                 // cur is moved to the end of word by
1877                                 // selectWord but bvcur is current
1878                                 // mouse position.
1879                                 cur.bv().cursor().setSelection();
1880                                 // We might have removed an empty but drawn selection
1881                                 // (probably a margin)
1882                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1883                         } else
1884                                 cur.noScreenUpdate();
1885                         // FIXME: We could try to handle drag and drop of selection here.
1886                         return;
1887
1888                 case mouse_button::button2:
1889                         // Middle mouse pasting is handled at mouse press time,
1890                         // see LFUN_MOUSE_PRESS.
1891                         cur.noScreenUpdate();
1892                         return;
1893
1894                 case mouse_button::button3:
1895                         // Cursor was set at LFUN_MOUSE_PRESS time.
1896                         // FIXME: If there is a selection we could try to handle a special
1897                         // drag & drop context menu.
1898                         cur.noScreenUpdate();
1899                         return;
1900
1901                 case mouse_button::none:
1902                 case mouse_button::button4:
1903                 case mouse_button::button5:
1904                         break;
1905                 } // switch (cmd.button())
1906
1907                 break;
1908
1909         case LFUN_SELF_INSERT: {
1910                 if (cmd.argument().empty())
1911                         break;
1912
1913                 // Automatically delete the currently selected
1914                 // text and replace it with what is being
1915                 // typed in now. Depends on lyxrc settings
1916                 // "auto_region_delete", which defaults to
1917                 // true (on).
1918
1919                 if (lyxrc.auto_region_delete && cur.selection())
1920                         cutSelection(cur, false, false);
1921
1922                 cur.clearSelection();
1923
1924                 docstring::const_iterator cit = cmd.argument().begin();
1925                 docstring::const_iterator const end = cmd.argument().end();
1926                 for (; cit != end; ++cit)
1927                         bv->translateAndInsert(*cit, this, cur);
1928
1929                 cur.resetAnchor();
1930                 moveCursor(cur, false);
1931                 cur.markNewWordPosition();
1932                 bv->bookmarkEditPosition();
1933                 break;
1934         }
1935
1936         case LFUN_HREF_INSERT: {
1937                 docstring content = cmd.argument();
1938                 if (content.empty() && cur.selection())
1939                         content = cur.selectionAsString(false);
1940
1941                 InsetCommandParams p(HYPERLINK_CODE);
1942                 if (!content.empty()){
1943                         // if it looks like a link, we'll put it as target,
1944                         // otherwise as name (bug #8792).
1945
1946                         // We can't do:
1947                         //   regex_match(to_utf8(content), matches, link_re)
1948                         // because smatch stores pointers to the substrings rather
1949                         // than making copies of them. And those pointers become
1950                         // invalid after regex_match returns, since it is then
1951                         // being given a temporary object. (Thanks to Georg for
1952                         // figuring that out.)
1953                         regex const link_re("^([a-z]+):.*");
1954                         smatch matches;
1955                         string const c = to_utf8(lowercase(content));
1956
1957                         if (c.substr(0,7) == "mailto:") {
1958                                 p["target"] = content;
1959                                 p["type"] = from_ascii("mailto:");
1960                         } else if (regex_match(c, matches, link_re)) {
1961                                 p["target"] = content;
1962                                 string protocol = matches.str(1);
1963                                 if (protocol == "file")
1964                                         p["type"] = from_ascii("file:");
1965                         } else
1966                                 p["name"] = content;
1967                 }
1968                 string const data = InsetCommand::params2string(p);
1969
1970                 // we need to have a target. if we already have one, then
1971                 // that gets used at the default for the name, too, which
1972                 // is probably what is wanted.
1973                 if (p["target"].empty()) {
1974                         bv->showDialog("href", data);
1975                 } else {
1976                         FuncRequest fr(LFUN_INSET_INSERT, data);
1977                         dispatch(cur, fr);
1978                 }
1979                 break;
1980         }
1981
1982         case LFUN_LABEL_INSERT: {
1983                 InsetCommandParams p(LABEL_CODE);
1984                 // Try to generate a valid label
1985                 p["name"] = (cmd.argument().empty()) ?
1986                         cur.getPossibleLabel() :
1987                         cmd.argument();
1988                 string const data = InsetCommand::params2string(p);
1989
1990                 if (cmd.argument().empty()) {
1991                         bv->showDialog("label", data);
1992                 } else {
1993                         FuncRequest fr(LFUN_INSET_INSERT, data);
1994                         dispatch(cur, fr);
1995                 }
1996                 break;
1997         }
1998
1999         case LFUN_INFO_INSERT: {
2000                 Inset * inset;
2001                 if (cmd.argument().empty() && cur.selection()) {
2002                         // if command argument is empty use current selection as parameter.
2003                         docstring ds = cur.selectionAsString(false);
2004                         cutSelection(cur, true, false);
2005                         FuncRequest cmd0(cmd, ds);
2006                         inset = createInset(cur.buffer(), cmd0);
2007                 } else {
2008                         inset = createInset(cur.buffer(), cmd);
2009                 }
2010                 if (!inset)
2011                         break;
2012                 cur.recordUndo();
2013                 insertInset(cur, inset);
2014                 cur.forceBufferUpdate();
2015                 cur.posForward();
2016                 break;
2017         }
2018         case LFUN_CAPTION_INSERT:
2019         case LFUN_FOOTNOTE_INSERT:
2020         case LFUN_NOTE_INSERT:
2021         case LFUN_BOX_INSERT:
2022         case LFUN_BRANCH_INSERT:
2023         case LFUN_PHANTOM_INSERT:
2024         case LFUN_ERT_INSERT:
2025         case LFUN_LISTING_INSERT:
2026         case LFUN_MARGINALNOTE_INSERT:
2027         case LFUN_ARGUMENT_INSERT:
2028         case LFUN_INDEX_INSERT:
2029         case LFUN_PREVIEW_INSERT:
2030         case LFUN_SCRIPT_INSERT:
2031         case LFUN_IPA_INSERT:
2032                 // Open the inset, and move the current selection
2033                 // inside it.
2034                 doInsertInset(cur, this, cmd, true, true);
2035                 cur.posForward();
2036                 // Some insets are numbered, others are shown in the outline pane so
2037                 // let's update the labels and the toc backend.
2038                 cur.forceBufferUpdate();
2039                 break;
2040
2041         case LFUN_FLEX_INSERT: {
2042                 // Open the inset, and move the current selection
2043                 // inside it.
2044                 bool const sel = cur.selection();
2045                 doInsertInset(cur, this, cmd, true, true);
2046                 // Insert auto-insert arguments
2047                 bool autoargs = false;
2048                 Layout::LaTeXArgMap args = cur.inset().getLayout().latexargs();
2049                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
2050                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
2051                 for (; lait != laend; ++lait) {
2052                         Layout::latexarg arg = (*lait).second;
2053                         if (arg.autoinsert) {
2054                                 // The cursor might have been invalidated by the replaceSelection.
2055                                 cur.buffer()->changed(true);
2056                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, (*lait).first);
2057                                 lyx::dispatch(cmd2);
2058                                 autoargs = true;
2059                         }
2060                 }
2061                 if (!autoargs) {
2062                         if (sel)
2063                                 cur.leaveInset(cur.inset());
2064                         cur.posForward();
2065                 }
2066                 // Some insets are numbered, others are shown in the outline pane so
2067                 // let's update the labels and the toc backend.
2068                 cur.forceBufferUpdate();
2069                 break;
2070         }
2071
2072         case LFUN_TABULAR_INSERT:
2073                 // if there were no arguments, just open the dialog
2074                 if (doInsertInset(cur, this, cmd, false, true))
2075                         cur.posForward();
2076                 else
2077                         bv->showDialog("tabularcreate");
2078
2079                 break;
2080
2081         case LFUN_FLOAT_INSERT:
2082         case LFUN_FLOAT_WIDE_INSERT:
2083         case LFUN_WRAP_INSERT: {
2084                 // will some content be moved into the inset?
2085                 bool const content = cur.selection();
2086                 // does the content consist of multiple paragraphs?
2087                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2088
2089                 doInsertInset(cur, this, cmd, true, true);
2090                 cur.posForward();
2091
2092                 // If some single-par content is moved into the inset,
2093                 // doInsertInset puts the cursor outside the inset.
2094                 // To insert the caption we put it back into the inset.
2095                 // FIXME cleanup doInsertInset to avoid such dances!
2096                 if (content && singlepar)
2097                         cur.backwardPos();
2098
2099                 ParagraphList & pars = cur.text()->paragraphs();
2100
2101                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2102
2103                 // add a separate paragraph for the caption inset
2104                 pars.push_back(Paragraph());
2105                 pars.back().setInsetOwner(&cur.text()->inset());
2106                 pars.back().setPlainOrDefaultLayout(tclass);
2107                 int cap_pit = pars.size() - 1;
2108
2109                 // if an empty inset was created, we create an additional empty
2110                 // paragraph at the bottom so that the user can choose where to put
2111                 // the graphics (or table).
2112                 if (!content) {
2113                         pars.push_back(Paragraph());
2114                         pars.back().setInsetOwner(&cur.text()->inset());
2115                         pars.back().setPlainOrDefaultLayout(tclass);
2116                 }
2117
2118                 // reposition the cursor to the caption
2119                 cur.pit() = cap_pit;
2120                 cur.pos() = 0;
2121                 // FIXME: This Text/Cursor dispatch handling is a mess!
2122                 // We cannot use Cursor::dispatch here it needs access to up to
2123                 // date metrics.
2124                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2125                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2126                 cur.forceBufferUpdate();
2127                 cur.screenUpdateFlags(Update::Force);
2128                 // FIXME: When leaving the Float (or Wrap) inset we should
2129                 // delete any empty paragraph left above or below the
2130                 // caption.
2131                 break;
2132         }
2133
2134         case LFUN_NOMENCL_INSERT: {
2135                 InsetCommandParams p(NOMENCL_CODE);
2136                 if (cmd.argument().empty())
2137                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
2138                 else
2139                         p["symbol"] = cmd.argument();
2140                 string const data = InsetCommand::params2string(p);
2141                 bv->showDialog("nomenclature", data);
2142                 break;
2143         }
2144
2145         case LFUN_INDEX_PRINT: {
2146                 InsetCommandParams p(INDEX_PRINT_CODE);
2147                 if (cmd.argument().empty())
2148                         p["type"] = from_ascii("idx");
2149                 else
2150                         p["type"] = cmd.argument();
2151                 string const data = InsetCommand::params2string(p);
2152                 FuncRequest fr(LFUN_INSET_INSERT, data);
2153                 dispatch(cur, fr);
2154                 break;
2155         }
2156
2157         case LFUN_NOMENCL_PRINT:
2158         case LFUN_NEWPAGE_INSERT:
2159                 // do nothing fancy
2160                 doInsertInset(cur, this, cmd, false, false);
2161                 cur.posForward();
2162                 break;
2163
2164         case LFUN_SEPARATOR_INSERT: {
2165                 doInsertInset(cur, this, cmd, false, false);
2166                 cur.posForward();
2167                 // remove a following space
2168                 Paragraph & par = cur.paragraph();
2169                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2170                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2171                 break;
2172         }
2173
2174         case LFUN_DEPTH_DECREMENT:
2175                 changeDepth(cur, DEC_DEPTH);
2176                 break;
2177
2178         case LFUN_DEPTH_INCREMENT:
2179                 changeDepth(cur, INC_DEPTH);
2180                 break;
2181
2182         case LFUN_REGEXP_MODE:
2183                 regexpDispatch(cur, cmd);
2184                 break;
2185
2186         case LFUN_MATH_MODE: {
2187                 if (cmd.argument() == "on" || cmd.argument() == "") {
2188                         // don't pass "on" as argument
2189                         // (it would appear literally in the first cell)
2190                         docstring sel = cur.selectionAsString(false);
2191                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2192                         // create a macro template if we see "\\newcommand" somewhere, and
2193                         // an ordinary formula otherwise
2194                         if (!sel.empty()
2195                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2196                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2197                                         || sel.find(from_ascii("\\def")) != string::npos)
2198                                 && macro->fromString(sel)) {
2199                                 cur.recordUndo();
2200                                 replaceSelection(cur);
2201                                 cur.insert(macro);
2202                         } else {
2203                                 // no meaningful macro template was found
2204                                 delete macro;
2205                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2206                         }
2207                 } else
2208                         // The argument is meaningful
2209                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2210                         // has a different meaning in math mode
2211                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2212                 break;
2213         }
2214
2215         case LFUN_MATH_MACRO:
2216                 if (cmd.argument().empty())
2217                         cur.errorMessage(from_utf8(N_("Missing argument")));
2218                 else {
2219                         cur.recordUndo();
2220                         string s = to_utf8(cmd.argument());
2221                         string const s1 = token(s, ' ', 1);
2222                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2223                         string const s2 = token(s, ' ', 2);
2224                         MacroType type = MacroTypeNewcommand;
2225                         if (s2 == "def")
2226                                 type = MacroTypeDef;
2227                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2228                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2229                         inset->setBuffer(bv->buffer());
2230                         insertInset(cur, inset);
2231
2232                         // enter macro inset and select the name
2233                         cur.push(*inset);
2234                         cur.top().pos() = cur.top().lastpos();
2235                         cur.resetAnchor();
2236                         cur.selection(true);
2237                         cur.top().pos() = 0;
2238                 }
2239                 break;
2240
2241         case LFUN_MATH_DISPLAY:
2242         case LFUN_MATH_SUBSCRIPT:
2243         case LFUN_MATH_SUPERSCRIPT:
2244         case LFUN_MATH_INSERT:
2245         case LFUN_MATH_AMS_MATRIX:
2246         case LFUN_MATH_MATRIX:
2247         case LFUN_MATH_DELIM:
2248         case LFUN_MATH_BIGDELIM:
2249                 mathDispatch(cur, cmd);
2250                 break;
2251
2252         case LFUN_FONT_EMPH: {
2253                 Font font(ignore_font, ignore_language);
2254                 font.fontInfo().setEmph(FONT_TOGGLE);
2255                 toggleAndShow(cur, this, font);
2256                 break;
2257         }
2258
2259         case LFUN_FONT_ITAL: {
2260                 Font font(ignore_font, ignore_language);
2261                 font.fontInfo().setShape(ITALIC_SHAPE);
2262                 toggleAndShow(cur, this, font);
2263                 break;
2264         }
2265
2266         case LFUN_FONT_BOLD:
2267         case LFUN_FONT_BOLDSYMBOL: {
2268                 Font font(ignore_font, ignore_language);
2269                 font.fontInfo().setSeries(BOLD_SERIES);
2270                 toggleAndShow(cur, this, font);
2271                 break;
2272         }
2273
2274         case LFUN_FONT_NOUN: {
2275                 Font font(ignore_font, ignore_language);
2276                 font.fontInfo().setNoun(FONT_TOGGLE);
2277                 toggleAndShow(cur, this, font);
2278                 break;
2279         }
2280
2281         case LFUN_FONT_TYPEWRITER: {
2282                 Font font(ignore_font, ignore_language);
2283                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2284                 toggleAndShow(cur, this, font);
2285                 break;
2286         }
2287
2288         case LFUN_FONT_SANS: {
2289                 Font font(ignore_font, ignore_language);
2290                 font.fontInfo().setFamily(SANS_FAMILY);
2291                 toggleAndShow(cur, this, font);
2292                 break;
2293         }
2294
2295         case LFUN_FONT_ROMAN: {
2296                 Font font(ignore_font, ignore_language);
2297                 font.fontInfo().setFamily(ROMAN_FAMILY);
2298                 toggleAndShow(cur, this, font);
2299                 break;
2300         }
2301
2302         case LFUN_FONT_DEFAULT: {
2303                 Font font(inherit_font, ignore_language);
2304                 toggleAndShow(cur, this, font);
2305                 break;
2306         }
2307
2308         case LFUN_FONT_STRIKEOUT: {
2309                 Font font(ignore_font, ignore_language);
2310                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2311                 toggleAndShow(cur, this, font);
2312                 break;
2313         }
2314
2315         case LFUN_FONT_CROSSOUT: {
2316                 Font font(ignore_font, ignore_language);
2317                 font.fontInfo().setXout(FONT_TOGGLE);
2318                 toggleAndShow(cur, this, font);
2319                 break;
2320         }
2321
2322         case LFUN_FONT_UNDERUNDERLINE: {
2323                 Font font(ignore_font, ignore_language);
2324                 font.fontInfo().setUuline(FONT_TOGGLE);
2325                 toggleAndShow(cur, this, font);
2326                 break;
2327         }
2328
2329         case LFUN_FONT_UNDERWAVE: {
2330                 Font font(ignore_font, ignore_language);
2331                 font.fontInfo().setUwave(FONT_TOGGLE);
2332                 toggleAndShow(cur, this, font);
2333                 break;
2334         }
2335
2336         case LFUN_FONT_UNDERLINE: {
2337                 Font font(ignore_font, ignore_language);
2338                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2339                 toggleAndShow(cur, this, font);
2340                 break;
2341         }
2342
2343         case LFUN_FONT_SIZE: {
2344                 Font font(ignore_font, ignore_language);
2345                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2346                 toggleAndShow(cur, this, font);
2347                 break;
2348         }
2349
2350         case LFUN_LANGUAGE: {
2351                 string const lang_arg = cmd.getArg(0);
2352                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2353                 Language const * lang =
2354                         reset ? reset_language
2355                               : languages.getLanguage(lang_arg);
2356                 // we allow reset_language, which is 0, but only if it
2357                 // was requested via empty or "reset" arg.
2358                 if (!lang && !reset)
2359                         break;
2360                 bool const toggle = (cmd.getArg(1) != "set");
2361                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2362                 Font font(ignore_font, lang);
2363                 toggleAndShow(cur, this, font, toggle);
2364                 break;
2365         }
2366
2367         case LFUN_TEXTSTYLE_APPLY:
2368                 toggleAndShow(cur, this, freefont, toggleall);
2369                 cur.message(_("Character set"));
2370                 break;
2371
2372         // Set the freefont using the contents of \param data dispatched from
2373         // the frontends and apply it at the current cursor location.
2374         case LFUN_TEXTSTYLE_UPDATE: {
2375                 Font font;
2376                 bool toggle;
2377                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2378                         freefont = font;
2379                         toggleall = toggle;
2380                         toggleAndShow(cur, this, freefont, toggleall);
2381                         cur.message(_("Character set"));
2382                 } else {
2383                         lyxerr << "Argument not ok";
2384                 }
2385                 break;
2386         }
2387
2388         case LFUN_FINISHED_LEFT:
2389                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2390                 // We're leaving an inset, going left. If the inset is LTR, we're
2391                 // leaving from the front, so we should not move (remain at --- but
2392                 // not in --- the inset). If the inset is RTL, move left, without
2393                 // entering the inset itself; i.e., move to after the inset.
2394                 if (cur.paragraph().getFontSettings(
2395                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2396                         cursorVisLeft(cur, true);
2397                 break;
2398
2399         case LFUN_FINISHED_RIGHT:
2400                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2401                 // We're leaving an inset, going right. If the inset is RTL, we're
2402                 // leaving from the front, so we should not move (remain at --- but
2403                 // not in --- the inset). If the inset is LTR, move right, without
2404                 // entering the inset itself; i.e., move to after the inset.
2405                 if (!cur.paragraph().getFontSettings(
2406                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2407                         cursorVisRight(cur, true);
2408                 break;
2409
2410         case LFUN_FINISHED_BACKWARD:
2411                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2412                 cur.setCurrentFont();
2413                 break;
2414
2415         case LFUN_FINISHED_FORWARD:
2416                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2417                 ++cur.pos();
2418                 cur.setCurrentFont();
2419                 break;
2420
2421         case LFUN_LAYOUT_PARAGRAPH: {
2422                 string data;
2423                 params2string(cur.paragraph(), data);
2424                 data = "show\n" + data;
2425                 bv->showDialog("paragraph", data);
2426                 break;
2427         }
2428
2429         case LFUN_PARAGRAPH_UPDATE: {
2430                 string data;
2431                 params2string(cur.paragraph(), data);
2432
2433                 // Will the paragraph accept changes from the dialog?
2434                 bool const accept =
2435                         cur.inset().allowParagraphCustomization(cur.idx());
2436
2437                 data = "update " + convert<string>(accept) + '\n' + data;
2438                 bv->updateDialog("paragraph", data);
2439                 break;
2440         }
2441
2442         case LFUN_ACCENT_UMLAUT:
2443         case LFUN_ACCENT_CIRCUMFLEX:
2444         case LFUN_ACCENT_GRAVE:
2445         case LFUN_ACCENT_ACUTE:
2446         case LFUN_ACCENT_TILDE:
2447         case LFUN_ACCENT_PERISPOMENI:
2448         case LFUN_ACCENT_CEDILLA:
2449         case LFUN_ACCENT_MACRON:
2450         case LFUN_ACCENT_DOT:
2451         case LFUN_ACCENT_UNDERDOT:
2452         case LFUN_ACCENT_UNDERBAR:
2453         case LFUN_ACCENT_CARON:
2454         case LFUN_ACCENT_BREVE:
2455         case LFUN_ACCENT_TIE:
2456         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2457         case LFUN_ACCENT_CIRCLE:
2458         case LFUN_ACCENT_OGONEK:
2459                 theApp()->handleKeyFunc(cmd.action());
2460                 if (!cmd.argument().empty())
2461                         // FIXME: Are all these characters encoded in one byte in utf8?
2462                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2463                 cur.screenUpdateFlags(Update::FitCursor);
2464                 break;
2465
2466         case LFUN_FLOAT_LIST_INSERT: {
2467                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2468                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2469                         cur.recordUndo();
2470                         if (cur.selection())
2471                                 cutSelection(cur, true, false);
2472                         breakParagraph(cur);
2473
2474                         if (cur.lastpos() != 0) {
2475                                 cursorBackward(cur);
2476                                 breakParagraph(cur);
2477                         }
2478
2479                         docstring const laystr = cur.inset().usePlainLayout() ?
2480                                 tclass.plainLayoutName() :
2481                                 tclass.defaultLayoutName();
2482                         setLayout(cur, laystr);
2483                         ParagraphParameters p;
2484                         // FIXME If this call were replaced with one to clearParagraphParams(),
2485                         // then we could get rid of this method altogether.
2486                         setParagraphs(cur, p);
2487                         // FIXME This should be simplified when InsetFloatList takes a
2488                         // Buffer in its constructor.
2489                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2490                         ifl->setBuffer(bv->buffer());
2491                         insertInset(cur, ifl);
2492                         cur.posForward();
2493                 } else {
2494                         lyxerr << "Non-existent float type: "
2495                                << to_utf8(cmd.argument()) << endl;
2496                 }
2497                 break;
2498         }
2499
2500         case LFUN_CHANGE_ACCEPT: {
2501                 acceptOrRejectChanges(cur, ACCEPT);
2502                 break;
2503         }
2504
2505         case LFUN_CHANGE_REJECT: {
2506                 acceptOrRejectChanges(cur, REJECT);
2507                 break;
2508         }
2509
2510         case LFUN_THESAURUS_ENTRY: {
2511                 Language const * language = cur.getFont().language();
2512                 docstring arg = cmd.argument();
2513                 if (arg.empty()) {
2514                         arg = cur.selectionAsString(false);
2515                         // FIXME
2516                         if (arg.size() > 100 || arg.empty()) {
2517                                 // Get word or selection
2518                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2519                                 arg = cur.selectionAsString(false);
2520                                 arg += " lang=" + from_ascii(language->lang());
2521                         }
2522                 } else {
2523                         string lang = cmd.getArg(1);
2524                         // This duplicates the code in GuiThesaurus::initialiseParams
2525                         if (prefixIs(lang, "lang=")) {
2526                                 language = languages.getLanguage(lang.substr(5));
2527                                 if (!language)
2528                                         language = cur.getFont().language();
2529                         }
2530                 }
2531                 string lang = language->code();
2532                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2533                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2534                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2535                                         _("The path to the thesaurus directory has not been specified.\n"
2536                                           "The thesaurus is not functional.\n"
2537                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2538                                           "instructions."));
2539                 }
2540                 bv->showDialog("thesaurus", to_utf8(arg));
2541                 break;
2542         }
2543
2544         case LFUN_SPELLING_ADD: {
2545                 Language const * language = getLanguage(cur, cmd.getArg(1));
2546                 docstring word = from_utf8(cmd.getArg(0));
2547                 if (word.empty()) {
2548                         word = cur.selectionAsString(false);
2549                         // FIXME
2550                         if (word.size() > 100 || word.empty()) {
2551                                 // Get word or selection
2552                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2553                                 word = cur.selectionAsString(false);
2554                         }
2555                 }
2556                 WordLangTuple wl(word, language);
2557                 theSpellChecker()->insert(wl);
2558                 break;
2559         }
2560
2561         case LFUN_SPELLING_IGNORE: {
2562                 Language const * language = getLanguage(cur, cmd.getArg(1));
2563                 docstring word = from_utf8(cmd.getArg(0));
2564                 if (word.empty()) {
2565                         word = cur.selectionAsString(false);
2566                         // FIXME
2567                         if (word.size() > 100 || word.empty()) {
2568                                 // Get word or selection
2569                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2570                                 word = cur.selectionAsString(false);
2571                         }
2572                 }
2573                 WordLangTuple wl(word, language);
2574                 theSpellChecker()->accept(wl);
2575                 break;
2576         }
2577
2578         case LFUN_SPELLING_REMOVE: {
2579                 Language const * language = getLanguage(cur, cmd.getArg(1));
2580                 docstring word = from_utf8(cmd.getArg(0));
2581                 if (word.empty()) {
2582                         word = cur.selectionAsString(false);
2583                         // FIXME
2584                         if (word.size() > 100 || word.empty()) {
2585                                 // Get word or selection
2586                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2587                                 word = cur.selectionAsString(false);
2588                         }
2589                 }
2590                 WordLangTuple wl(word, language);
2591                 theSpellChecker()->remove(wl);
2592                 break;
2593         }
2594
2595         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2596                 // Given data, an encoding of the ParagraphParameters
2597                 // generated in the Paragraph dialog, this function sets
2598                 // the current paragraph, or currently selected paragraphs,
2599                 // appropriately.
2600                 // NOTE: This function overrides all existing settings.
2601                 setParagraphs(cur, cmd.argument());
2602                 cur.message(_("Paragraph layout set"));
2603                 break;
2604         }
2605
2606         case LFUN_PARAGRAPH_PARAMS: {
2607                 // Given data, an encoding of the ParagraphParameters as we'd
2608                 // find them in a LyX file, this function modifies the current paragraph,
2609                 // or currently selected paragraphs.
2610                 // NOTE: This function only modifies, and does not override, existing
2611                 // settings.
2612                 setParagraphs(cur, cmd.argument(), true);
2613                 cur.message(_("Paragraph layout set"));
2614                 break;
2615         }
2616
2617         case LFUN_ESCAPE:
2618                 if (cur.selection()) {
2619                         cur.selection(false);
2620                 } else {
2621                         cur.undispatched();
2622                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2623                         // correct, but I'm not 100% sure -- dov, 071019
2624                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2625                 }
2626                 break;
2627
2628         case LFUN_OUTLINE_UP:
2629                 outline(OutlineUp, cur, this);
2630                 setCursor(cur, cur.pit(), 0);
2631                 cur.forceBufferUpdate();
2632                 needsUpdate = true;
2633                 break;
2634
2635         case LFUN_OUTLINE_DOWN:
2636                 outline(OutlineDown, cur, this);
2637                 setCursor(cur, cur.pit(), 0);
2638                 cur.forceBufferUpdate();
2639                 needsUpdate = true;
2640                 break;
2641
2642         case LFUN_OUTLINE_IN:
2643                 outline(OutlineIn, cur, this);
2644                 cur.forceBufferUpdate();
2645                 needsUpdate = true;
2646                 break;
2647
2648         case LFUN_OUTLINE_OUT:
2649                 outline(OutlineOut, cur, this);
2650                 cur.forceBufferUpdate();
2651                 needsUpdate = true;
2652                 break;
2653
2654         case LFUN_SERVER_GET_STATISTICS:
2655                 {
2656                         DocIterator from, to;
2657                         if (cur.selection()) {
2658                                 from = cur.selectionBegin();
2659                                 to = cur.selectionEnd();
2660                         } else {
2661                                 from = doc_iterator_begin(cur.buffer());
2662                                 to = doc_iterator_end(cur.buffer());
2663                         }
2664
2665                         cur.buffer()->updateStatistics(from, to);
2666                         string const arg0 = cmd.getArg(0);
2667                         if (arg0 == "words") {
2668                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2669                         } else if (arg0 == "chars") {
2670                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2671                         } else if (arg0 == "chars-space") {
2672                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2673                         } else {
2674                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2675                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2676                                 + convert<docstring>(cur.buffer()->charCount(true)));
2677                         }
2678                 }
2679                 break;
2680
2681         default:
2682                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2683                 cur.undispatched();
2684                 break;
2685         }
2686
2687         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2688
2689         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2690                 // Check for misspelled text
2691                 // The redraw is useful because of the painting of
2692                 // misspelled markers depends on the cursor position.
2693                 // Trigger a redraw for cursor moves inside misspelled text.
2694                 if (!cur.inTexted()) {
2695                         // move from regular text to math
2696                         needsUpdate = last_misspelled;
2697                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2698                         // move inside regular text
2699                         needsUpdate = last_misspelled
2700                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2701                 }
2702         }
2703
2704         // FIXME: The cursor flag is reset two lines below
2705         // so we need to check here if some of the LFUN did touch that.
2706         // for now only Text::erase() and Text::backspace() do that.
2707         // The plan is to verify all the LFUNs and then to remove this
2708         // singleParUpdate boolean altogether.
2709         if (cur.result().screenUpdate() & Update::Force) {
2710                 singleParUpdate = false;
2711                 needsUpdate = true;
2712         }
2713
2714         // FIXME: the following code should go in favor of fine grained
2715         // update flag treatment.
2716         if (singleParUpdate) {
2717                 // Inserting characters does not change par height in general. So, try
2718                 // to update _only_ this paragraph. BufferView will detect if a full
2719                 // metrics update is needed anyway.
2720                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2721                 return;
2722         }
2723         if (!needsUpdate
2724             && &oldTopSlice.inset() == &cur.inset()
2725             && oldTopSlice.idx() == cur.idx()
2726             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2727             && !cur.selection())
2728                 // FIXME: it would be better if we could just do this
2729                 //
2730                 //if (cur.result().update() != Update::FitCursor)
2731                 //      cur.noScreenUpdate();
2732                 //
2733                 // But some LFUNs do not set Update::FitCursor when needed, so we
2734                 // do it for all. This is not very harmfull as FitCursor will provoke
2735                 // a full redraw only if needed but still, a proper review of all LFUN
2736                 // should be done and this needsUpdate boolean can then be removed.
2737                 cur.screenUpdateFlags(Update::FitCursor);
2738         else
2739                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2740 }
2741
2742
2743 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2744                         FuncStatus & flag) const
2745 {
2746         LBUFERR(this == cur.text());
2747
2748         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2749         bool enable = true;
2750         bool allow_in_passthru = false;
2751         InsetCode code = NO_CODE;
2752
2753         switch (cmd.action()) {
2754
2755         case LFUN_DEPTH_DECREMENT:
2756                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2757                 break;
2758
2759         case LFUN_DEPTH_INCREMENT:
2760                 enable = changeDepthAllowed(cur, INC_DEPTH);
2761                 break;
2762
2763         case LFUN_APPENDIX:
2764                 // FIXME We really should not allow this to be put, e.g.,
2765                 // in a footnote, or in ERT. But it would make sense in a
2766                 // branch, so I'm not sure what to do.
2767                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2768                 break;
2769
2770         case LFUN_DIALOG_SHOW_NEW_INSET:
2771                 if (cmd.argument() == "bibitem")
2772                         code = BIBITEM_CODE;
2773                 else if (cmd.argument() == "bibtex") {
2774                         code = BIBTEX_CODE;
2775                         // not allowed in description items
2776                         enable = !inDescriptionItem(cur);
2777                 }
2778                 else if (cmd.argument() == "box")
2779                         code = BOX_CODE;
2780                 else if (cmd.argument() == "branch")
2781                         code = BRANCH_CODE;
2782                 else if (cmd.argument() == "citation")
2783                         code = CITE_CODE;
2784                 else if (cmd.argument() == "ert")
2785                         code = ERT_CODE;
2786                 else if (cmd.argument() == "external")
2787                         code = EXTERNAL_CODE;
2788                 else if (cmd.argument() == "float")
2789                         code = FLOAT_CODE;
2790                 else if (cmd.argument() == "graphics")
2791                         code = GRAPHICS_CODE;
2792                 else if (cmd.argument() == "href")
2793                         code = HYPERLINK_CODE;
2794                 else if (cmd.argument() == "include")
2795                         code = INCLUDE_CODE;
2796                 else if (cmd.argument() == "index")
2797                         code = INDEX_CODE;
2798                 else if (cmd.argument() == "index_print")
2799                         code = INDEX_PRINT_CODE;
2800                 else if (cmd.argument() == "listings")
2801                         code = LISTINGS_CODE;
2802                 else if (cmd.argument() == "mathspace")
2803                         code = MATH_HULL_CODE;
2804                 else if (cmd.argument() == "nomenclature")
2805                         code = NOMENCL_CODE;
2806                 else if (cmd.argument() == "nomencl_print")
2807                         code = NOMENCL_PRINT_CODE;
2808                 else if (cmd.argument() == "label")
2809                         code = LABEL_CODE;
2810                 else if (cmd.argument() == "line")
2811                         code = LINE_CODE;
2812                 else if (cmd.argument() == "note")
2813                         code = NOTE_CODE;
2814                 else if (cmd.argument() == "phantom")
2815                         code = PHANTOM_CODE;
2816                 else if (cmd.argument() == "ref")
2817                         code = REF_CODE;
2818                 else if (cmd.argument() == "space")
2819                         code = SPACE_CODE;
2820                 else if (cmd.argument() == "toc")
2821                         code = TOC_CODE;
2822                 else if (cmd.argument() == "vspace")
2823                         code = VSPACE_CODE;
2824                 else if (cmd.argument() == "wrap")
2825                         code = WRAP_CODE;
2826                 break;
2827
2828         case LFUN_ERT_INSERT:
2829                 code = ERT_CODE;
2830                 break;
2831         case LFUN_LISTING_INSERT:
2832                 code = LISTINGS_CODE;
2833                 // not allowed in description items
2834                 enable = !inDescriptionItem(cur);
2835                 break;
2836         case LFUN_FOOTNOTE_INSERT:
2837                 code = FOOT_CODE;
2838                 break;
2839         case LFUN_TABULAR_INSERT:
2840                 code = TABULAR_CODE;
2841                 break;
2842         case LFUN_MARGINALNOTE_INSERT:
2843                 code = MARGIN_CODE;
2844                 break;
2845         case LFUN_FLOAT_INSERT:
2846         case LFUN_FLOAT_WIDE_INSERT:
2847                 // FIXME: If there is a selection, we should check whether there
2848                 // are floats in the selection, but this has performance issues, see
2849                 // LFUN_CHANGE_ACCEPT/REJECT.
2850                 code = FLOAT_CODE;
2851                 if (inDescriptionItem(cur))
2852                         // not allowed in description items
2853                         enable = false;
2854                 else {
2855                         InsetCode const inset_code = cur.inset().lyxCode();
2856
2857                         // algorithm floats cannot be put in another float
2858                         if (to_utf8(cmd.argument()) == "algorithm") {
2859                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2860                                 break;
2861                         }
2862
2863                         // for figures and tables: only allow in another
2864                         // float or wrap if it is of the same type and
2865                         // not a subfloat already
2866                         if(cur.inset().lyxCode() == code) {
2867                                 InsetFloat const & ins =
2868                                         static_cast<InsetFloat const &>(cur.inset());
2869                                 enable = ins.params().type == to_utf8(cmd.argument())
2870                                         && !ins.params().subfloat;
2871                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2872                                 InsetWrap const & ins =
2873                                         static_cast<InsetWrap const &>(cur.inset());
2874                                 enable = ins.params().type == to_utf8(cmd.argument());
2875                         }
2876                 }
2877                 break;
2878         case LFUN_WRAP_INSERT:
2879                 code = WRAP_CODE;
2880                 // not allowed in description items
2881                 enable = !inDescriptionItem(cur);
2882                 break;
2883         case LFUN_FLOAT_LIST_INSERT: {
2884                 code = FLOAT_LIST_CODE;
2885                 // not allowed in description items
2886                 enable = !inDescriptionItem(cur);
2887                 if (enable) {
2888                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2889                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2890                         // make sure we know about such floats
2891                         if (cit == floats.end() ||
2892                                         // and that we know how to generate a list of them
2893                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2894                                 flag.setUnknown(true);
2895                                 // probably not necessary, but...
2896                                 enable = false;
2897                         }
2898                 }
2899                 break;
2900         }
2901         case LFUN_CAPTION_INSERT: {
2902                 code = CAPTION_CODE;
2903                 string arg = cmd.getArg(0);
2904                 bool varia = arg != "Unnumbered"
2905                         && cur.inset().allowsCaptionVariation(arg);
2906                 // not allowed in description items,
2907                 // and in specific insets
2908                 enable = !inDescriptionItem(cur)
2909                         && (varia || arg.empty() || arg == "Standard");
2910                 break;
2911         }
2912         case LFUN_NOTE_INSERT:
2913                 code = NOTE_CODE;
2914                 break;
2915         case LFUN_FLEX_INSERT: {
2916                 code = FLEX_CODE;
2917                 string s = cmd.getArg(0);
2918                 InsetLayout il =
2919                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2920                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2921                     il.lyxtype() != InsetLayout::CUSTOM &&
2922                     il.lyxtype() != InsetLayout::ELEMENT &&
2923                     il.lyxtype ()!= InsetLayout::STANDARD)
2924                         enable = false;
2925                 break;
2926                 }
2927         case LFUN_BOX_INSERT:
2928                 code = BOX_CODE;
2929                 break;
2930         case LFUN_BRANCH_INSERT:
2931                 code = BRANCH_CODE;
2932                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2933                     && cur.buffer()->params().branchlist().empty())
2934                         enable = false;
2935                 break;
2936         case LFUN_IPA_INSERT:
2937                 code = IPA_CODE;
2938                 break;
2939         case LFUN_PHANTOM_INSERT:
2940                 code = PHANTOM_CODE;
2941                 break;
2942         case LFUN_LABEL_INSERT:
2943                 code = LABEL_CODE;
2944                 break;
2945         case LFUN_INFO_INSERT:
2946                 code = INFO_CODE;
2947                 break;
2948         case LFUN_ARGUMENT_INSERT: {
2949                 code = ARG_CODE;
2950                 allow_in_passthru = true;
2951                 string const arg = cmd.getArg(0);
2952                 if (arg.empty()) {
2953                         enable = false;
2954                         break;
2955                 }
2956                 Layout const & lay = cur.paragraph().layout();
2957                 Layout::LaTeXArgMap args = lay.args();
2958                 Layout::LaTeXArgMap::const_iterator const lait =
2959                                 args.find(arg);
2960                 if (lait != args.end()) {
2961                         enable = true;
2962                         pit_type pit = cur.pit();
2963                         pit_type lastpit = cur.pit();
2964                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
2965                                 // In a sequence of "merged" environment layouts, we only allow
2966                                 // non-item arguments once.
2967                                 lastpit = cur.lastpit();
2968                                 // get the first paragraph in sequence with this layout
2969                                 depth_type const current_depth = cur.paragraph().params().depth();
2970                                 while (true) {
2971                                         if (pit == 0)
2972                                                 break;
2973                                         Paragraph cpar = pars_[pit - 1];
2974                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
2975                                                 --pit;
2976                                         else
2977                                                 break;
2978                                 }
2979                         }
2980                         for (; pit <= lastpit; ++pit) {
2981                                 if (pars_[pit].layout() != lay)
2982                                         break;
2983                                 for (auto const & table : pars_[pit].insetList())
2984                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
2985                                                 if (ins->name() == arg) {
2986                                                         // we have this already
2987                                                         enable = false;
2988                                                         break;
2989                                                 }
2990                         }
2991                 } else
2992                         enable = false;
2993                 break;
2994         }
2995         case LFUN_INDEX_INSERT:
2996                 code = INDEX_CODE;
2997                 break;
2998         case LFUN_INDEX_PRINT:
2999                 code = INDEX_PRINT_CODE;
3000                 // not allowed in description items
3001                 enable = !inDescriptionItem(cur);
3002                 break;
3003         case LFUN_NOMENCL_INSERT:
3004                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3005                         enable = false;
3006                         break;
3007                 }
3008                 code = NOMENCL_CODE;
3009                 break;
3010         case LFUN_NOMENCL_PRINT:
3011                 code = NOMENCL_PRINT_CODE;
3012                 // not allowed in description items
3013                 enable = !inDescriptionItem(cur);
3014                 break;
3015         case LFUN_HREF_INSERT:
3016                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3017                         enable = false;
3018                         break;
3019                 }
3020                 code = HYPERLINK_CODE;
3021                 break;
3022         case LFUN_IPAMACRO_INSERT: {
3023                 string const arg = cmd.getArg(0);
3024                 if (arg == "deco")
3025                         code = IPADECO_CODE;
3026                 else
3027                         code = IPACHAR_CODE;
3028                 break;
3029         }
3030         case LFUN_QUOTE_INSERT:
3031                 // always allow this, since we will inset a raw quote
3032                 // if an inset is not allowed.
3033                 allow_in_passthru = true;
3034                 break;
3035         case LFUN_SPECIALCHAR_INSERT:
3036                 code = SPECIALCHAR_CODE;
3037                 break;
3038         case LFUN_SPACE_INSERT:
3039                 // slight hack: we know this is allowed in math mode
3040                 if (cur.inTexted())
3041                         code = SPACE_CODE;
3042                 break;
3043         case LFUN_PREVIEW_INSERT:
3044                 code = PREVIEW_CODE;
3045                 break;
3046         case LFUN_SCRIPT_INSERT:
3047                 code = SCRIPT_CODE;
3048                 break;
3049
3050         case LFUN_MATH_INSERT:
3051         case LFUN_MATH_AMS_MATRIX:
3052         case LFUN_MATH_MATRIX:
3053         case LFUN_MATH_DELIM:
3054         case LFUN_MATH_BIGDELIM:
3055         case LFUN_MATH_DISPLAY:
3056         case LFUN_MATH_MODE:
3057         case LFUN_MATH_MACRO:
3058         case LFUN_MATH_SUBSCRIPT:
3059         case LFUN_MATH_SUPERSCRIPT:
3060                 code = MATH_HULL_CODE;
3061                 break;
3062
3063         case LFUN_REGEXP_MODE:
3064                 code = MATH_HULL_CODE;
3065                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3066                 break;
3067
3068         case LFUN_INSET_MODIFY:
3069                 // We need to disable this, because we may get called for a
3070                 // tabular cell via
3071                 // InsetTabular::getStatus() -> InsetText::getStatus()
3072                 // and we don't handle LFUN_INSET_MODIFY.
3073                 enable = false;
3074                 break;
3075
3076         case LFUN_FONT_EMPH:
3077                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3078                 enable = !cur.paragraph().isPassThru();
3079                 break;
3080
3081         case LFUN_FONT_ITAL:
3082                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3083                 enable = !cur.paragraph().isPassThru();
3084                 break;
3085
3086         case LFUN_FONT_NOUN:
3087                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3088                 enable = !cur.paragraph().isPassThru();
3089                 break;
3090
3091         case LFUN_FONT_BOLD:
3092         case LFUN_FONT_BOLDSYMBOL:
3093                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3094                 enable = !cur.paragraph().isPassThru();
3095                 break;
3096
3097         case LFUN_FONT_SANS:
3098                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3099                 enable = !cur.paragraph().isPassThru();
3100                 break;
3101
3102         case LFUN_FONT_ROMAN:
3103                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3104                 enable = !cur.paragraph().isPassThru();
3105                 break;
3106
3107         case LFUN_FONT_TYPEWRITER:
3108                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3109                 enable = !cur.paragraph().isPassThru();
3110                 break;
3111
3112         case LFUN_CUT:
3113         case LFUN_COPY:
3114                 enable = cur.selection();
3115                 break;
3116
3117         case LFUN_PASTE: {
3118                 if (cmd.argument().empty()) {
3119                         if (theClipboard().isInternal())
3120                                 enable = cap::numberOfSelections() > 0;
3121                         else
3122                                 enable = !theClipboard().empty();
3123                         break;
3124                 }
3125
3126                 // we have an argument
3127                 string const arg = to_utf8(cmd.argument());
3128                 if (isStrUnsignedInt(arg)) {
3129                         // it's a number and therefore means the internal stack
3130                         unsigned int n = convert<unsigned int>(arg);
3131                         enable = cap::numberOfSelections() > n;
3132                         break;
3133                 }
3134
3135                 // explicit text type?
3136                 if (arg == "html") {
3137                         // Do not enable for PlainTextType, since some tidying in the
3138                         // frontend is needed for HTML, which is too unsafe for plain text.
3139                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3140                         break;
3141                 } else if (arg == "latex") {
3142                         // LaTeX is usually not available on the clipboard with
3143                         // the correct MIME type, but in plain text.
3144                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3145                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3146                         break;
3147                 }
3148
3149                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3150                 if (arg == "pdf")
3151                         type = Clipboard::PdfGraphicsType;
3152                 else if (arg == "png")
3153                         type = Clipboard::PngGraphicsType;
3154                 else if (arg == "jpeg")
3155                         type = Clipboard::JpegGraphicsType;
3156                 else if (arg == "linkback")
3157                         type = Clipboard::LinkBackGraphicsType;
3158                 else if (arg == "emf")
3159                         type = Clipboard::EmfGraphicsType;
3160                 else if (arg == "wmf")
3161                         type = Clipboard::WmfGraphicsType;
3162                 else {
3163                         // unknown argument
3164                         LYXERR0("Unrecognized graphics type: " << arg);
3165                         // we don't want to assert if the user just mistyped the LFUN
3166                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3167                         enable = false;
3168                         break;
3169                 }
3170                 enable = theClipboard().hasGraphicsContents(type);
3171                 break;
3172         }
3173
3174         case LFUN_CLIPBOARD_PASTE:
3175         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3176                 enable = !theClipboard().empty();
3177                 break;
3178
3179         case LFUN_PRIMARY_SELECTION_PASTE:
3180                 enable = cur.selection() || !theSelection().empty();
3181                 break;
3182
3183         case LFUN_SELECTION_PASTE:
3184                 enable = cap::selection();
3185                 break;
3186
3187         case LFUN_PARAGRAPH_MOVE_UP:
3188                 enable = cur.pit() > 0 && !cur.selection();
3189                 break;
3190
3191         case LFUN_PARAGRAPH_MOVE_DOWN:
3192                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3193                 break;
3194
3195         case LFUN_CHANGE_ACCEPT:
3196         case LFUN_CHANGE_REJECT:
3197                 // In principle, these LFUNs should only be enabled if there
3198                 // is a change at the current position/in the current selection.
3199                 // However, without proper optimizations, this will inevitably
3200                 // result in unacceptable performance - just imagine a user who
3201                 // wants to select the complete content of a long document.
3202                 if (!cur.selection())
3203                         enable = cur.paragraph().isChanged(cur.pos());
3204                 else
3205                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
3206                         // for selections.
3207                         enable = true;
3208                 break;
3209
3210         case LFUN_OUTLINE_UP:
3211         case LFUN_OUTLINE_DOWN:
3212         case LFUN_OUTLINE_IN:
3213         case LFUN_OUTLINE_OUT:
3214                 // FIXME: LyX is not ready for outlining within inset.
3215                 enable = isMainText()
3216                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3217                 break;
3218
3219         case LFUN_NEWLINE_INSERT:
3220                 // LaTeX restrictions (labels or empty par)
3221                 enable = !cur.paragraph().isPassThru()
3222                         && cur.pos() > cur.paragraph().beginOfBody();
3223                 break;
3224
3225         case LFUN_SEPARATOR_INSERT:
3226                 // Always enabled for now
3227                 enable = true;
3228                 break;
3229
3230         case LFUN_TAB_INSERT:
3231         case LFUN_TAB_DELETE:
3232                 enable = cur.paragraph().isPassThru();
3233                 break;
3234
3235         case LFUN_GRAPHICS_SET_GROUP: {
3236                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3237                 if (!ins)
3238                         enable = false;
3239                 else
3240                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3241                 break;
3242         }
3243
3244         case LFUN_NEWPAGE_INSERT:
3245                 // not allowed in description items
3246                 code = NEWPAGE_CODE;
3247                 enable = !inDescriptionItem(cur);
3248                 break;
3249
3250         case LFUN_DATE_INSERT: {
3251                 string const format = cmd.argument().empty()
3252                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
3253                 enable = support::os::is_valid_strftime(format);
3254                 break;
3255         }
3256
3257         case LFUN_LANGUAGE:
3258                 enable = !cur.paragraph().isPassThru();
3259                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3260                 break;
3261
3262         case LFUN_PARAGRAPH_BREAK:
3263                 enable = inset().allowMultiPar();
3264                 break;
3265
3266         case LFUN_SPELLING_ADD:
3267         case LFUN_SPELLING_IGNORE:
3268         case LFUN_SPELLING_REMOVE:
3269                 enable = theSpellChecker() != NULL;
3270                 if (enable && !cmd.getArg(1).empty()) {
3271                         // validate explicitly given language
3272                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3273                         enable &= lang != NULL;
3274                 }
3275                 break;
3276
3277         case LFUN_LAYOUT: {
3278                 DocumentClass const & tclass = cur.buffer()->params().documentClass();
3279                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3280                 docstring layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3281                 if (layout.empty())
3282                         layout = tclass.defaultLayoutName();
3283                 enable = !owner_->forcePlainLayout() && tclass.hasLayout(layout);
3284
3285                 flag.setOnOff(layout == cur.paragraph().layout().name());
3286                 break;
3287         }
3288
3289         case LFUN_ENVIRONMENT_SPLIT: {
3290                 if (cmd.argument() == "outer") {
3291                         // check if we have an environment in our nesting hierarchy
3292                         bool res = false;
3293                         depth_type const current_depth = cur.paragraph().params().depth();
3294                         pit_type pit = cur.pit();
3295                         Paragraph cpar = pars_[pit];
3296                         while (true) {
3297                                 if (pit == 0 || cpar.params().depth() == 0)
3298                                         break;
3299                                 --pit;
3300                                 cpar = pars_[pit];
3301                                 if (cpar.params().depth() < current_depth)
3302                                         res = cpar.layout().isEnvironment();
3303                         }
3304                         enable = res;
3305                         break;
3306                 }
3307                 else if (cmd.argument() == "previous") {
3308                         // look if we have an environment in the previous par
3309                         pit_type pit = cur.pit();
3310                         Paragraph cpar = pars_[pit];
3311                         if (pit > 0) {
3312                                 --pit;
3313                                 cpar = pars_[pit];
3314                                 enable = cpar.layout().isEnvironment();
3315                                 break;
3316                         }
3317                         enable = false;
3318                         break;
3319                 }
3320                 else if (cur.paragraph().layout().isEnvironment()) {
3321                         enable = cmd.argument() == "before"
3322                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3323                         break;
3324                 }
3325                 enable = false;
3326                 break;
3327         }
3328
3329         case LFUN_LAYOUT_PARAGRAPH:
3330         case LFUN_PARAGRAPH_PARAMS:
3331         case LFUN_PARAGRAPH_PARAMS_APPLY:
3332         case LFUN_PARAGRAPH_UPDATE:
3333                 enable = owner_->allowParagraphCustomization();
3334                 break;
3335
3336         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3337         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3338         //  that cannot be handled by LaTeX but must be converted according
3339         //  to the definition in lib/unicodesymbols?
3340         case LFUN_ACCENT_ACUTE:
3341         case LFUN_ACCENT_BREVE:
3342         case LFUN_ACCENT_CARON:
3343         case LFUN_ACCENT_CEDILLA:
3344         case LFUN_ACCENT_CIRCLE:
3345         case LFUN_ACCENT_CIRCUMFLEX:
3346         case LFUN_ACCENT_DOT:
3347         case LFUN_ACCENT_GRAVE:
3348         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3349         case LFUN_ACCENT_MACRON:
3350         case LFUN_ACCENT_OGONEK:
3351         case LFUN_ACCENT_TIE:
3352         case LFUN_ACCENT_TILDE:
3353         case LFUN_ACCENT_PERISPOMENI:
3354         case LFUN_ACCENT_UMLAUT:
3355         case LFUN_ACCENT_UNDERBAR:
3356         case LFUN_ACCENT_UNDERDOT:
3357         case LFUN_FONT_DEFAULT:
3358         case LFUN_FONT_FRAK:
3359         case LFUN_FONT_SIZE:
3360         case LFUN_FONT_STATE:
3361         case LFUN_FONT_UNDERLINE:
3362         case LFUN_FONT_STRIKEOUT:
3363         case LFUN_FONT_CROSSOUT:
3364         case LFUN_FONT_UNDERUNDERLINE:
3365         case LFUN_FONT_UNDERWAVE:
3366         case LFUN_TEXTSTYLE_APPLY:
3367         case LFUN_TEXTSTYLE_UPDATE:
3368                 enable = !cur.paragraph().isPassThru();
3369                 break;
3370
3371         case LFUN_WORD_DELETE_FORWARD:
3372         case LFUN_WORD_DELETE_BACKWARD:
3373         case LFUN_LINE_DELETE_FORWARD:
3374         case LFUN_WORD_FORWARD:
3375         case LFUN_WORD_BACKWARD:
3376         case LFUN_WORD_RIGHT:
3377         case LFUN_WORD_LEFT:
3378         case LFUN_CHAR_FORWARD:
3379         case LFUN_CHAR_FORWARD_SELECT:
3380         case LFUN_CHAR_BACKWARD:
3381         case LFUN_CHAR_BACKWARD_SELECT:
3382         case LFUN_CHAR_LEFT:
3383         case LFUN_CHAR_LEFT_SELECT:
3384         case LFUN_CHAR_RIGHT:
3385         case LFUN_CHAR_RIGHT_SELECT:
3386         case LFUN_UP:
3387         case LFUN_UP_SELECT:
3388         case LFUN_DOWN:
3389         case LFUN_DOWN_SELECT:
3390         case LFUN_PARAGRAPH_UP_SELECT:
3391         case LFUN_PARAGRAPH_DOWN_SELECT:
3392         case LFUN_LINE_BEGIN_SELECT:
3393         case LFUN_LINE_END_SELECT:
3394         case LFUN_WORD_FORWARD_SELECT:
3395         case LFUN_WORD_BACKWARD_SELECT:
3396         case LFUN_WORD_RIGHT_SELECT:
3397         case LFUN_WORD_LEFT_SELECT:
3398         case LFUN_WORD_SELECT:
3399         case LFUN_SECTION_SELECT:
3400         case LFUN_BUFFER_BEGIN:
3401         case LFUN_BUFFER_END:
3402         case LFUN_BUFFER_BEGIN_SELECT:
3403         case LFUN_BUFFER_END_SELECT:
3404         case LFUN_INSET_BEGIN:
3405         case LFUN_INSET_END:
3406         case LFUN_INSET_BEGIN_SELECT:
3407         case LFUN_INSET_END_SELECT:
3408         case LFUN_PARAGRAPH_UP:
3409         case LFUN_PARAGRAPH_DOWN:
3410         case LFUN_LINE_BEGIN:
3411         case LFUN_LINE_END:
3412         case LFUN_CHAR_DELETE_FORWARD:
3413         case LFUN_CHAR_DELETE_BACKWARD:
3414         case LFUN_WORD_UPCASE:
3415         case LFUN_WORD_LOWCASE:
3416         case LFUN_WORD_CAPITALIZE:
3417         case LFUN_CHARS_TRANSPOSE:
3418         case LFUN_SERVER_GET_XY:
3419         case LFUN_SERVER_SET_XY:
3420         case LFUN_SERVER_GET_LAYOUT:
3421         case LFUN_SELF_INSERT:
3422         case LFUN_UNICODE_INSERT:
3423         case LFUN_THESAURUS_ENTRY:
3424         case LFUN_ESCAPE:
3425         case LFUN_SERVER_GET_STATISTICS:
3426                 // these are handled in our dispatch()
3427                 enable = true;
3428                 break;
3429
3430         case LFUN_INSET_INSERT: {
3431                 string const type = cmd.getArg(0);
3432                 if (type == "toc") {
3433                         code = TOC_CODE;
3434                         // not allowed in description items
3435                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3436                         enable = !inDescriptionItem(cur);
3437                 } else {
3438                         enable = true;
3439                 }
3440                 break;
3441         }
3442
3443         default:
3444                 return false;
3445         }
3446
3447         if (code != NO_CODE
3448             && (cur.empty()
3449                 || !cur.inset().insetAllowed(code)
3450                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3451                 enable = false;
3452
3453         flag.setEnabled(enable);
3454         return true;
3455 }
3456
3457
3458 void Text::pasteString(Cursor & cur, docstring const & clip,
3459                 bool asParagraphs)
3460 {
3461         if (!clip.empty()) {
3462                 cur.recordUndo();
3463                 if (asParagraphs)
3464                         insertStringAsParagraphs(cur, clip, cur.current_font);
3465                 else
3466                         insertStringAsLines(cur, clip, cur.current_font);
3467         }
3468 }
3469
3470
3471 // FIXME: an item inset would make things much easier.
3472 bool Text::inDescriptionItem(Cursor & cur) const
3473 {
3474         Paragraph & par = cur.paragraph();
3475         pos_type const pos = cur.pos();
3476         pos_type const body_pos = par.beginOfBody();
3477
3478         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3479             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3480                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3481                 return false;
3482
3483         return (pos < body_pos
3484                 || (pos == body_pos
3485                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3486 }
3487
3488 } // namespace lyx