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