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