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