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