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