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