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