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