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