]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Fix bug 4166: Crash when middle button click on inset label
[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 "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyXFunc.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include "insets/InsetCollapsable.h"
53 #include "insets/InsetCommand.h"
54 #include "insets/InsetFloatList.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetQuotes.h"
57 #include "insets/InsetSpecialChar.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetInfo.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/gettext.h"
66 #include "support/lstrings.h"
67 #include "support/lyxtime.h"
68
69 #include "mathed/InsetMathHull.h"
70 #include "mathed/MathMacroTemplate.h"
71
72 #include <boost/next_prior.hpp>
73
74 #include <clocale>
75 #include <sstream>
76
77 using namespace std;
78 using namespace lyx::support;
79
80 namespace lyx {
81
82 using cap::copySelection;
83 using cap::cutSelection;
84 using cap::pasteFromStack;
85 using cap::pasteClipboardText;
86 using cap::pasteClipboardGraphics;
87 using cap::replaceSelection;
88
89 // globals...
90 static Font freefont(ignore_font, ignore_language);
91 static bool toggleall = false;
92
93 static void toggleAndShow(Cursor & cur, Text * text,
94         Font const & font, bool toggleall = true)
95 {
96         text->toggleFree(cur, font, toggleall);
97
98         if (font.language() != ignore_language ||
99             font.fontInfo().number() != FONT_IGNORE) {
100                 TextMetrics const & tm = cur.bv().textMetrics(text);
101                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
102                                                        cur.real_current_font))
103                         text->setCursor(cur, cur.pit(), cur.pos(),
104                                         false, !cur.boundary());
105         }
106 }
107
108
109 static void moveCursor(Cursor & cur, bool selecting)
110 {
111         if (selecting || cur.mark())
112                 cur.setSelection();
113 }
114
115
116 static void finishChange(Cursor & cur, bool selecting)
117 {
118         cur.finishUndo();
119         moveCursor(cur, selecting);
120 }
121
122
123 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
124 {
125         cur.recordUndo();
126         docstring sel = cur.selectionAsString(false);
127
128         // It may happen that sel is empty but there is a selection
129         replaceSelection(cur);
130
131         if (sel.empty()) {
132 #ifdef ENABLE_ASSERTIONS
133                 const int old_pos = cur.pos();
134 #endif
135                 cur.insert(new InsetMathHull(hullSimple));
136 #ifdef ENABLE_ASSERTIONS
137                 LASSERT(old_pos == cur.pos(), /**/);
138 #endif
139                 cur.nextInset()->edit(cur, true);
140                 // don't do that also for LFUN_MATH_MODE
141                 // unless you want end up with always changing
142                 // to mathrm when opening an inlined inset --
143                 // I really hate "LyXfunc overloading"...
144                 if (display)
145                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
146                 // Avoid an unnecessary undo step if cmd.argument
147                 // is empty
148                 if (!cmd.argument().empty())
149                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
150                                                  cmd.argument()));
151         } else {
152                 // create a macro if we see "\\newcommand"
153                 // somewhere, and an ordinary formula
154                 // otherwise
155                 if (sel.find(from_ascii("\\newcommand")) == string::npos
156                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
157                                 && sel.find(from_ascii("\\def")) == string::npos)
158                 {
159                         InsetMathHull * formula = new InsetMathHull;
160                         istringstream is(to_utf8(sel));
161                         Lexer lex;
162                         lex.setStream(is);
163                         formula->read(lex);
164                         if (formula->getType() == hullNone)
165                                 // Don't create pseudo formulas if
166                                 // delimiters are left out
167                                 formula->mutate(hullSimple);
168                         cur.insert(formula);
169                 } else {
170                         cur.insert(new MathMacroTemplate(sel));
171                 }
172         }
173         cur.message(from_utf8(N_("Math editor mode")));
174 }
175
176
177 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
178 {
179         cur.recordUndo();
180         cap::replaceSelection(cur);
181         cur.insert(new InsetSpecialChar(kind));
182         cur.posForward();
183 }
184
185
186 static bool doInsertInset(Cursor & cur, Text * text,
187         FuncRequest const & cmd, bool edit, bool pastesel)
188 {
189         Buffer & buffer = cur.bv().buffer();
190         BufferParams const & bparams = buffer.params();
191         Inset * inset = createInset(buffer, cmd);
192         if (!inset)
193                 return false;
194
195         if (InsetCollapsable * ci = inset->asInsetCollapsable())
196                 ci->setLayout(bparams);
197
198         cur.recordUndo();
199         if (cmd.action == LFUN_INDEX_INSERT) {
200                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
201                 text->insertInset(cur, inset);
202                 if (edit)
203                         inset->edit(cur, true);
204                 // Now put this into inset
205                 static_cast<InsetCollapsable *>(inset)->text().insertStringAsParagraphs(cur, ds);
206                 return true;
207         }
208
209         bool gotsel = false;
210         if (cur.selection()) {
211                 cutSelection(cur, false, pastesel);
212                 cur.clearSelection();
213                 gotsel = true;
214         }
215         text->insertInset(cur, inset);
216
217         if (edit)
218                 inset->edit(cur, true);
219
220         if (!gotsel || !pastesel)
221                 return true;
222
223         pasteFromStack(cur, cur.buffer().errorList("Paste"), 0);
224         cur.buffer().errors("Paste");
225         cur.clearSelection(); // bug 393
226         cur.finishUndo();
227         InsetText * insetText = dynamic_cast<InsetText *>(inset);
228         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
229                 // reset first par to default
230                 cur.text()->paragraphs().begin()
231                         ->setPlainOrDefaultLayout(bparams.documentClass());
232                 cur.pos() = 0;
233                 cur.pit() = 0;
234                 // Merge multiple paragraphs -- hack
235                 while (cur.lastpit() > 0)
236                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
237                 cur.leaveInset(*inset);
238         } else {
239                 cur.leaveInset(*inset);
240                 // reset surrounding par to default
241                 DocumentClass const & dc = bparams.documentClass();
242                 docstring const layoutname = inset->usePlainLayout()
243                         ? dc.plainLayoutName()
244                         : dc.defaultLayoutName();
245                 text->setLayout(cur, layoutname);
246         }
247
248         return true;
249 }
250
251
252 string const freefont2string()
253 {
254         return freefont.toString(toggleall);
255 }
256
257
258 /// the type of outline operation
259 enum OutlineOp {
260         OutlineUp, // Move this header with text down
261         OutlineDown,   // Move this header with text up
262         OutlineIn, // Make this header deeper
263         OutlineOut // Make this header shallower
264 };
265
266
267 static void outline(OutlineOp mode, Cursor & cur)
268 {
269         Buffer & buf = cur.buffer();
270         pit_type & pit = cur.pit();
271         ParagraphList & pars = buf.text().paragraphs();
272         ParagraphList::iterator bgn = pars.begin();
273         // The first paragraph of the area to be copied:
274         ParagraphList::iterator start = boost::next(bgn, pit);
275         // The final paragraph of area to be copied:
276         ParagraphList::iterator finish = start;
277         ParagraphList::iterator end = pars.end();
278
279         DocumentClass const & tc = buf.params().documentClass();
280
281         int const thistoclevel = start->layout().toclevel;
282         int toclevel;
283
284         // Move out (down) from this section header
285         if (finish != end)
286                 ++finish;
287         // Seek the one (on same level) below
288         for (; finish != end; ++finish) {
289                 toclevel = finish->layout().toclevel;
290                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel) {
291                         break;
292                 }
293         }
294
295         switch (mode) {
296                 case OutlineUp: {
297                         if (start == pars.begin())
298                                 // Nothing to move.
299                                 return;
300                         ParagraphList::iterator dest = start;
301                         // Move out (up) from this header
302                         if (dest == bgn)
303                                 return;
304                         // Search previous same-level header above
305                         do {
306                                 --dest;
307                                 toclevel = dest->layout().toclevel;
308                         } while(dest != bgn
309                                 && (toclevel == Layout::NOT_IN_TOC
310                                     || toclevel > thistoclevel));
311                         // Not found; do nothing
312                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
313                                 return;
314                         pit_type const newpit = distance(bgn, dest);
315                         pit_type const len = distance(start, finish);
316                         pit_type const deletepit = pit + len;
317                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
318                         pars.insert(dest, start, finish);
319                         start = boost::next(pars.begin(), deletepit);
320                         pit = newpit;
321                         pars.erase(start, finish);
322                         return;
323                 }
324                 case OutlineDown: {
325                         if (finish == end)
326                                 // Nothing to move.
327                                 return;
328                         // Go one down from *this* header:
329                         ParagraphList::iterator dest = boost::next(finish, 1);
330                         // Go further down to find header to insert in front of:
331                         for (; dest != end; ++dest) {
332                                 toclevel = dest->layout().toclevel;
333                                 if (toclevel != Layout::NOT_IN_TOC
334                                     && toclevel <= thistoclevel) {
335                                         break;
336                                 }
337                         }
338                         // One such was found:
339                         pit_type newpit = distance(bgn, dest);
340                         pit_type const len = distance(start, finish);
341                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
342                         pars.insert(dest, start, finish);
343                         start = boost::next(bgn, pit);
344                         pit = newpit - len;
345                         pars.erase(start, finish);
346                         return;
347                 }
348                 case OutlineIn: {
349                         pit_type const len = distance(start, finish);
350                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
351                         for (; start != finish; ++start) {
352                                 toclevel = start->layout().toclevel;
353                                 if (toclevel == Layout::NOT_IN_TOC)
354                                         continue;
355                                 DocumentClass::const_iterator lit = tc.begin();
356                                 DocumentClass::const_iterator len = tc.end();
357                                 for (; lit != len; ++lit) {
358                                         if (lit->toclevel == toclevel + 1 &&
359                                             start->layout().labeltype == lit->labeltype) {
360                                                 start->setLayout(*lit);
361                                                 break;
362                                         }
363                                 }
364                         }
365                         return;
366                 }
367                 case OutlineOut: {
368                         pit_type const len = distance(start, finish);
369                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
370                         for (; start != finish; ++start) {
371                                 toclevel = start->layout().toclevel;
372                                 if (toclevel == Layout::NOT_IN_TOC)
373                                         continue;
374                                 DocumentClass::const_iterator lit = tc.begin();
375                                 DocumentClass::const_iterator len = tc.end();
376                                 for (; lit != len; ++lit) {
377                                         if (lit->toclevel == toclevel - 1 &&
378                                                 start->layout().labeltype == lit->labeltype) {
379                                                         start->setLayout(*lit);
380                                                         break;
381                                         }
382                                 }
383                         }
384                         return;
385                 }
386         }
387 }
388
389
390 void Text::number(Cursor & cur)
391 {
392         FontInfo font = ignore_font;
393         font.setNumber(FONT_TOGGLE);
394         toggleAndShow(cur, this, Font(font, ignore_language));
395 }
396
397
398 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
399 {
400         return par.isRTL(buffer.params());
401 }
402
403
404 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
405 {
406         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
407
408         BufferView * bv = &cur.bv();
409         TextMetrics & tm = bv->textMetrics(this);
410         if (!tm.contains(cur.pit()))
411                 lyx::dispatch(FuncRequest(LFUN_SCREEN_RECENTER));
412
413         // FIXME: We use the update flag to indicates wether a singlePar or a
414         // full screen update is needed. We reset it here but shall we restore it
415         // at the end?
416         cur.noUpdate();
417
418         LASSERT(cur.text() == this, /**/);
419         CursorSlice oldTopSlice = cur.top();
420         bool oldBoundary = cur.boundary();
421         bool sel = cur.selection();
422         // Signals that, even if needsUpdate == false, an update of the
423         // cursor paragraph is required
424         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
425                 LyXAction::SingleParUpdate);
426         // Signals that a full-screen update is required
427         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
428                 LyXAction::NoUpdate) || singleParUpdate);
429
430         switch (cmd.action) {
431
432         case LFUN_PARAGRAPH_MOVE_DOWN: {
433                 pit_type const pit = cur.pit();
434                 recUndo(cur, pit, pit + 1);
435                 cur.finishUndo();
436                 swap(pars_[pit], pars_[pit + 1]);
437                 updateLabels(cur.buffer());
438                 needsUpdate = true;
439                 ++cur.pit();
440                 break;
441         }
442
443         case LFUN_PARAGRAPH_MOVE_UP: {
444                 pit_type const pit = cur.pit();
445                 recUndo(cur, pit - 1, pit);
446                 cur.finishUndo();
447                 swap(pars_[pit], pars_[pit - 1]);
448                 updateLabels(cur.buffer());
449                 --cur.pit();
450                 needsUpdate = true;
451                 break;
452         }
453
454         case LFUN_APPENDIX: {
455                 Paragraph & par = cur.paragraph();
456                 bool start = !par.params().startOfAppendix();
457
458 // FIXME: The code below only makes sense at top level.
459 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
460                 // ensure that we have only one start_of_appendix in this document
461                 // FIXME: this don't work for multipart document!
462                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
463                         if (pars_[tmp].params().startOfAppendix()) {
464                                 recUndo(cur, tmp);
465                                 pars_[tmp].params().startOfAppendix(false);
466                                 break;
467                         }
468                 }
469
470                 cur.recordUndo();
471                 par.params().startOfAppendix(start);
472
473                 // we can set the refreshing parameters now
474                 updateLabels(cur.buffer());
475                 break;
476         }
477
478         case LFUN_WORD_DELETE_FORWARD:
479                 if (cur.selection()) {
480                         cutSelection(cur, true, false);
481                 } else
482                         deleteWordForward(cur);
483                 finishChange(cur, false);
484                 break;
485
486         case LFUN_WORD_DELETE_BACKWARD:
487                 if (cur.selection()) {
488                         cutSelection(cur, true, false);
489                 } else
490                         deleteWordBackward(cur);
491                 finishChange(cur, false);
492                 break;
493
494         case LFUN_LINE_DELETE:
495                 if (cur.selection()) {
496                         cutSelection(cur, true, false);
497                 } else
498                         tm.deleteLineForward(cur);
499                 finishChange(cur, false);
500                 break;
501
502         case LFUN_BUFFER_BEGIN:
503         case LFUN_BUFFER_BEGIN_SELECT:
504                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
505                 if (cur.depth() == 1) {
506                         needsUpdate |= cursorTop(cur);
507                 } else {
508                         cur.undispatched();
509                 }
510                 cur.updateFlags(Update::FitCursor);
511                 break;
512
513         case LFUN_BUFFER_END:
514         case LFUN_BUFFER_END_SELECT:
515                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
516                 if (cur.depth() == 1) {
517                         needsUpdate |= cursorBottom(cur);
518                 } else {
519                         cur.undispatched();
520                 }
521                 cur.updateFlags(Update::FitCursor);
522                 break;
523
524         case LFUN_CHAR_FORWARD:
525         case LFUN_CHAR_FORWARD_SELECT:
526                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
527                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
528                 needsUpdate |= cursorForward(cur);
529
530                 if (!needsUpdate && oldTopSlice == cur.top()
531                                 && cur.boundary() == oldBoundary) {
532                         cur.undispatched();
533                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
534                 }
535                 break;
536
537         case LFUN_CHAR_BACKWARD:
538         case LFUN_CHAR_BACKWARD_SELECT:
539                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
540                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
541                 needsUpdate |= cursorBackward(cur);
542
543                 if (!needsUpdate && oldTopSlice == cur.top()
544                         && cur.boundary() == oldBoundary) {
545                         cur.undispatched();
546                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
547                 }
548                 break;
549
550         case LFUN_CHAR_LEFT:
551         case LFUN_CHAR_LEFT_SELECT:
552                 if (lyxrc.visual_cursor) {
553                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
554                         needsUpdate |= cursorVisLeft(cur);
555                         if (!needsUpdate && oldTopSlice == cur.top()
556                                         && cur.boundary() == oldBoundary) {
557                                 cur.undispatched();
558                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
559                         }
560                 } else {
561                         if (reverseDirectionNeeded(cur)) {
562                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
563                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
564                         } else {
565                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
566                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
567                         }
568                         dispatch(cur, cmd);
569                         return;
570                 }
571                 break;
572
573         case LFUN_CHAR_RIGHT:
574         case LFUN_CHAR_RIGHT_SELECT:
575                 if (lyxrc.visual_cursor) {
576                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
577                         needsUpdate |= cursorVisRight(cur);
578                         if (!needsUpdate && oldTopSlice == cur.top()
579                                         && cur.boundary() == oldBoundary) {
580                                 cur.undispatched();
581                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
582                         }
583                 } else {
584                         if (reverseDirectionNeeded(cur)) {
585                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
586                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
587                         } else {
588                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
589                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
590                         }
591                         dispatch(cur, cmd);
592                         return;
593                 }
594                 break;
595                 
596
597         case LFUN_UP_SELECT:
598         case LFUN_DOWN_SELECT:
599         case LFUN_UP:
600         case LFUN_DOWN: {
601                 // stop/start the selection
602                 bool select = cmd.action == LFUN_DOWN_SELECT ||
603                         cmd.action == LFUN_UP_SELECT;
604                 cur.selHandle(select);
605                 
606                 // move cursor up/down
607                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
608                 bool const successful = cur.upDownInText(up, needsUpdate);
609                 if (successful) {
610                         // redraw if you leave mathed (for the decorations)
611                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
612                 } else
613                         cur.undispatched();
614                 
615                 break;
616         }
617
618         case LFUN_PARAGRAPH_UP:
619         case LFUN_PARAGRAPH_UP_SELECT:
620                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
621                 needsUpdate |= cursorUpParagraph(cur);
622                 break;
623
624         case LFUN_PARAGRAPH_DOWN:
625         case LFUN_PARAGRAPH_DOWN_SELECT:
626                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
627                 needsUpdate |= cursorDownParagraph(cur);
628                 break;
629
630         case LFUN_LINE_BEGIN:
631         case LFUN_LINE_BEGIN_SELECT:
632                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
633                 needsUpdate |= tm.cursorHome(cur);
634                 break;
635
636         case LFUN_LINE_END:
637         case LFUN_LINE_END_SELECT:
638                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
639                 needsUpdate |= tm.cursorEnd(cur);
640                 break;
641
642         case LFUN_WORD_RIGHT:
643         case LFUN_WORD_RIGHT_SELECT:
644                 if (lyxrc.visual_cursor) {
645                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
646                         needsUpdate |= cursorVisRightOneWord(cur);
647                         if (!needsUpdate && oldTopSlice == cur.top()
648                                         && cur.boundary() == oldBoundary) {
649                                 cur.undispatched();
650                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
651                         }
652                 } else {
653                         if (reverseDirectionNeeded(cur)) {
654                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
655                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
656                         } else {
657                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
658                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
659                         }
660                         dispatch(cur, cmd);
661                         return;
662                 }
663                 break;
664
665         case LFUN_WORD_FORWARD:
666         case LFUN_WORD_FORWARD_SELECT:
667                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
668                 needsUpdate |= cursorForwardOneWord(cur);
669                 break;
670
671         case LFUN_WORD_LEFT:
672         case LFUN_WORD_LEFT_SELECT:
673                 if (lyxrc.visual_cursor) {
674                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
675                         needsUpdate |= cursorVisLeftOneWord(cur);
676                         if (!needsUpdate && oldTopSlice == cur.top()
677                                         && cur.boundary() == oldBoundary) {
678                                 cur.undispatched();
679                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
680                         }
681                 } else {
682                         if (reverseDirectionNeeded(cur)) {
683                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
684                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
685                         } else {
686                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
687                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
688                         }
689                         dispatch(cur, cmd);
690                         return;
691                 }
692                 break;
693
694         case LFUN_WORD_BACKWARD:
695         case LFUN_WORD_BACKWARD_SELECT:
696                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
697                 needsUpdate |= cursorBackwardOneWord(cur);
698                 break;
699
700         case LFUN_WORD_SELECT: {
701                 selectWord(cur, WHOLE_WORD);
702                 finishChange(cur, true);
703                 break;
704         }
705
706         case LFUN_NEWLINE_INSERT: {
707                 InsetNewlineParams inp;
708                 docstring arg = cmd.argument();
709                 // this avoids a double undo
710                 // FIXME: should not be needed, ideally
711                 if (!cur.selection())
712                         cur.recordUndo();
713                 cap::replaceSelection(cur);
714                 if (arg == "linebreak")
715                         inp.kind = InsetNewlineParams::LINEBREAK;
716                 else
717                         inp.kind = InsetNewlineParams::NEWLINE;
718                 cur.insert(new InsetNewline(inp));
719                 cur.posForward();
720                 moveCursor(cur, false);
721                 break;
722         }
723         
724         case LFUN_CHAR_DELETE_FORWARD:
725                 if (!cur.selection()) {
726                         if (cur.pos() == cur.paragraph().size())
727                                 // Par boundary, force full-screen update
728                                 singleParUpdate = false;
729                         needsUpdate |= erase(cur);
730                         cur.resetAnchor();
731                         // It is possible to make it a lot faster still
732                         // just comment out the line below...
733                 } else {
734                         cutSelection(cur, true, false);
735                         singleParUpdate = false;
736                 }
737                 moveCursor(cur, false);
738                 break;
739
740         case LFUN_CHAR_DELETE_BACKWARD:
741                 if (!cur.selection()) {
742                         if (bv->getIntl().getTransManager().backspace()) {
743                                 // Par boundary, full-screen update
744                                 if (cur.pos() == 0)
745                                         singleParUpdate = false;
746                                 needsUpdate |= backspace(cur);
747                                 cur.resetAnchor();
748                                 // It is possible to make it a lot faster still
749                                 // just comment out the line below...
750                         }
751                 } else {
752                         cutSelection(cur, true, false);
753                         singleParUpdate = false;
754                 }
755                 break;
756
757         case LFUN_BREAK_PARAGRAPH:
758                 cap::replaceSelection(cur);
759                 breakParagraph(cur, cmd.argument() == "inverse");
760                 cur.resetAnchor();
761                 break;
762
763         // TODO
764         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
765         // as its duties can be performed there. Should it be removed??
766         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
767         case LFUN_PARAGRAPH_SPACING: {
768                 Paragraph & par = cur.paragraph();
769                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
770                 string cur_value = "1.0";
771                 if (cur_spacing == Spacing::Other)
772                         cur_value = par.params().spacing().getValueAsString();
773
774                 istringstream is(to_utf8(cmd.argument()));
775                 string tmp;
776                 is >> tmp;
777                 Spacing::Space new_spacing = cur_spacing;
778                 string new_value = cur_value;
779                 if (tmp.empty()) {
780                         lyxerr << "Missing argument to `paragraph-spacing'"
781                                << endl;
782                 } else if (tmp == "single") {
783                         new_spacing = Spacing::Single;
784                 } else if (tmp == "onehalf") {
785                         new_spacing = Spacing::Onehalf;
786                 } else if (tmp == "double") {
787                         new_spacing = Spacing::Double;
788                 } else if (tmp == "other") {
789                         new_spacing = Spacing::Other;
790                         string tmpval = "0.0";
791                         is >> tmpval;
792                         lyxerr << "new_value = " << tmpval << endl;
793                         if (tmpval != "0.0")
794                                 new_value = tmpval;
795                 } else if (tmp == "default") {
796                         new_spacing = Spacing::Default;
797                 } else {
798                         lyxerr << to_utf8(_("Unknown spacing argument: "))
799                                << to_utf8(cmd.argument()) << endl;
800                 }
801                 if (cur_spacing != new_spacing || cur_value != new_value)
802                         par.params().spacing(Spacing(new_spacing, new_value));
803                 break;
804         }
805
806         case LFUN_INSET_INSERT: {
807                 cur.recordUndo();
808                 Inset * inset = createInset(bv->buffer(), cmd);
809                 if (inset) {
810                         // FIXME (Abdel 01/02/2006):
811                         // What follows would be a partial fix for bug 2154:
812                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
813                         // This automatically put the label inset _after_ a
814                         // numbered section. It should be possible to extend the mechanism
815                         // to any kind of LateX environement.
816                         // The correct way to fix that bug would be at LateX generation.
817                         // I'll let the code here for reference as it could be used for some
818                         // other feature like "automatic labelling".
819                         /*
820                         Paragraph & par = pars_[cur.pit()];
821                         if (inset->lyxCode() == LABEL_CODE
822                                 && par.layout().labeltype == LABEL_COUNTER) {
823                                 // Go to the end of the paragraph
824                                 // Warning: Because of Change-Tracking, the last
825                                 // position is 'size()' and not 'size()-1':
826                                 cur.pos() = par.size();
827                                 // Insert a new paragraph
828                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
829                                 dispatch(cur, fr);
830                         }
831                         */
832                         if (cur.selection())
833                                 cutSelection(cur, true, false);
834                         cur.insert(inset);
835                         cur.posForward();
836                 }
837                 break;
838         }
839
840         case LFUN_INSET_DISSOLVE:
841                 needsUpdate |= dissolveInset(cur);
842                 break;
843
844         case LFUN_INSET_SETTINGS: {
845                 Inset & inset = cur.inset();
846                 if (cmd.getArg(0) == insetName(inset.lyxCode())) {
847                         // This inset dialog has been explicitely requested.
848                         inset.showInsetDialog(bv);
849                         break;
850                 }
851                 // else, if there is an inset at the cursor, access this
852                 Inset * next_inset = cur.nextInset();
853                 if (next_inset) {
854                         next_inset->showInsetDialog(bv);
855                         break;
856                 }
857                 // if not then access the underlying inset.
858                 inset.showInsetDialog(bv);
859                 break;
860         }
861
862         case LFUN_SET_GRAPHICS_GROUP: {
863                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
864                 if (!ins)
865                         break;
866
867                 cur.recordUndoFullDocument();
868
869                 string id = to_utf8(cmd.argument());
870                 string grp = graphics::getGroupParams(bv->buffer(), id);
871                 InsetGraphicsParams tmp, inspar = ins->getParams();
872
873                 if (id.empty())
874                         inspar.groupId = to_utf8(cmd.argument());
875                 else {
876                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
877                         tmp.filename = inspar.filename;
878                         inspar = tmp;
879                 }
880
881                 ins->setParams(inspar);
882         }
883
884         case LFUN_SPACE_INSERT:
885                 if (cur.paragraph().layout().free_spacing)
886                         insertChar(cur, ' ');
887                 else {
888                         doInsertInset(cur, this, cmd, false, false);
889                         cur.posForward();
890                 }
891                 moveCursor(cur, false);
892                 break;
893
894         case LFUN_SPECIALCHAR_INSERT: {
895                 string const name = to_utf8(cmd.argument());
896                 if (name == "hyphenation")
897                         specialChar(cur, InsetSpecialChar::HYPHENATION);
898                 else if (name == "ligature-break")
899                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
900                 else if (name == "slash")
901                         specialChar(cur, InsetSpecialChar::SLASH);
902                 else if (name == "nobreakdash")
903                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
904                 else if (name == "dots")
905                         specialChar(cur, InsetSpecialChar::LDOTS);
906                 else if (name == "end-of-sentence")
907                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
908                 else if (name == "menu-separator")
909                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
910                 else if (name.empty())
911                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
912                 else
913                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
914                 break;
915         }
916
917         case LFUN_WORD_UPCASE:
918                 changeCase(cur, text_uppercase);
919                 break;
920
921         case LFUN_WORD_LOWCASE:
922                 changeCase(cur, text_lowercase);
923                 break;
924
925         case LFUN_WORD_CAPITALIZE:
926                 changeCase(cur, text_capitalization);
927                 break;
928
929         case LFUN_CHARS_TRANSPOSE:
930                 charsTranspose(cur);
931                 break;
932
933         case LFUN_PASTE: {
934                 cur.message(_("Paste"));
935                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
936                 cap::replaceSelection(cur);
937
938                 // without argument?
939                 string const arg = to_utf8(cmd.argument());
940                 if (arg.empty()) {
941                         if (theClipboard().isInternal())
942                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
943                         else if (theClipboard().hasGraphicsContents())
944                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
945                         else
946                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
947                 } else if (isStrUnsignedInt(arg)) {
948                         // we have a numerical argument
949                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
950                                        convert<unsigned int>(arg));
951                 } else {
952                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
953                         if (arg == "pdf")
954                                 type = Clipboard::PdfGraphicsType;
955                         else if (arg == "png")
956                                 type = Clipboard::PngGraphicsType;
957                         else if (arg == "jpeg")
958                                 type = Clipboard::JpegGraphicsType;
959                         else if (arg == "linkback")
960                                 type = Clipboard::LinkBackGraphicsType;
961                         else
962                                 LASSERT(false, /**/);
963
964                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
965                 }
966
967                 bv->buffer().errors("Paste");
968                 cur.clearSelection(); // bug 393
969                 cur.finishUndo();
970                 break;
971         }
972
973         case LFUN_CUT:
974                 cutSelection(cur, true, true);
975                 cur.message(_("Cut"));
976                 break;
977
978         case LFUN_COPY:
979                 copySelection(cur);
980                 cur.message(_("Copy"));
981                 break;
982
983         case LFUN_SERVER_GET_XY:
984                 cur.message(from_utf8(
985                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
986                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
987                 break;
988
989         case LFUN_SERVER_SET_XY: {
990                 int x = 0;
991                 int y = 0;
992                 istringstream is(to_utf8(cmd.argument()));
993                 is >> x >> y;
994                 if (!is)
995                         lyxerr << "SETXY: Could not parse coordinates in '"
996                                << to_utf8(cmd.argument()) << endl;
997                 else
998                         tm.setCursorFromCoordinates(cur, x, y);
999                 break;
1000         }
1001
1002         case LFUN_SERVER_GET_LAYOUT:
1003                 cur.message(cur.paragraph().layout().name());
1004                 break;
1005
1006         case LFUN_LAYOUT: {
1007                 docstring layout = cmd.argument();
1008                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1009
1010                 Paragraph const & para = cur.paragraph();
1011                 docstring const old_layout = para.layout().name();
1012                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1013
1014                 if (layout.empty())
1015                         layout = tclass.defaultLayoutName();
1016
1017                 if (para.forcePlainLayout()) 
1018                         // in this case only the empty layout is allowed
1019                         layout = tclass.plainLayoutName();
1020                 else if (para.usePlainLayout()) {
1021                         // in this case, default layout maps to empty layout 
1022                         if (layout == tclass.defaultLayoutName())
1023                                 layout = tclass.plainLayoutName();
1024                 } else { 
1025                         // otherwise, the empty layout maps to the default
1026                         if (layout == tclass.plainLayoutName())
1027                                 layout = tclass.defaultLayoutName();
1028                 }
1029
1030                 bool hasLayout = tclass.hasLayout(layout);
1031
1032                 // If the entry is obsolete, use the new one instead.
1033                 if (hasLayout) {
1034                         docstring const & obs = tclass[layout].obsoleted_by();
1035                         if (!obs.empty())
1036                                 layout = obs;
1037                 }
1038
1039                 if (!hasLayout) {
1040                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1041                                 from_utf8(N_(" not known")));
1042                         break;
1043                 }
1044
1045                 bool change_layout = (old_layout != layout);
1046
1047                 if (!change_layout && cur.selection() &&
1048                         cur.selBegin().pit() != cur.selEnd().pit())
1049                 {
1050                         pit_type spit = cur.selBegin().pit();
1051                         pit_type epit = cur.selEnd().pit() + 1;
1052                         while (spit != epit) {
1053                                 if (pars_[spit].layout().name() != old_layout) {
1054                                         change_layout = true;
1055                                         break;
1056                                 }
1057                                 ++spit;
1058                         }
1059                 }
1060
1061                 if (change_layout)
1062                         setLayout(cur, layout);
1063
1064                 break;
1065         }
1066
1067         case LFUN_CLIPBOARD_PASTE:
1068                 cur.clearSelection();
1069                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1070                                cmd.argument() == "paragraph");
1071                 bv->buffer().errors("Paste");
1072                 break;
1073
1074         case LFUN_PRIMARY_SELECTION_PASTE:
1075                 pasteString(cur, theSelection().get(),
1076                             cmd.argument() == "paragraph");
1077                 break;
1078
1079         case LFUN_UNICODE_INSERT: {
1080                 if (cmd.argument().empty())
1081                         break;
1082                 docstring hexstring = cmd.argument();
1083                 if (isHex(hexstring)) {
1084                         char_type c = hexToInt(hexstring);
1085                         if (c >= 32 && c < 0x10ffff) {
1086                                 lyxerr << "Inserting c: " << c << endl;
1087                                 docstring s = docstring(1, c);
1088                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1089                         }
1090                 }
1091                 break;
1092         }
1093
1094         case LFUN_QUOTE_INSERT: {
1095                 Paragraph & par = cur.paragraph();
1096                 pos_type pos = cur.pos();
1097                 BufferParams const & bufparams = bv->buffer().params();
1098                 Layout const & style = par.layout();
1099                 if (!style.pass_thru
1100                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1101                         // this avoids a double undo
1102                         // FIXME: should not be needed, ideally
1103                         if (!cur.selection())
1104                                 cur.recordUndo();
1105                         cap::replaceSelection(cur);
1106                         pos = cur.pos();
1107                         char_type c;
1108                         if (pos == 0)
1109                                 c = ' ';
1110                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1111                                 c = ' ';
1112                         else
1113                                 c = par.getChar(pos - 1);
1114                         string arg = to_utf8(cmd.argument());
1115                         cur.insert(new InsetQuotes(c, bufparams.quotes_language,
1116                                 (arg == "single") ? InsetQuotes::SingleQuotes
1117                                         : InsetQuotes::DoubleQuotes));
1118                         cur.posForward();
1119                 }
1120                 else
1121                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1122                 break;
1123         }
1124
1125         case LFUN_DATE_INSERT: {
1126                 string const format = cmd.argument().empty()
1127                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1128                 string const time = formatted_time(current_time(), format);
1129                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1130                 break;
1131         }
1132
1133         case LFUN_MOUSE_TRIPLE:
1134                 if (cmd.button() == mouse_button::button1) {
1135                         tm.cursorHome(cur);
1136                         cur.resetAnchor();
1137                         tm.cursorEnd(cur);
1138                         cur.setSelection();
1139                         bv->cursor() = cur;
1140                 }
1141                 break;
1142
1143         case LFUN_MOUSE_DOUBLE:
1144                 if (cmd.button() == mouse_button::button1) {
1145                         selectWord(cur, WHOLE_WORD_STRICT);
1146                         bv->cursor() = cur;
1147                 }
1148                 break;
1149
1150         // Single-click on work area
1151         case LFUN_MOUSE_PRESS:
1152                 // We are not marking a selection with the keyboard in any case.
1153                 cur.bv().cursor().mark() = false;
1154                 switch (cmd.button()) {
1155                 case mouse_button::button1:
1156                         // Set the cursor
1157                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1158                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1159                         break;                  
1160
1161                 case mouse_button::button2:
1162                         // Middle mouse pasting.
1163                         if (!cap::selection()) {                        
1164                                 // There is no local selection in the current buffer, so try to
1165                                 // paste primary selection instead.
1166                                 lyx::dispatch(FuncRequest(LFUN_PRIMARY_SELECTION_PASTE,
1167                                         "paragraph"));
1168                                 // Nothing else to do.
1169                                 cur.noUpdate();
1170                                 return;
1171                         }
1172                         // Copy the selection buffer to the clipboard stack, because we want it
1173                         // to appear in the "Edit->Paste recent" menu.
1174                         cap::copySelectionToStack();
1175                         cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1176                         cur.updateFlags(Update::Force | Update::FitCursor);
1177                         bv->buffer().errors("Paste");
1178                         bv->buffer().markDirty();
1179                         bv->cursor().finishUndo();
1180                         break;
1181
1182                 case mouse_button::button3: {
1183                         Cursor const & bvcur = cur.bv().cursor();
1184                         // Don't do anything if we right-click a
1185                         // selection, a context menu will popup.
1186                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1187                             && cur <= bvcur.selectionEnd()) {
1188                                 cur.noUpdate();
1189                                 return;
1190                         }
1191                         if (!bv->mouseSetCursor(cur, false))
1192                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1193                         break;                  
1194                 }
1195
1196                 default:
1197                         break;
1198                 } // switch (cmd.button())
1199                 break;
1200
1201         case LFUN_MOUSE_MOTION: {
1202                 // Mouse motion with right or middle mouse do nothing for now.
1203                 if (cmd.button() != mouse_button::button1) {
1204                         cur.noUpdate();
1205                         return;
1206                 }
1207                 // ignore motions deeper nested than the real anchor
1208                 Cursor & bvcur = cur.bv().cursor();
1209                 if (!bvcur.anchor_.hasPart(cur)) {
1210                         cur.undispatched();
1211                         break;
1212                 }
1213                 CursorSlice old = bvcur.top();
1214
1215                 int const wh = bv->workHeight();
1216                 int const y = max(0, min(wh - 1, cmd.y));
1217
1218                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1219                 cur.setTargetX(cmd.x);
1220                 if (cmd.y >= wh)
1221                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1222                 else if (cmd.y < 0)
1223                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1224                 // This is to allow jumping over large insets
1225                 if (cur.top() == old) {
1226                         if (cmd.y >= wh)
1227                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1228                         else if (cmd.y < 0)
1229                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1230                 }
1231                 // We continue with our existing selection or start a new one, so don't
1232                 // reset the anchor.
1233                 bvcur.setCursor(cur);
1234                 bvcur.selection() = true;
1235                 if (cur.top() == old) {
1236                         // We didn't move one iota, so no need to update the screen.
1237                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1238                         //cur.noUpdate();
1239                         return;
1240                 }
1241                 break;
1242         }
1243
1244         case LFUN_MOUSE_RELEASE:
1245                 switch (cmd.button()) {
1246                 case mouse_button::button1:
1247                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1248                         // If there is a new selection, update persistent selection;
1249                         // otherwise, single click does not clear persistent selection
1250                         // buffer.
1251                         if (cur.selection()) {
1252                                 // Finish selection.
1253                                 // If double click, cur is moved to the end of word by selectWord
1254                                 // but bvcur is current mouse position.
1255                                 cur.bv().cursor().selection() = true;
1256                         }
1257                         // FIXME: We could try to handle drag and drop of selection here.
1258                         cur.noUpdate();
1259                         return;
1260
1261                 case mouse_button::button2:
1262                         // Middle mouse pasting is handled at mouse press time,
1263                         // see LFUN_MOUSE_PRESS.
1264                         cur.noUpdate();
1265                         return;
1266
1267                 case mouse_button::button3:
1268                         // Cursor was set at LFUN_MOUSE_PRESS time.
1269                         // FIXME: If there is a selection we could try to handle a special
1270                         // drag & drop context menu.
1271                         cur.noUpdate();
1272                         return;
1273
1274                 case mouse_button::none:
1275                 case mouse_button::button4:
1276                 case mouse_button::button5:
1277                         break;
1278                 } // switch (cmd.button())
1279
1280                 break;
1281
1282         case LFUN_SELF_INSERT: {
1283                 if (cmd.argument().empty())
1284                         break;
1285
1286                 // Automatically delete the currently selected
1287                 // text and replace it with what is being
1288                 // typed in now. Depends on lyxrc settings
1289                 // "auto_region_delete", which defaults to
1290                 // true (on).
1291
1292                 if (lyxrc.auto_region_delete && cur.selection())
1293                         cutSelection(cur, false, false);
1294
1295                 cur.clearSelection();
1296                 Font const old_font = cur.real_current_font;
1297
1298                 docstring::const_iterator cit = cmd.argument().begin();
1299                 docstring::const_iterator end = cmd.argument().end();
1300                 for (; cit != end; ++cit)
1301                         bv->translateAndInsert(*cit, this, cur);
1302
1303                 cur.resetAnchor();
1304                 moveCursor(cur, false);
1305                 break;
1306         }
1307
1308         case LFUN_HYPERLINK_INSERT: {
1309                 InsetCommandParams p(HYPERLINK_CODE);
1310                 docstring content;
1311                 if (cur.selection()) {
1312                         content = cur.selectionAsString(false);
1313                         cutSelection(cur, true, false);
1314                 }
1315                 p["target"] = (cmd.argument().empty()) ?
1316                         content : cmd.argument();
1317                 string const data = InsetCommand::params2string("href", p);
1318                 if (p["target"].empty()) {
1319                         bv->showDialog("href", data);
1320                 } else {
1321                         FuncRequest fr(LFUN_INSET_INSERT, data);
1322                         dispatch(cur, fr);
1323                 }
1324                 break;
1325         }
1326
1327         case LFUN_LABEL_INSERT: {
1328                 InsetCommandParams p(LABEL_CODE);
1329                 // Try to generate a valid label
1330                 p["name"] = (cmd.argument().empty()) ?
1331                         cur.getPossibleLabel() :
1332                         cmd.argument();
1333                 string const data = InsetCommand::params2string("label", p);
1334
1335                 if (cmd.argument().empty()) {
1336                         bv->showDialog("label", data);
1337                 } else {
1338                         FuncRequest fr(LFUN_INSET_INSERT, data);
1339                         dispatch(cur, fr);
1340                 }
1341                 break;
1342         }
1343
1344         case LFUN_INFO_INSERT: {
1345                 Inset * inset;
1346                 if (cmd.argument().empty() && cur.selection()) {
1347                         // if command argument is empty use current selection as parameter.
1348                         docstring ds = cur.selectionAsString(false);
1349                         cutSelection(cur, true, false);
1350                         FuncRequest cmd0(cmd, ds);
1351                         inset = createInset(cur.bv().buffer(), cmd0);
1352                 } else {
1353                         inset = createInset(cur.bv().buffer(), cmd);
1354                 }
1355                 if (!inset)
1356                         break;
1357                 insertInset(cur, inset);
1358                 cur.posForward();
1359                 break;
1360         }
1361         case LFUN_CAPTION_INSERT:
1362         case LFUN_FOOTNOTE_INSERT:
1363         case LFUN_NOTE_INSERT:
1364         case LFUN_FLEX_INSERT:
1365         case LFUN_BOX_INSERT:
1366         case LFUN_BRANCH_INSERT:
1367         case LFUN_ERT_INSERT:
1368         case LFUN_LISTING_INSERT:
1369         case LFUN_MARGINALNOTE_INSERT:
1370         case LFUN_OPTIONAL_INSERT:
1371         case LFUN_INDEX_INSERT:
1372                 // Open the inset, and move the current selection
1373                 // inside it.
1374                 doInsertInset(cur, this, cmd, true, true);
1375                 cur.posForward();
1376                 // Some insets are numbered, others are shown in the outline pane so
1377                 // let's update the labels and the toc backend.
1378                 updateLabels(bv->buffer());
1379                 break;
1380
1381         case LFUN_TABULAR_INSERT:
1382                 // if there were no arguments, just open the dialog
1383                 if (doInsertInset(cur, this, cmd, false, true))
1384                         cur.posForward();
1385                 else
1386                         bv->showDialog("tabularcreate");
1387
1388                 break;
1389
1390         case LFUN_FLOAT_INSERT:
1391         case LFUN_FLOAT_WIDE_INSERT:
1392         case LFUN_WRAP_INSERT: {
1393                 bool content = cur.selection();  // will some text be moved into the inset?
1394
1395                 doInsertInset(cur, this, cmd, true, true);
1396                 cur.posForward();
1397                 ParagraphList & pars = cur.text()->paragraphs();
1398
1399                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1400
1401                 // add a separate paragraph for the caption inset
1402                 pars.push_back(Paragraph());
1403                 pars.back().setInsetOwner(pars[0].inInset());
1404                 pars.back().setPlainOrDefaultLayout(tclass);
1405                 int cap_pit = pars.size() - 1;
1406
1407                 // if an empty inset was created, we create an additional empty
1408                 // paragraph at the bottom so that the user can choose where to put
1409                 // the graphics (or table).
1410                 if (!content) {
1411                         pars.push_back(Paragraph());
1412                         pars.back().setInsetOwner(pars[0].inInset());
1413                         pars.back().setPlainOrDefaultLayout(tclass);
1414                 }
1415
1416                 // reposition the cursor to the caption
1417                 cur.pit() = cap_pit;
1418                 cur.pos() = 0;
1419                 // FIXME: This Text/Cursor dispatch handling is a mess!
1420                 // We cannot use Cursor::dispatch here it needs access to up to
1421                 // date metrics.
1422                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1423                 cur.text()->dispatch(cur, cmd_caption);
1424                 cur.updateFlags(Update::Force);
1425                 // FIXME: When leaving the Float (or Wrap) inset we should
1426                 // delete any empty paragraph left above or below the
1427                 // caption.
1428                 break;
1429         }
1430
1431         case LFUN_NOMENCL_INSERT: {
1432                 InsetCommandParams p(NOMENCL_CODE);
1433                 if (cmd.argument().empty())
1434                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1435                 else
1436                         p["symbol"] = cmd.argument();
1437                 string const data = InsetCommand::params2string("nomenclature", p);
1438                 bv->showDialog("nomenclature", data);   
1439                 break;
1440         }
1441
1442         case LFUN_INDEX_PRINT:
1443         case LFUN_NOMENCL_PRINT:
1444         case LFUN_TOC_INSERT:
1445         case LFUN_LINE_INSERT:
1446         case LFUN_NEWPAGE_INSERT:
1447                 // do nothing fancy
1448                 doInsertInset(cur, this, cmd, false, false);
1449                 cur.posForward();
1450                 break;
1451
1452         case LFUN_DEPTH_DECREMENT:
1453                 changeDepth(cur, DEC_DEPTH);
1454                 break;
1455
1456         case LFUN_DEPTH_INCREMENT:
1457                 changeDepth(cur, INC_DEPTH);
1458                 break;
1459
1460         case LFUN_MATH_DISPLAY:
1461                 mathDispatch(cur, cmd, true);
1462                 break;
1463
1464         case LFUN_MATH_MODE:
1465                 if (cmd.argument() == "on")
1466                         // don't pass "on" as argument
1467                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1468                 else
1469                         mathDispatch(cur, cmd, false);
1470                 break;
1471
1472         case LFUN_MATH_MACRO:
1473                 if (cmd.argument().empty())
1474                         cur.errorMessage(from_utf8(N_("Missing argument")));
1475                 else {
1476                         string s = to_utf8(cmd.argument());
1477                         string const s1 = token(s, ' ', 1);
1478                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1479                         string const s2 = token(s, ' ', 2);
1480                         MacroType type = MacroTypeNewcommand;
1481                         if (s2 == "def")
1482                                 type = MacroTypeDef;
1483                         cur.insert(new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type));
1484                         //cur.nextInset()->edit(cur, true);
1485                 }
1486                 break;
1487
1488         // passthrough hat and underscore outside mathed:
1489         case LFUN_MATH_SUBSCRIPT:
1490                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1491                 break;
1492         case LFUN_MATH_SUPERSCRIPT:
1493                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1494                 break;
1495
1496         case LFUN_MATH_INSERT:
1497         case LFUN_MATH_MATRIX:
1498         case LFUN_MATH_DELIM:
1499         case LFUN_MATH_BIGDELIM: {
1500                 cap::replaceSelection(cur);
1501                 cur.insert(new InsetMathHull(hullSimple));
1502                 checkAndActivateInset(cur, true);
1503                 LASSERT(cur.inMathed(), /**/);
1504                 cur.dispatch(cmd);
1505                 break;
1506         }
1507
1508         case LFUN_FONT_EMPH: {
1509                 Font font(ignore_font, ignore_language);
1510                 font.fontInfo().setEmph(FONT_TOGGLE);
1511                 toggleAndShow(cur, this, font);
1512                 break;
1513         }
1514
1515         case LFUN_FONT_BOLD: {
1516                 Font font(ignore_font, ignore_language);
1517                 font.fontInfo().setSeries(BOLD_SERIES);
1518                 toggleAndShow(cur, this, font);
1519                 break;
1520         }
1521
1522         case LFUN_FONT_NOUN: {
1523                 Font font(ignore_font, ignore_language);
1524                 font.fontInfo().setNoun(FONT_TOGGLE);
1525                 toggleAndShow(cur, this, font);
1526                 break;
1527         }
1528
1529         case LFUN_FONT_TYPEWRITER: {
1530                 Font font(ignore_font, ignore_language);
1531                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1532                 toggleAndShow(cur, this, font);
1533                 break;
1534         }
1535
1536         case LFUN_FONT_SANS: {
1537                 Font font(ignore_font, ignore_language);
1538                 font.fontInfo().setFamily(SANS_FAMILY);
1539                 toggleAndShow(cur, this, font);
1540                 break;
1541         }
1542
1543         case LFUN_FONT_ROMAN: {
1544                 Font font(ignore_font, ignore_language);
1545                 font.fontInfo().setFamily(ROMAN_FAMILY);
1546                 toggleAndShow(cur, this, font);
1547                 break;
1548         }
1549
1550         case LFUN_FONT_DEFAULT: {
1551                 Font font(inherit_font, ignore_language);
1552                 toggleAndShow(cur, this, font);
1553                 break;
1554         }
1555
1556         case LFUN_FONT_UNDERLINE: {
1557                 Font font(ignore_font, ignore_language);
1558                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1559                 toggleAndShow(cur, this, font);
1560                 break;
1561         }
1562
1563         case LFUN_FONT_SIZE: {
1564                 Font font(ignore_font, ignore_language);
1565                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1566                 toggleAndShow(cur, this, font);
1567                 break;
1568         }
1569
1570         case LFUN_LANGUAGE: {
1571                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1572                 if (!lang)
1573                         break;
1574                 Font font(ignore_font, lang);
1575                 toggleAndShow(cur, this, font);
1576                 break;
1577         }
1578
1579         case LFUN_TEXTSTYLE_APPLY:
1580                 toggleAndShow(cur, this, freefont, toggleall);
1581                 cur.message(_("Character set"));
1582                 break;
1583
1584         // Set the freefont using the contents of \param data dispatched from
1585         // the frontends and apply it at the current cursor location.
1586         case LFUN_TEXTSTYLE_UPDATE: {
1587                 Font font;
1588                 bool toggle;
1589                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1590                         freefont = font;
1591                         toggleall = toggle;
1592                         toggleAndShow(cur, this, freefont, toggleall);
1593                         cur.message(_("Character set"));
1594                 } else {
1595                         lyxerr << "Argument not ok";
1596                 }
1597                 break;
1598         }
1599
1600         case LFUN_FINISHED_LEFT:
1601                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1602                 // We're leaving an inset, going left. If the inset is LTR, we're 
1603                 // leaving from the front, so we should not move (remain at --- but
1604                 // not in --- the inset). If the inset is RTL, move left, without 
1605                 // entering the inset itself; i.e., move to after the inset.
1606                 if (cur.paragraph().getFontSettings(
1607                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1608                         cursorVisLeft(cur, true);
1609                 break;
1610
1611         case LFUN_FINISHED_RIGHT:
1612                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1613                 // We're leaving an inset, going right. If the inset is RTL, we're 
1614                 // leaving from the front, so we should not move (remain at --- but
1615                 // not in --- the inset). If the inset is LTR, move right, without 
1616                 // entering the inset itself; i.e., move to after the inset.
1617                 if (!cur.paragraph().getFontSettings(
1618                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1619                         cursorVisRight(cur, true);
1620                 break;
1621
1622         case LFUN_FINISHED_BACKWARD:
1623                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1624                 break;
1625
1626         case LFUN_FINISHED_FORWARD:
1627                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1628                 ++cur.pos();
1629                 cur.setCurrentFont();
1630                 break;
1631
1632         case LFUN_LAYOUT_PARAGRAPH: {
1633                 string data;
1634                 params2string(cur.paragraph(), data);
1635                 data = "show\n" + data;
1636                 bv->showDialog("paragraph", data);
1637                 break;
1638         }
1639
1640         case LFUN_PARAGRAPH_UPDATE: {
1641                 string data;
1642                 params2string(cur.paragraph(), data);
1643
1644                 // Will the paragraph accept changes from the dialog?
1645                 bool const accept = 
1646                         cur.inset().allowParagraphCustomization(cur.idx());
1647
1648                 data = "update " + convert<string>(accept) + '\n' + data;
1649                 bv->updateDialog("paragraph", data);
1650                 break;
1651         }
1652
1653         case LFUN_ACCENT_UMLAUT:
1654         case LFUN_ACCENT_CIRCUMFLEX:
1655         case LFUN_ACCENT_GRAVE:
1656         case LFUN_ACCENT_ACUTE:
1657         case LFUN_ACCENT_TILDE:
1658         case LFUN_ACCENT_CEDILLA:
1659         case LFUN_ACCENT_MACRON:
1660         case LFUN_ACCENT_DOT:
1661         case LFUN_ACCENT_UNDERDOT:
1662         case LFUN_ACCENT_UNDERBAR:
1663         case LFUN_ACCENT_CARON:
1664         case LFUN_ACCENT_BREVE:
1665         case LFUN_ACCENT_TIE:
1666         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1667         case LFUN_ACCENT_CIRCLE:
1668         case LFUN_ACCENT_OGONEK:
1669                 theLyXFunc().handleKeyFunc(cmd.action);
1670                 if (!cmd.argument().empty())
1671                         // FIXME: Are all these characters encoded in one byte in utf8?
1672                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1673                 break;
1674
1675         case LFUN_FLOAT_LIST_INSERT: {
1676                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1677                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1678                         cur.recordUndo();
1679                         if (cur.selection())
1680                                 cutSelection(cur, true, false);
1681                         breakParagraph(cur);
1682
1683                         if (cur.lastpos() != 0) {
1684                                 cursorBackward(cur);
1685                                 breakParagraph(cur);
1686                         }
1687
1688                         docstring const laystr = cur.inset().usePlainLayout() ?
1689                                 tclass.plainLayoutName() :
1690                                 tclass.defaultLayoutName();
1691                         setLayout(cur, laystr);
1692                         ParagraphParameters p;
1693                         setParagraphs(cur, p);
1694                         // FIXME This should be simplified when InsetFloatList takes a 
1695                         // Buffer in its constructor.
1696                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
1697                         ifl->setBuffer(bv->buffer());
1698                         insertInset(cur, ifl);
1699                         cur.posForward();
1700                 } else {
1701                         lyxerr << "Non-existent float type: "
1702                                << to_utf8(cmd.argument()) << endl;
1703                 }
1704                 break;
1705         }
1706
1707         case LFUN_CHANGE_ACCEPT: {
1708                 acceptOrRejectChanges(cur, ACCEPT);
1709                 break;
1710         }
1711
1712         case LFUN_CHANGE_REJECT: {
1713                 acceptOrRejectChanges(cur, REJECT);
1714                 break;
1715         }
1716
1717         case LFUN_THESAURUS_ENTRY: {
1718                 docstring arg = cmd.argument();
1719                 if (arg.empty()) {
1720                         arg = cur.selectionAsString(false);
1721                         // FIXME
1722                         if (arg.size() > 100 || arg.empty()) {
1723                                 // Get word or selection
1724                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1725                                 arg = cur.selectionAsString(false);
1726                         }
1727                 }
1728                 bv->showDialog("thesaurus", to_utf8(arg));
1729                 break;
1730         }
1731
1732         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1733                 // Given data, an encoding of the ParagraphParameters
1734                 // generated in the Paragraph dialog, this function sets
1735                 // the current paragraph, or currently selected paragraphs,
1736                 // appropriately. 
1737                 // NOTE: This function overrides all existing settings.
1738                 setParagraphs(cur, cmd.argument());
1739                 cur.message(_("Paragraph layout set"));
1740                 break;
1741         }
1742         
1743         case LFUN_PARAGRAPH_PARAMS: {
1744                 // Given data, an encoding of the ParagraphParameters as we'd
1745                 // find them in a LyX file, this function modifies the current paragraph, 
1746                 // or currently selected paragraphs. 
1747                 // NOTE: This function only modifies, and does not override, existing
1748                 // settings.
1749                 setParagraphs(cur, cmd.argument(), true);
1750                 cur.message(_("Paragraph layout set"));
1751                 break;
1752         }
1753
1754         case LFUN_ESCAPE:
1755                 if (cur.selection()) {
1756                         cur.selection() = false;
1757                 } else {
1758                         cur.undispatched();
1759                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1760                         // correct, but I'm not 100% sure -- dov, 071019
1761                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1762                 }
1763                 break;
1764
1765         case LFUN_OUTLINE_UP:
1766                 outline(OutlineUp, cur);
1767                 setCursor(cur, cur.pit(), 0);
1768                 updateLabels(cur.buffer());
1769                 needsUpdate = true;
1770                 break;
1771
1772         case LFUN_OUTLINE_DOWN:
1773                 outline(OutlineDown, cur);
1774                 setCursor(cur, cur.pit(), 0);
1775                 updateLabels(cur.buffer());
1776                 needsUpdate = true;
1777                 break;
1778
1779         case LFUN_OUTLINE_IN:
1780                 outline(OutlineIn, cur);
1781                 updateLabels(cur.buffer());
1782                 needsUpdate = true;
1783                 break;
1784
1785         case LFUN_OUTLINE_OUT:
1786                 outline(OutlineOut, cur);
1787                 updateLabels(cur.buffer());
1788                 needsUpdate = true;
1789                 break;
1790
1791         default:
1792                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1793                 cur.undispatched();
1794                 break;
1795         }
1796
1797         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1798
1799         // FIXME: The cursor flag is reset two lines below
1800         // so we need to check here if some of the LFUN did touch that.
1801         // for now only Text::erase() and Text::backspace() do that.
1802         // The plan is to verify all the LFUNs and then to remove this
1803         // singleParUpdate boolean altogether.
1804         if (cur.result().update() & Update::Force) {
1805                 singleParUpdate = false;
1806                 needsUpdate = true;
1807         }
1808
1809         // FIXME: the following code should go in favor of fine grained
1810         // update flag treatment.
1811         if (singleParUpdate) {
1812                 // Inserting characters does not change par height in general. So, try
1813                 // to update _only_ this paragraph. BufferView will detect if a full
1814                 // metrics update is needed anyway.
1815                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1816                 return;
1817         }
1818
1819         if (!needsUpdate
1820             && &oldTopSlice.inset() == &cur.inset()
1821             && oldTopSlice.idx() == cur.idx()
1822             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1823             && !cur.selection())
1824                 // FIXME: it would be better if we could just do this
1825                 //
1826                 //if (cur.result().update() != Update::FitCursor)
1827                 //      cur.noUpdate();
1828                 //
1829                 // But some LFUNs do not set Update::FitCursor when needed, so we
1830                 // do it for all. This is not very harmfull as FitCursor will provoke
1831                 // a full redraw only if needed but still, a proper review of all LFUN
1832                 // should be done and this needsUpdate boolean can then be removed.
1833                 cur.updateFlags(Update::FitCursor);
1834         else
1835                 cur.updateFlags(Update::Force | Update::FitCursor);
1836 }
1837
1838
1839 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1840                         FuncStatus & flag) const
1841 {
1842         LASSERT(cur.text() == this, /**/);
1843
1844         Font const & font = cur.real_current_font;
1845         FontInfo const & fontinfo = font.fontInfo();
1846         bool enable = true;
1847         InsetCode code = NO_CODE;
1848
1849         switch (cmd.action) {
1850
1851         case LFUN_DEPTH_DECREMENT:
1852                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1853                 break;
1854
1855         case LFUN_DEPTH_INCREMENT:
1856                 enable = changeDepthAllowed(cur, INC_DEPTH);
1857                 break;
1858
1859         case LFUN_APPENDIX:
1860                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1861                 break;
1862
1863         case LFUN_DIALOG_SHOW_NEW_INSET:
1864                 if (cmd.argument() == "bibitem")
1865                         code = BIBITEM_CODE;
1866                 else if (cmd.argument() == "bibtex")
1867                         code = BIBTEX_CODE;
1868                 else if (cmd.argument() == "box")
1869                         code = BOX_CODE;
1870                 else if (cmd.argument() == "branch")
1871                         code = BRANCH_CODE;
1872                 else if (cmd.argument() == "citation")
1873                         code = CITE_CODE;
1874                 else if (cmd.argument() == "ert")
1875                         code = ERT_CODE;
1876                 else if (cmd.argument() == "external")
1877                         code = EXTERNAL_CODE;
1878                 else if (cmd.argument() == "float")
1879                         code = FLOAT_CODE;
1880                 else if (cmd.argument() == "graphics")
1881                         code = GRAPHICS_CODE;
1882                 else if (cmd.argument() == "href")
1883                         code = HYPERLINK_CODE;
1884                 else if (cmd.argument() == "include")
1885                         code = INCLUDE_CODE;
1886                 else if (cmd.argument() == "index")
1887                         code = INDEX_CODE;
1888                 else if (cmd.argument() == "nomenclature")
1889                         code = NOMENCL_CODE;
1890                 else if (cmd.argument() == "label")
1891                         code = LABEL_CODE;
1892                 else if (cmd.argument() == "note")
1893                         code = NOTE_CODE;
1894                 else if (cmd.argument() == "ref")
1895                         code = REF_CODE;
1896                 else if (cmd.argument() == "space")
1897                         code = SPACE_CODE;
1898                 else if (cmd.argument() == "toc")
1899                         code = TOC_CODE;
1900                 else if (cmd.argument() == "vspace")
1901                         code = VSPACE_CODE;
1902                 else if (cmd.argument() == "wrap")
1903                         code = WRAP_CODE;
1904                 else if (cmd.argument() == "listings")
1905                         code = LISTINGS_CODE;
1906                 break;
1907
1908         case LFUN_ERT_INSERT:
1909                 code = ERT_CODE;
1910                 break;
1911         case LFUN_LISTING_INSERT:
1912                 code = LISTINGS_CODE;
1913                 break;
1914         case LFUN_FOOTNOTE_INSERT:
1915                 code = FOOT_CODE;
1916                 break;
1917         case LFUN_TABULAR_INSERT:
1918                 code = TABULAR_CODE;
1919                 break;
1920         case LFUN_MARGINALNOTE_INSERT:
1921                 code = MARGIN_CODE;
1922                 break;
1923         case LFUN_FLOAT_INSERT:
1924         case LFUN_FLOAT_WIDE_INSERT:
1925                 code = FLOAT_CODE;
1926                 break;
1927         case LFUN_WRAP_INSERT:
1928                 code = WRAP_CODE;
1929                 break;
1930         case LFUN_FLOAT_LIST_INSERT:
1931                 code = FLOAT_LIST_CODE;
1932                 break;
1933         case LFUN_CAPTION_INSERT:
1934                 code = CAPTION_CODE;
1935                 break;
1936         case LFUN_NOTE_INSERT:
1937                 code = NOTE_CODE;
1938                 // in commands (sections etc., only Notes are allowed)
1939                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
1940                           !cur.paragraph().layout().isCommand());
1941                 break;
1942         case LFUN_FLEX_INSERT: {
1943                 code = FLEX_CODE;
1944                 string s = cmd.getArg(0);
1945                 InsetLayout il = 
1946                         cur.buffer().params().documentClass().insetLayout(from_utf8(s));
1947                 if (il.lyxtype() != "charstyle" &&
1948                     il.lyxtype() != "custom" &&
1949                     il.lyxtype() != "element" &&
1950                     il.lyxtype ()!= "standard")
1951                         enable = false;
1952                 break;
1953                 }
1954         case LFUN_BOX_INSERT:
1955                 code = BOX_CODE;
1956                 break;
1957         case LFUN_BRANCH_INSERT:
1958                 code = BRANCH_CODE;
1959                 if (cur.buffer().masterBuffer()->params().branchlist().empty())
1960                         enable = false;
1961                 break;
1962         case LFUN_LABEL_INSERT:
1963                 code = LABEL_CODE;
1964                 break;
1965         case LFUN_INFO_INSERT:
1966                 code = INFO_CODE;
1967                 break;
1968         case LFUN_OPTIONAL_INSERT:
1969                 code = OPTARG_CODE;
1970                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
1971                         < cur.paragraph().layout().optionalargs;
1972                 break;
1973         case LFUN_INDEX_INSERT:
1974                 code = INDEX_CODE;
1975                 break;
1976         case LFUN_INDEX_PRINT:
1977                 code = INDEX_PRINT_CODE;
1978                 break;
1979         case LFUN_NOMENCL_INSERT:
1980                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
1981                         enable = false;
1982                         break;
1983                 }
1984                 code = NOMENCL_CODE;
1985                 break;
1986         case LFUN_NOMENCL_PRINT:
1987                 code = NOMENCL_PRINT_CODE;
1988                 break;
1989         case LFUN_TOC_INSERT:
1990                 code = TOC_CODE;
1991                 break;
1992         case LFUN_HYPERLINK_INSERT:
1993                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
1994                         enable = false;
1995                         break;
1996                 }
1997                 code = HYPERLINK_CODE;
1998                 break;
1999         case LFUN_QUOTE_INSERT:
2000                 // always allow this, since we will inset a raw quote
2001                 // if an inset is not allowed.
2002                 break;
2003         case LFUN_SPECIALCHAR_INSERT:
2004                 code = SPECIALCHAR_CODE;
2005                 break;
2006         case LFUN_SPACE_INSERT:
2007                 // slight hack: we know this is allowed in math mode
2008                 if (cur.inTexted())
2009                         code = SPACE_CODE;
2010                 break;
2011
2012         case LFUN_INSET_MODIFY:
2013                 // We need to disable this, because we may get called for a
2014                 // tabular cell via
2015                 // InsetTabular::getStatus() -> InsetText::getStatus()
2016                 // and we don't handle LFUN_INSET_MODIFY.
2017                 enable = false;
2018                 break;
2019
2020         case LFUN_FONT_EMPH:
2021                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2022                 break;
2023
2024         case LFUN_FONT_NOUN:
2025                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2026                 break;
2027
2028         case LFUN_FONT_BOLD:
2029                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2030                 break;
2031
2032         case LFUN_FONT_SANS:
2033                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2034                 break;
2035
2036         case LFUN_FONT_ROMAN:
2037                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2038                 break;
2039
2040         case LFUN_FONT_TYPEWRITER:
2041                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2042                 break;
2043
2044         case LFUN_CUT:
2045         case LFUN_COPY:
2046                 enable = cur.selection();
2047                 break;
2048
2049         case LFUN_PASTE: {
2050                 if (cmd.argument().empty()) {
2051                         if (theClipboard().isInternal())
2052                                 enable = cap::numberOfSelections() > 0;
2053                         else
2054                                 enable = !theClipboard().empty();
2055                         break;
2056                 }
2057                 
2058                 // we have an argument
2059                 string const arg = to_utf8(cmd.argument());
2060                 if (isStrUnsignedInt(arg)) {
2061                         // it's a number and therefore means the internal stack
2062                         unsigned int n = convert<unsigned int>(arg);
2063                         enable = cap::numberOfSelections() > n;
2064                         break;
2065                 }
2066                 
2067                 // explicit graphics type?
2068                 if ((arg == "pdf" && theClipboard().hasGraphicsContents(Clipboard::PdfGraphicsType))
2069                     || (arg == "png" && theClipboard().hasGraphicsContents(Clipboard::PngGraphicsType))
2070                     || (arg == "jpeg" && theClipboard().hasGraphicsContents(Clipboard::JpegGraphicsType))
2071                     || (arg == "linkback" && theClipboard().hasGraphicsContents(Clipboard::LinkBackGraphicsType))) {
2072                         enable = true;
2073                         break;
2074                 }
2075                 
2076                 // unknown argument
2077                 enable = false;
2078                 break;
2079          }
2080
2081         case LFUN_CLIPBOARD_PASTE:
2082                 enable = !theClipboard().empty();
2083                 break;
2084
2085         case LFUN_PRIMARY_SELECTION_PASTE:
2086                 enable = cur.selection() || !theSelection().empty();
2087                 break;
2088
2089         case LFUN_PARAGRAPH_MOVE_UP:
2090                 enable = cur.pit() > 0 && !cur.selection();
2091                 break;
2092
2093         case LFUN_PARAGRAPH_MOVE_DOWN:
2094                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2095                 break;
2096
2097         case LFUN_INSET_DISSOLVE:
2098                 if (!cmd.argument().empty()) {
2099                         InsetLayout il = cur.inset().getLayout(cur.buffer().params());
2100                         enable = cur.inset().lyxCode() == FLEX_CODE
2101                                  && il.lyxtype() == to_utf8(cmd.argument());
2102                 } else {
2103                         enable = !isMainText(cur.bv().buffer()) 
2104                                  && cur.inset().nargs() == 1;
2105                 }
2106                 break;
2107
2108         case LFUN_CHANGE_ACCEPT:
2109         case LFUN_CHANGE_REJECT:
2110                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2111                 // In principle, these LFUNs should only be enabled if there
2112                 // is a change at the current position/in the current selection.
2113                 // However, without proper optimizations, this will inevitably
2114                 // result in unacceptable performance - just imagine a user who
2115                 // wants to select the complete content of a long document.
2116                 enable = true;
2117                 break;
2118
2119         case LFUN_OUTLINE_UP:
2120         case LFUN_OUTLINE_DOWN:
2121         case LFUN_OUTLINE_IN:
2122         case LFUN_OUTLINE_OUT:
2123                 // FIXME: LyX is not ready for outlining within inset.
2124                 enable = isMainText(cur.bv().buffer())
2125                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2126                 break;
2127
2128         case LFUN_NEWLINE_INSERT:
2129                 // LaTeX restrictions (labels or empty par)
2130                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2131                 break;
2132
2133         case LFUN_SET_GRAPHICS_GROUP: {
2134                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2135                 if (!ins) 
2136                         enable = false;
2137                 else
2138                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2139                 break;
2140         }
2141
2142         case LFUN_WORD_DELETE_FORWARD:
2143         case LFUN_WORD_DELETE_BACKWARD:
2144         case LFUN_LINE_DELETE:
2145         case LFUN_WORD_FORWARD:
2146         case LFUN_WORD_BACKWARD:
2147         case LFUN_WORD_RIGHT:
2148         case LFUN_WORD_LEFT:
2149         case LFUN_CHAR_FORWARD:
2150         case LFUN_CHAR_FORWARD_SELECT:
2151         case LFUN_CHAR_BACKWARD:
2152         case LFUN_CHAR_BACKWARD_SELECT:
2153         case LFUN_CHAR_LEFT:
2154         case LFUN_CHAR_LEFT_SELECT:
2155         case LFUN_CHAR_RIGHT:
2156         case LFUN_CHAR_RIGHT_SELECT:
2157         case LFUN_UP:
2158         case LFUN_UP_SELECT:
2159         case LFUN_DOWN:
2160         case LFUN_DOWN_SELECT:
2161         case LFUN_PARAGRAPH_UP_SELECT:
2162         case LFUN_PARAGRAPH_DOWN_SELECT:
2163         case LFUN_LINE_BEGIN_SELECT:
2164         case LFUN_LINE_END_SELECT:
2165         case LFUN_WORD_FORWARD_SELECT:
2166         case LFUN_WORD_BACKWARD_SELECT:
2167         case LFUN_WORD_RIGHT_SELECT:
2168         case LFUN_WORD_LEFT_SELECT:
2169         case LFUN_WORD_SELECT:
2170         case LFUN_PARAGRAPH_UP:
2171         case LFUN_PARAGRAPH_DOWN:
2172         case LFUN_LINE_BEGIN:
2173         case LFUN_LINE_END:
2174         case LFUN_CHAR_DELETE_FORWARD:
2175         case LFUN_CHAR_DELETE_BACKWARD:
2176         case LFUN_BREAK_PARAGRAPH:
2177         case LFUN_PARAGRAPH_SPACING:
2178         case LFUN_INSET_INSERT:
2179         case LFUN_WORD_UPCASE:
2180         case LFUN_WORD_LOWCASE:
2181         case LFUN_WORD_CAPITALIZE:
2182         case LFUN_CHARS_TRANSPOSE:
2183         case LFUN_SERVER_GET_XY:
2184         case LFUN_SERVER_SET_XY:
2185         case LFUN_SERVER_GET_LAYOUT:
2186         case LFUN_LAYOUT:
2187         case LFUN_DATE_INSERT:
2188         case LFUN_SELF_INSERT:
2189         case LFUN_LINE_INSERT:
2190         case LFUN_NEWPAGE_INSERT:
2191         case LFUN_MATH_DISPLAY:
2192         case LFUN_MATH_MODE:
2193         case LFUN_MATH_MACRO:
2194         case LFUN_MATH_MATRIX:
2195         case LFUN_MATH_DELIM:
2196         case LFUN_MATH_BIGDELIM:
2197         case LFUN_MATH_INSERT:
2198         case LFUN_MATH_SUBSCRIPT:
2199         case LFUN_MATH_SUPERSCRIPT:
2200         case LFUN_FONT_DEFAULT:
2201         case LFUN_FONT_UNDERLINE:
2202         case LFUN_FONT_SIZE:
2203         case LFUN_LANGUAGE:
2204         case LFUN_TEXTSTYLE_APPLY:
2205         case LFUN_TEXTSTYLE_UPDATE:
2206         case LFUN_LAYOUT_PARAGRAPH:
2207         case LFUN_PARAGRAPH_UPDATE:
2208         case LFUN_ACCENT_UMLAUT:
2209         case LFUN_ACCENT_CIRCUMFLEX:
2210         case LFUN_ACCENT_GRAVE:
2211         case LFUN_ACCENT_ACUTE:
2212         case LFUN_ACCENT_TILDE:
2213         case LFUN_ACCENT_CEDILLA:
2214         case LFUN_ACCENT_MACRON:
2215         case LFUN_ACCENT_DOT:
2216         case LFUN_ACCENT_UNDERDOT:
2217         case LFUN_ACCENT_UNDERBAR:
2218         case LFUN_ACCENT_CARON:
2219         case LFUN_ACCENT_BREVE:
2220         case LFUN_ACCENT_TIE:
2221         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2222         case LFUN_ACCENT_CIRCLE:
2223         case LFUN_ACCENT_OGONEK:
2224         case LFUN_THESAURUS_ENTRY:
2225         case LFUN_PARAGRAPH_PARAMS_APPLY:
2226         case LFUN_PARAGRAPH_PARAMS:
2227         case LFUN_ESCAPE:
2228         case LFUN_BUFFER_END:
2229         case LFUN_BUFFER_BEGIN:
2230         case LFUN_BUFFER_BEGIN_SELECT:
2231         case LFUN_BUFFER_END_SELECT:
2232         case LFUN_UNICODE_INSERT:
2233                 // these are handled in our dispatch()
2234                 enable = true;
2235                 break;
2236
2237         default:
2238                 return false;
2239         }
2240
2241         if (code != NO_CODE
2242             && (cur.empty() || !cur.inset().insetAllowed(code)))
2243                 enable = false;
2244
2245         flag.setEnabled(enable);
2246         return true;
2247 }
2248
2249
2250 void Text::pasteString(Cursor & cur, docstring const & clip,
2251                 bool asParagraphs)
2252 {
2253         cur.clearSelection();
2254         if (!clip.empty()) {
2255                 cur.recordUndo();
2256                 if (asParagraphs)
2257                         insertStringAsParagraphs(cur, clip);
2258                 else
2259                         insertStringAsLines(cur, clip);
2260         }
2261 }
2262
2263 } // namespace lyx