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