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