]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
refactor topCursorVisible() prototype a little. Compile fix
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author various
7  */
8
9 #include <config.h>
10
11 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "BufferView_pimpl.h"
16 #include "frontends/WorkArea.h"
17 #include "frontends/screen.h"
18 #include "frontends/Dialogs.h"
19 #include "frontends/Alert.h"
20 #include "frontends/FileDialog.h"
21 #include "lyxtext.h"
22 #include "lyxrow.h"
23 #include "paragraph.h"
24 #include "frontends/LyXView.h"
25 #include "commandtags.h"
26 #include "lyxfunc.h"
27 #include "debug.h"
28 #include "bufferview_funcs.h"
29 #include "TextCache.h"
30 #include "bufferlist.h"
31 #include "lyxrc.h"
32 #include "intl.h"
33 // added for Dispatch functions
34 #include "lyx_cb.h"
35 #include "lyx_main.h"
36 #include "FloatList.h"
37 #include "gettext.h"
38 #include "ParagraphParameters.h"
39 #include "undo_funcs.h"
40 #include "lyxtextclasslist.h"
41
42 #include "insets/insetbib.h"
43 #include "insets/insettext.h"
44 #include "insets/inseturl.h"
45 #include "insets/insetlatexaccent.h"
46 #include "insets/insettoc.h"
47 #include "insets/insetref.h"
48 #include "insets/insetparent.h"
49 #include "insets/insetindex.h"
50 #include "insets/insetnote.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insetcite.h"
53 #include "insets/insetert.h"
54 #include "insets/insetexternal.h"
55 #include "insets/insetgraphics.h"
56 #include "insets/insetfoot.h"
57 #include "insets/insetmarginal.h"
58 #include "insets/insetminipage.h"
59 #include "insets/insetfloat.h"
60 #include "insets/insettabular.h"
61 #if 0
62 #include "insets/insettheorem.h"
63 #include "insets/insetlist.h"
64 #endif
65 #include "insets/insetcaption.h"
66 #include "insets/insetfloatlist.h"
67 #include "insets/insetspecialchar.h"
68
69 #include "mathed/formulabase.h"
70
71 #include "support/LAssert.h"
72 #include "support/lstrings.h"
73 #include "support/filetools.h"
74 #include "support/lyxfunctional.h"
75
76 #include <boost/bind.hpp>
77
78 #include <cstdio>
79 #include <ctime>
80 #include <unistd.h>
81 #include <sys/wait.h>
82 #include <clocale>
83
84
85 extern string current_layout;
86
87 #ifndef CXX_GLOBAL_CSTD
88 using std::tm;
89 using std::localtime;
90 using std::time;
91 using std::setlocale;
92 using std::strftime;
93 #endif
94
95 using std::vector;
96 using std::find_if;
97 using std::find;
98 using std::pair;
99 using std::endl;
100 using std::make_pair;
101 using std::min;
102
103 using lyx::pos_type;
104 using lyx::textclass_type;
105
106 /* the selection possible is needed, that only motion events are
107  * used, where the bottom press event was on the drawing area too */
108 bool selection_possible = false;
109
110 extern BufferList bufferlist;
111 extern char ascii_type;
112
113 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
114
115
116 namespace {
117
118 const unsigned int saved_positions_num = 20;
119
120 inline
121 void waitForX()
122 {
123         XSync(fl_get_display(), 0);
124 }
125
126
127 void SetXtermCursor(Window win)
128 {
129         static Cursor cursor;
130         static bool cursor_undefined = true;
131         if (cursor_undefined) {
132                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
133                 XFlush(fl_get_display());
134                 cursor_undefined = false;
135         }
136         XDefineCursor(fl_get_display(), win, cursor);
137         XFlush(fl_get_display());
138 }
139
140 } // anon namespace
141
142
143 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
144              int xpos, int ypos, int width, int height)
145         : bv_(b), owner_(o), buffer_(0),
146           current_scrollbar_value(0), cursor_timeout(400),
147           using_xterm_cursor(false)
148 {
149         workarea_.reset(new WorkArea(xpos, ypos, width, height));
150         screen_.reset(new LScreen(workarea()));
151  
152         // Setup the signals
153         workarea().scrollCB.connect(boost::bind(&BufferView::Pimpl::scrollCB, this, _1));
154         workarea().workAreaExpose
155                 .connect(boost::bind(&BufferView::Pimpl::workAreaExpose, this));
156         workarea().workAreaButtonPress
157                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonPress, this, _1, _2, _3));
158         workarea().workAreaButtonRelease
159                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonRelease, this, _1, _2, _3));
160         workarea().workAreaMotionNotify
161                 .connect(boost::bind(&BufferView::Pimpl::workAreaMotionNotify, this, _1, _2, _3));
162         workarea().workAreaDoubleClick
163                 .connect(boost::bind(&BufferView::Pimpl::doubleClick, this, _1, _2, _3));
164         workarea().workAreaTripleClick
165                 .connect(boost::bind(&BufferView::Pimpl::tripleClick, this, _1, _2, _3));
166         workarea().workAreaKeyPress
167                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
168         workarea().selectionRequested
169                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
170         workarea().selectionLost
171                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
172
173         cursor_timeout.timeout.connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
174         cursor_timeout.start();
175         workarea().setFocus();
176         saved_positions.resize(saved_positions_num);
177 }
178
179
180 WorkArea & BufferView::Pimpl::workarea() const
181 {
182         return *workarea_.get();
183 }
184
185  
186 LScreen & BufferView::Pimpl::screen() const
187 {
188         return *screen_.get();
189 }
190
191
192 Painter & BufferView::Pimpl::painter() const
193 {
194         return workarea().getPainter();
195 }
196
197
198 void BufferView::Pimpl::buffer(Buffer * b)
199 {
200         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
201                             << b << ")" << endl;
202         if (buffer_) {
203                 buffer_->delUser(bv_);
204
205                 // Put the old text into the TextCache, but
206                 // only if the buffer is still loaded.
207                 // Also set the owner of the test to 0
208                 //              bv_->text->owner(0);
209                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
210                 if (lyxerr.debugging())
211                         textcache.show(lyxerr, "BufferView::buffer");
212
213                 bv_->text = 0;
214         }
215
216         // Set current buffer
217         buffer_ = b;
218
219         if (bufferlist.getState() == BufferList::CLOSING) return;
220
221         // If we are closing the buffer, use the first buffer as current
222         if (!buffer_) {
223                 buffer_ = bufferlist.first();
224         }
225
226         if (buffer_) {
227                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
228                 buffer_->addUser(bv_);
229                 // If we don't have a text object for this, we make one
230                 if (bv_->text == 0) {
231                         resizeCurrentBuffer();
232                 } else {
233                         updateScreen();
234                         updateScrollbar();
235                 }
236                 bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
237                 owner_->updateMenubar();
238                 owner_->updateToolbar();
239                 // Similarly, buffer-dependent dialogs should be updated or
240                 // hidden. This should go here because some dialogs (eg ToC)
241                 // require bv_->text.
242                 owner_->getDialogs()->updateBufferDependent(true);
243                 redraw();
244         } else {
245                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
246                 owner_->updateMenubar();
247                 owner_->updateToolbar();
248                 owner_->getDialogs()->hideBufferDependent();
249                 updateScrollbar();
250                 workarea().redraw();
251
252                 // Also remove all remaining text's from the testcache.
253                 // (there should not be any!) (if there is any it is a
254                 // bug!)
255                 if (lyxerr.debugging())
256                         textcache.show(lyxerr, "buffer delete all");
257                 textcache.clear();
258         }
259         // should update layoutchoice even if we don't have a buffer.
260         owner_->updateLayoutChoice();
261
262         owner_->updateWindowTitle();
263 }
264
265
266 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
267 {
268         workarea().resize(xpos, ypos, width, height);
269         update(bv_->text, SELECT);
270         redraw();
271 }
272
273
274 void BufferView::Pimpl::resize()
275 {
276         if (buffer_)
277                 resizeCurrentBuffer();
278 }
279
280
281 void BufferView::Pimpl::redraw()
282 {
283         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
284         workarea().redraw();
285 }
286
287
288 bool BufferView::Pimpl::fitCursor()
289 {
290         bool ret;
291
292         if (bv_->theLockingInset()) {
293                 bv_->theLockingInset()->fitInsetCursor(bv_);
294                 ret = true;
295         } else {
296                 ret = screen().fitCursor(bv_->text, bv_);
297         }
298
299         bv_->owner()->getDialogs()->updateParagraph();
300         if (ret)
301             updateScrollbar();
302         return ret;
303 }
304
305
306 void BufferView::Pimpl::redoCurrentBuffer()
307 {
308         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
309         if (buffer_ && bv_->text) {
310                 resize();
311                 owner_->updateLayoutChoice();
312         }
313 }
314
315
316 int BufferView::Pimpl::resizeCurrentBuffer()
317 {
318         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
319
320         Paragraph * par = 0;
321         Paragraph * selstartpar = 0;
322         Paragraph * selendpar = 0;
323         UpdatableInset * the_locking_inset = 0;
324
325         pos_type pos = 0;
326         pos_type selstartpos = 0;
327         pos_type selendpos = 0;
328         bool selection = false;
329         bool mark_set  = false;
330
331         owner_->prohibitInput();
332
333         owner_->message(_("Formatting document..."));
334
335         if (bv_->text) {
336                 par = bv_->text->cursor.par();
337                 pos = bv_->text->cursor.pos();
338                 selstartpar = bv_->text->selection.start.par();
339                 selstartpos = bv_->text->selection.start.pos();
340                 selendpar = bv_->text->selection.end.par();
341                 selendpos = bv_->text->selection.end.pos();
342                 selection = bv_->text->selection.set();
343                 mark_set = bv_->text->selection.mark();
344                 the_locking_inset = bv_->theLockingInset();
345                 buffer_->resizeInsets(bv_);
346                 // I don't think the delete and new are necessary here we just could
347                 // call only init! (Jug 20020419)
348                 delete bv_->text;
349                 bv_->text = new LyXText(bv_);
350                 bv_->text->init(bv_);
351         } else {
352                 // See if we have a text in TextCache that fits
353                 // the new buffer_ with the correct width.
354                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
355                 if (bv_->text) {
356                         if (lyxerr.debugging()) {
357                                 lyxerr << "Found a LyXText that fits:\n";
358                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
359                         }
360                         // Set the owner of the newly found text
361                         //      bv_->text->owner(bv_);
362                         if (lyxerr.debugging())
363                                 textcache.show(lyxerr, "resizeCurrentBuffer");
364                 } else {
365                         bv_->text = new LyXText(bv_);
366                         bv_->text->init(bv_);
367                         //buffer_->resizeInsets(bv_);
368                 }
369         }
370
371         updateScreen();
372
373         if (par) {
374                 bv_->text->selection.set(true);
375                 // At this point just to avoid the Delete-Empty-Paragraph-
376                 // Mechanism when setting the cursor.
377                 bv_->text->selection.mark(mark_set);
378                 if (selection) {
379                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
380                         bv_->text->selection.cursor = bv_->text->cursor;
381                         bv_->text->setCursor(bv_, selendpar, selendpos);
382                         bv_->text->setSelection(bv_);
383                         bv_->text->setCursor(bv_, par, pos);
384                 } else {
385                         bv_->text->setCursor(bv_, par, pos);
386                         bv_->text->selection.cursor = bv_->text->cursor;
387                         bv_->text->selection.set(false);
388                 }
389                 // remake the inset locking
390                 bv_->theLockingInset(the_locking_inset);
391         }
392
393         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
394
395         // this will scroll the screen such that the cursor becomes visible
396         updateScrollbar();
397         redraw();
398
399         setState();
400         owner_->allowInput();
401
402         /// clear the "Formatting Document" message
403         owner_->message("");
404
405         return 0;
406 }
407
408
409 void BufferView::Pimpl::updateScreen()
410 {
411         // Regenerate the screen.
412         screen().reset();
413 }
414
415
416 void BufferView::Pimpl::updateScrollbar()
417 {
418         if (!bv_->text) {
419                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
420                 workarea().setScrollbar(0, 1.0);
421                 return;
422         }
423
424         long const text_height = bv_->text->height;
425         long const work_height = workarea().workHeight();
426
427         double const lineh = bv_->text->defaultHeight();
428         double const slider_size =
429                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
430
431         lyxerr[Debug::GUI] << "text_height now " << text_height << endl;
432         lyxerr[Debug::GUI] << "work_height " << work_height << endl;
433
434         /* If the text is smaller than the working area, the scrollbar
435          * maximum must be the working area height. No scrolling will
436          * be possible */
437         if (text_height <= work_height) {
438                 lyxerr[Debug::GUI] << "doc smaller than workarea !" << endl;
439                 workarea().setScrollbarBounds(0.0, 0.0);
440                 current_scrollbar_value = bv_->text->first_y;
441                 workarea().setScrollbar(current_scrollbar_value, 1.0);
442                 return;
443         }
444
445         workarea().setScrollbarBounds(0.0, text_height - work_height);
446         workarea().setScrollbarIncrements(lineh);
447         current_scrollbar_value = bv_->text->first_y;
448         workarea().setScrollbar(current_scrollbar_value, slider_size);
449 }
450
451
452 // Callback for scrollbar slider
453 void BufferView::Pimpl::scrollCB(double value)
454 {
455         lyxerr[Debug::GUI] << "scrollCB of " << value << endl;
456
457         if (!buffer_) return;
458
459         current_scrollbar_value = long(value);
460
461         if (current_scrollbar_value < 0)
462                 current_scrollbar_value = 0;
463
464         screen().draw(bv_->text, bv_, current_scrollbar_value);
465
466         if (!lyxrc.cursor_follows_scrollbar) {
467                 waitForX();
468                 return;
469         }
470
471         LyXText * vbt = bv_->text;
472
473         int const height = vbt->defaultHeight();
474         int const first = static_cast<int>((bv_->text->first_y + height));
475         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
476
477         if (vbt->cursor.y() < first)
478                 vbt->setCursorFromCoordinates(bv_, 0, first);
479         else if (vbt->cursor.y() > last)
480                 vbt->setCursorFromCoordinates(bv_, 0, last);
481
482         waitForX();
483 }
484
485
486 int BufferView::Pimpl::scrollUp(long time)
487 {
488         if (!buffer_)
489                 return 0;
490
491         double value = workarea().getScrollbarValue();
492
493         if (value == 0)
494                 return 0;
495
496 #if 1
497         float add_value =  (bv_->text->defaultHeight()
498                             + float(time) * float(time) * 0.125);
499
500         if (add_value > workarea().workHeight())
501                 add_value = float(workarea().workHeight() -
502                                   bv_->text->defaultHeight());
503 #else
504         float add_value =  float(workarea().workHeight()) * float(time) / 100;
505 #endif
506
507         value -= add_value;
508
509         if (value < 0)
510                 value = 0;
511
512         workarea().setScrollbarValue(value);
513
514         scrollCB(value);
515         return 0;
516 }
517
518
519 int BufferView::Pimpl::scrollDown(long time)
520 {
521         if (!buffer_)
522                 return 0;
523
524         double value = workarea().getScrollbarValue();
525         pair<float, float> p = workarea().getScrollbarBounds();
526         double const max = p.second;
527
528         if (value == max)
529                 return 0;
530
531 #if 1
532         float add_value =  (bv_->text->defaultHeight()
533                             + float(time) * float(time) * 0.125);
534
535         if (add_value > workarea().workHeight())
536                 add_value = float(workarea().workHeight() -
537                                   bv_->text->defaultHeight());
538 #else
539         float add_value =  float(workarea().workHeight()) * float(time) / 100;
540 #endif
541
542         value += add_value;
543
544         if (value > max)
545                 value = max;
546
547         workarea().setScrollbarValue(value);
548
549         scrollCB(value);
550         return 0;
551 }
552
553
554 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, key_modifier::state state)
555 {
556         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
557 }
558
559
560 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, mouse_button::state state)
561 {
562         // Only use motion with button 1
563         if (!(state & mouse_button::button1))
564                 return;
565
566         if (!buffer_)
567                 return;
568
569         // Check for inset locking
570         if (bv_->theLockingInset()) {
571                 LyXCursor cursor = bv_->text->cursor;
572                 LyXFont font = bv_->text->getFont(buffer_,
573                                                   cursor.par(), cursor.pos());
574                 int width = bv_->theLockingInset()->width(bv_, font);
575                 int inset_x = font.isVisibleRightToLeft()
576                         ? cursor.ix() - width : cursor.ix();
577                 int start_x = inset_x + bv_->theLockingInset()->scroll();
578
579                 bv_->theLockingInset()->
580                         insetMotionNotify(bv_,
581                                           x - start_x,
582                                           y - cursor.iy() + bv_->text->first_y,
583                                           state);
584                 return;
585         }
586
587         /* The test for not selection possible is needed, that only motion
588            events are used, where the bottom press event was on
589            the drawing area too */
590         if (!selection_possible)
591                 return;
592
593         screen().hideCursor();
594
595         Row * cursorrow = bv_->text->cursor.row();
596         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
597 #if 0
598         // sorry for this but I have a strange error that the y value jumps at
599         // a certain point. This seems like an error in my xforms library or
600         // in some other local environment, but I would like to leave this here
601         // for the moment until I can remove this (Jug 20020418)
602         if (y_before < bv_->text->cursor.y())
603                 lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
604 #endif
605         // This is to allow jumping over large insets
606         if (cursorrow == bv_->text->cursor.row()) {
607                 if (y >= int(workarea().workHeight())) {
608                         bv_->text->cursorDown(bv_, false);
609                 } else if (y < 0) {
610                         bv_->text->cursorUp(bv_, false);
611                 }
612         }
613
614         if (!bv_->text->selection.set())
615                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
616
617         bv_->text->setSelection(bv_);
618         screen().toggleToggle(bv_->text, bv_);
619         fitCursor();
620         showCursor();
621 }
622
623
624 // Single-click on work area
625 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
626                                             mouse_button::state button)
627 {
628         if (!buffer_)
629                 return;
630
631         // ok ok, this is a hack (for xforms)
632
633         if (button == mouse_button::button4) {
634                 scrollUp(lyxrc.wheel_jump);
635                 // We shouldn't go further down as we really should only do the
636                 // scrolling and be done with this. Otherwise we may open some
637                 // dialogs (Jug 20020424).
638                 return;
639         } else if (button == mouse_button::button5) {
640                 scrollDown(lyxrc.wheel_jump);
641                 // We shouldn't go further down as we really should only do the
642                 // scrolling and be done with this. Otherwise we may open some
643                 // dialogs (Jug 20020424).
644                 return;
645         }
646
647         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
648
649         // Middle button press pastes if we have a selection
650         // We do this here as if the selection was inside an inset
651         // it could get cleared on the unlocking of the inset so
652         // we have to check this first
653         bool paste_internally = false;
654         if (button == mouse_button::button2 && bv_->getLyXText()->selection.set()) {
655                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
656                 paste_internally = true;
657         }
658
659         int const screen_first = bv_->text->first_y;
660
661         if (bv_->theLockingInset()) {
662                 // We are in inset locking mode
663
664                 /* Check whether the inset was hit. If not reset mode,
665                    otherwise give the event to the inset */
666                 if (inset_hit == bv_->theLockingInset()) {
667                         bv_->theLockingInset()->
668                                 insetButtonPress(bv_, xpos, ypos, button);
669                         return;
670                 } else {
671                         bv_->unlockInset(bv_->theLockingInset());
672                 }
673         }
674
675         if (!inset_hit)
676                 selection_possible = true;
677         screen().hideCursor();
678
679         // Clear the selection
680         screen().toggleSelection(bv_->text, bv_);
681         bv_->text->clearSelection();
682         bv_->text->fullRebreak(bv_);
683         update();
684         updateScrollbar();
685
686         // Single left click in math inset?
687         if (isHighlyEditableInset(inset_hit)) {
688                 // Highly editable inset, like math
689                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
690                 selection_possible = false;
691                 owner_->updateLayoutChoice();
692                 owner_->message(inset->editMessage());
693                 //inset->edit(bv_, xpos, ypos, button);
694                 // We just have to lock the inset before calling a PressEvent on it!
695                 // we don't need the edit() call here! (Jug20020329)
696                 if (!bv_->lockInset(inset)) {
697                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
698                 }
699                 inset->insetButtonPress(bv_, xpos, ypos, button);
700                 return;
701         }
702         // I'm not sure we should continue here if we hit an inset (Jug20020403)
703
704         // Right click on a footnote flag opens float menu
705         if (button == mouse_button::button3) {
706                 selection_possible = false;
707                 return;
708         }
709
710         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
711                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
712         finishUndo();
713         bv_->text->selection.cursor = bv_->text->cursor;
714         bv_->text->cursor.x_fix(bv_->text->cursor.x());
715
716         owner_->updateLayoutChoice();
717         if (fitCursor()) {
718                 selection_possible = false;
719         }
720
721         // Insert primary selection with middle mouse
722         // if there is a local selection in the current buffer,
723         // insert this
724         if (button == mouse_button::button2) {
725                 if (paste_internally)
726                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
727                 else
728                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
729                                                        "paragraph");
730                 selection_possible = false;
731                 return;
732         }
733 }
734
735
736 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, mouse_button::state button)
737 {
738         if (!buffer_)
739                 return;
740
741         LyXText * text = bv_->getLyXText();
742
743         if (text->bv_owner && bv_->theLockingInset())
744                 return;
745
746         if (button == mouse_button::button1) {
747                 if (text->bv_owner) {
748                         screen().hideCursor();
749                         screen().toggleSelection(text, bv_);
750                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
751                         screen().toggleSelection(text, bv_, false);
752                 } else {
753                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
754                 }
755                 /* This will fit the cursor on the screen
756                  * if necessary */
757                 update(text, BufferView::SELECT|BufferView::FITCUR);
758         }
759 }
760
761
762 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, mouse_button::state button)
763 {
764         if (!buffer_)
765                 return;
766
767         LyXText * text = bv_->getLyXText();
768
769         if (text->bv_owner && bv_->theLockingInset())
770             return;
771
772         if (button == mouse_button::button1) {
773                 if (text->bv_owner) {
774                         screen().hideCursor();
775                         screen().toggleSelection(text, bv_);
776                 }
777                 text->cursorHome(bv_);
778                 text->selection.cursor = text->cursor;
779                 text->cursorEnd(bv_);
780                 text->setSelection(bv_);
781                 if (text->bv_owner) {
782                         screen().toggleSelection(text, bv_, false);
783                 }
784                 /* This will fit the cursor on the screen
785                  * if necessary */
786                 update(text, BufferView::SELECT|BufferView::FITCUR);
787         }
788 }
789
790
791 void BufferView::Pimpl::selectionRequested()
792 {
793         static string sel;
794
795         if (!available())
796                 return;
797
798         LyXText * text = bv_->getLyXText();
799
800         if (text->selection.set() &&
801                 (!bv_->text->xsel_cache.set() ||
802                  text->selection.start != bv_->text->xsel_cache.start ||
803                  text->selection.end != bv_->text->xsel_cache.end))
804         {
805                 bv_->text->xsel_cache = text->selection;
806                 sel = text->selectionAsString(bv_->buffer(), false);
807         } else if (!text->selection.set()) {
808                 sel = string();
809                 bv_->text->xsel_cache.set(false);
810         }
811         if (!sel.empty()) {
812                 workarea().putClipboard(sel);
813         }
814 }
815
816
817 void BufferView::Pimpl::selectionLost()
818 {
819         if (available()) {
820                 hideCursor();
821                 toggleSelection();
822                 bv_->getLyXText()->clearSelection();
823                 showCursor();
824                 bv_->text->xsel_cache.set(false);
825         }
826 }
827
828
829 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
830                                               mouse_button::state button)
831 {
832         // do nothing if we used the mouse wheel
833         if (!buffer_ || button == mouse_button::button4 || button == mouse_button::button5)
834                 return;
835
836         // If we hit an inset, we have the inset coordinates in these
837         // and inset_hit points to the inset.  If we do not hit an
838         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
839         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
840
841         if (bv_->theLockingInset()) {
842                 // We are in inset locking mode.
843
844                 /* LyX does a kind of work-area grabbing for insets.
845                    Only a ButtonPress Event outside the inset will
846                    force a insetUnlock. */
847                 bv_->theLockingInset()->
848                         insetButtonRelease(bv_, x, y, button);
849                 return;
850         }
851
852         selection_possible = false;
853
854         if (button == mouse_button::button2)
855                 return;
856
857         // finish selection
858         if (button == mouse_button::button1) {
859                 workarea().haveSelection(bv_->getLyXText()->selection.set());
860         }
861
862         setState();
863         owner_->showState();
864         owner_->updateMenubar();
865         owner_->updateToolbar();
866
867         // Did we hit an editable inset?
868         if (inset_hit) {
869                 selection_possible = false;
870
871                 // if we reach this point with a selection, it
872                 // must mean we are currently selecting.
873                 // But we don't want to open the inset
874                 // because that is annoying for the user.
875                 // So just pretend we didn't hit it.
876                 // this is OK because a "kosher" ButtonRelease
877                 // will follow a ButtonPress that clears
878                 // the selection.
879                 // Note this also fixes selection drawing
880                 // problems if we end up opening an inset
881                 if (bv_->getLyXText()->selection.set())
882                         return;
883
884                 // CHECK fix this proper in 0.13
885                 // well, maybe 13.0 !!!!!!!!!
886
887                 // Following a ref shouldn't issue
888                 // a push on the undo-stack
889                 // anylonger, now that we have
890                 // keybindings for following
891                 // references and returning from
892                 // references.  IMHO though, it
893                 // should be the inset's own business
894                 // to push or not push on the undo
895                 // stack. They don't *have* to
896                 // alter the document...
897                 // (Joacim)
898                 // ...or maybe the SetCursorParUndo()
899                 // below isn't necessary at all anylonger?
900                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
901                         setCursorParUndo(bv_);
902                 }
903
904                 owner_->message(inset_hit->editMessage());
905
906                 if (isHighlyEditableInset(inset_hit)) {
907                         // Highly editable inset, like math
908                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
909                         inset->insetButtonRelease(bv_, x, y, button);
910                 } else {
911                         inset_hit->insetButtonRelease(bv_, x, y, button);
912                         // IMO this is a grosshack! Inset's should be changed so that
913                         // they call the actions they have to do with the insetButtonRel.
914                         // function and not in the edit(). This should be changed
915                         // (Jug 20020329)
916                         inset_hit->edit(bv_, x, y, button);
917                 }
918                 return;
919         }
920
921         // Maybe we want to edit a bibitem ale970302
922         if (bv_->text->cursor.par()->bibkey && x < 20 +
923             bibitemMaxWidth(bv_, textclasslist[buffer_->params.textclass].defaultfont())) {
924                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, mouse_button::none);
925         }
926
927         return;
928 }
929
930
931 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
932                                        LyXCursor const & cursor) const
933 {
934         Paragraph /*const*/ & par = *cursor.par();
935         pos_type const pos = cursor.pos();
936
937         lyx::Assert(par.getInset(pos));
938
939         Inset const & inset(*par.getInset(pos));
940
941         LyXFont const & font = text.getFont(buffer_, &par, pos);
942
943         int const width = inset.width(bv_, font);
944         int const inset_x = font.isVisibleRightToLeft()
945                 ? (cursor.ix() - width) : cursor.ix();
946
947         return Box(
948                 inset_x + inset.scroll(),
949                 inset_x + width,
950                 cursor.iy() - inset.ascent(bv_, font),
951                 cursor.iy() + inset.descent(bv_, font));
952 }
953
954
955 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
956                                       LyXCursor const & cursor,
957                                       int & x, int & y) const
958 {
959         pos_type const pos(cursor.pos());
960         Paragraph /*const*/ & par(*cursor.par());
961
962         if (pos >= par.size() || !par.isInset(pos)) {
963                 return 0;
964         }
965
966         Inset /*const*/ * inset = par.getInset(pos);
967
968         if (!isEditableInset(inset)) {
969                 return 0;
970         }
971
972         Box b(insetDimensions(text, cursor));
973
974         if (!b.contained(x, y)) {
975                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
976                         << " box " << b << endl;
977                 return 0;
978         }
979
980         text.setCursor(bv_, &par, pos, true);
981
982         x -= b.x1;
983         // The origin of an inset is on the baseline
984         y -= text.cursor.iy();
985
986         return inset;
987 }
988
989
990 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
991 {
992         int y_tmp = y + text->first_y;
993
994         LyXCursor cursor;
995         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
996
997         Inset * inset(checkInset(*text, cursor, x, y_tmp));
998
999         if (inset) {
1000                 y = y_tmp;
1001                 return inset;
1002         }
1003
1004         // look at previous position
1005
1006         if (cursor.pos() == 0) {
1007                 return 0;
1008         }
1009
1010         // move back one
1011         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
1012
1013         inset = checkInset(*text, cursor, x, y_tmp);
1014         if (inset) {
1015                 y = y_tmp;
1016         }
1017         return inset;
1018 }
1019
1020
1021 void BufferView::Pimpl::workAreaExpose()
1022 {
1023         static int work_area_width;
1024         static unsigned int work_area_height;
1025
1026         bool const widthChange = workarea().workWidth() != work_area_width;
1027         bool const heightChange = workarea().workHeight() != work_area_height;
1028
1029         // update from work area
1030         work_area_width = workarea().workWidth();
1031         work_area_height = workarea().workHeight();
1032         if (buffer_ != 0) {
1033                 if (widthChange) {
1034                         // The visible LyXView need a resize
1035                         owner_->resize();
1036
1037                         // Remove all texts from the textcache
1038                         // This is not _really_ what we want to do. What
1039                         // we really want to do is to delete in textcache
1040                         // that does not have a BufferView with matching
1041                         // width, but as long as we have only one BufferView
1042                         // deleting all gives the same result.
1043                         if (lyxerr.debugging())
1044                                 textcache.show(lyxerr, "Expose delete all");
1045                         textcache.clear();
1046                         buffer_->resizeInsets(bv_);
1047                 } else if (heightChange) {
1048                         // Rebuild image of current screen
1049                         updateScreen();
1050                         // fitCursor() ensures we don't jump back
1051                         // to the start of the document on vertical
1052                         // resize
1053                         fitCursor();
1054
1055                         // The main window size has changed, repaint most stuff
1056                         redraw();
1057                 } else {
1058                         screen().redraw(bv_->text, bv_);
1059                 }
1060         } else {
1061                 // Grey box when we don't have a buffer
1062                 workarea().greyOut();
1063         }
1064
1065         // always make sure that the scrollbar is sane.
1066         updateScrollbar();
1067         owner_->updateLayoutChoice();
1068         return;
1069 }
1070
1071
1072 void BufferView::Pimpl::update()
1073 {
1074         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
1075                 LyXText::text_status st = bv_->text->status();
1076                 screen().update(bv_->text, bv_);
1077                 bool fitc = false;
1078                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
1079                         bv_->text->fullRebreak(bv_);
1080                         st = LyXText::NEED_MORE_REFRESH;
1081                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
1082                                              bv_->text->cursor.pos());
1083                         if (bv_->text->selection.set()) {
1084                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
1085                                                      bv_->text->selection.start.par(),
1086                                                      bv_->text->selection.start.pos());
1087                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
1088                                                      bv_->text->selection.end.par(),
1089                                                      bv_->text->selection.end.pos());
1090                         }
1091                         fitc = true;
1092                         bv_->text->status(bv_, st);
1093                         screen().update(bv_->text, bv_);
1094                 }
1095                 // do this here instead of in the screen::update because of
1096                 // the above loop!
1097                 bv_->text->status(bv_, LyXText::UNCHANGED);
1098                 if (fitc)
1099                         fitCursor();
1100         }
1101 }
1102
1103 // Values used when calling update:
1104 // -3 - update
1105 // -2 - update, move sel_cursor if selection, fitcursor
1106 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1107 //  0 - update, move sel_cursor if selection, fitcursor
1108 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1109 //  3 - update, move sel_cursor if selection
1110 //
1111 // update -
1112 // a simple redraw of the parts that need refresh
1113 //
1114 // move sel_cursor if selection -
1115 // the text's sel_cursor is moved if there is selection is progress
1116 //
1117 // fitcursor -
1118 // fitCursor() is called and the scrollbar updated
1119 //
1120 // mark dirty -
1121 // the buffer is marked dirty.
1122 //
1123 // enum {
1124 //       UPDATE = 0,
1125 //       SELECT = 1,
1126 //       FITCUR = 2,
1127 //       CHANGE = 4
1128 // };
1129 //
1130 // UPDATE_ONLY = UPDATE;
1131 // UPDATE_SELECT = UPDATE | SELECT;
1132 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1133 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1134 //
1135 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1136 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1137 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1138 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1139 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1140
1141 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1142 {
1143         owner_->updateLayoutChoice();
1144
1145         if (!text->selection.set() && (f & SELECT)) {
1146                 text->selection.cursor = text->cursor;
1147         }
1148
1149         text->fullRebreak(bv_);
1150
1151         if (text->inset_owner) {
1152                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1153             updateInset(text->inset_owner, false);
1154         } else {
1155             update();
1156         }
1157
1158         if ((f & FITCUR)) {
1159                 fitCursor();
1160         }
1161
1162         if ((f & CHANGE)) {
1163                 buffer_->markDirty();
1164         }
1165 }
1166
1167
1168 // Callback for cursor timer
1169 void BufferView::Pimpl::cursorToggle()
1170 {
1171         if (!buffer_) {
1172                 cursor_timeout.restart();
1173                 return;
1174         }
1175
1176         /* FIXME */
1177         extern void reapSpellchecker(void);
1178         reapSpellchecker();
1179
1180         if (!bv_->theLockingInset()) {
1181                 screen().cursorToggle(bv_);
1182         } else {
1183                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1184         }
1185
1186         cursor_timeout.restart();
1187 }
1188
1189
1190 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1191 {
1192         if (!text->cursor.row()->previous()) {
1193                 if (text->first_y > 0) {
1194                         int new_y = bv_->text->first_y - workarea().workHeight();
1195                         screen().draw(bv_->text, bv_, new_y < 0 ? 0 : new_y);
1196                         updateScrollbar();
1197                 }
1198                 return;
1199         }
1200
1201         int y = text->first_y;
1202         Row * cursorrow = text->cursor.row();
1203
1204         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y);
1205         finishUndo();
1206
1207         int new_y;
1208         if (cursorrow == bv_->text->cursor.row()) {
1209                 // we have a row which is higher than the workarea so we leave the
1210                 // cursor on the start of the row and move only the draw up as soon
1211                 // as we move the cursor or do something while inside the row (it may
1212                 // span several workarea-heights) we'll move to the top again, but this
1213                 // is better than just jump down and only display part of the row.
1214                 new_y = bv_->text->first_y - workarea().workHeight();
1215         } else {
1216                 if (text->inset_owner) {
1217                         new_y = bv_->text->cursor.iy()
1218                                 + bv_->theLockingInset()->insetInInsetY() + y
1219                                 + text->cursor.row()->height()
1220                                 - workarea().workHeight() + 1;
1221                 } else {
1222                         new_y = text->cursor.y()
1223                                 - text->cursor.row()->baseline()
1224                                 + text->cursor.row()->height()
1225                                 - workarea().workHeight() + 1;
1226                 }
1227         }
1228         screen().draw(bv_->text, bv_,  new_y < 0 ? 0 : new_y);
1229         if (text->cursor.row()->previous()) {
1230                 LyXCursor cur;
1231                 text->setCursor(bv_, cur, text->cursor.row()->previous()->par(),
1232                                                 text->cursor.row()->previous()->pos(), false);
1233                 if (cur.y() > text->first_y) {
1234                         text->cursorUp(bv_, true);
1235                 }
1236         }
1237         updateScrollbar();
1238 }
1239
1240
1241 void BufferView::Pimpl::cursorNext(LyXText * text)
1242 {
1243         if (!text->cursor.row()->next()) {
1244                 int y = text->cursor.y() - text->cursor.row()->baseline() +
1245                         text->cursor.row()->height();
1246                 if (y > int(text->first_y + workarea().workHeight())) {
1247                         screen().draw(bv_->text, bv_,
1248                                                   bv_->text->first_y + workarea().workHeight());
1249                         updateScrollbar();
1250                 }
1251                 return;
1252         }
1253
1254         int y = text->first_y + workarea().workHeight();
1255         if (text->inset_owner && !text->first_y) {
1256                 y -= (bv_->text->cursor.iy()
1257                           - bv_->text->first_y
1258                           + bv_->theLockingInset()->insetInInsetY());
1259         }
1260
1261         text->getRowNearY(y);
1262
1263         Row * cursorrow = text->cursor.row();
1264         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea().workHeight());
1265         finishUndo();
1266
1267         int new_y;
1268         if (cursorrow == bv_->text->cursor.row()) {
1269                 // we have a row which is higher than the workarea so we leave the
1270                 // cursor on the start of the row and move only the draw down as soon
1271                 // as we move the cursor or do something while inside the row (it may
1272                 // span several workarea-heights) we'll move to the top again, but this
1273                 // is better than just jump down and only display part of the row.
1274                 new_y = bv_->text->first_y + workarea().workHeight();
1275         } else {
1276                 if (text->inset_owner) {
1277                         new_y = bv_->text->cursor.iy()
1278                                 + bv_->theLockingInset()->insetInInsetY()
1279                                 + y - text->cursor.row()->baseline();
1280                 } else {
1281                         new_y =  text->cursor.y() - text->cursor.row()->baseline();
1282                 }
1283         }
1284         screen().draw(bv_->text, bv_, new_y);
1285         if (text->cursor.row()->next()) {
1286                 LyXCursor cur;
1287                 text->setCursor(bv_, cur, text->cursor.row()->next()->par(),
1288                                                 text->cursor.row()->next()->pos(), false);
1289                 if (cur.y() < int(text->first_y + workarea().workHeight())) {
1290                         text->cursorDown(bv_, true);
1291                 }
1292         }
1293         updateScrollbar();
1294 }
1295
1296
1297 bool BufferView::Pimpl::available() const
1298 {
1299         if (buffer_ && bv_->text)
1300                 return true;
1301         return false;
1302 }
1303
1304
1305 void BufferView::Pimpl::beforeChange(LyXText * text)
1306 {
1307         toggleSelection();
1308         text->clearSelection();
1309 }
1310
1311
1312 void BufferView::Pimpl::savePosition(unsigned int i)
1313 {
1314         if (i >= saved_positions_num)
1315                 return;
1316         saved_positions[i] = Position(buffer_->fileName(),
1317                                       bv_->text->cursor.par()->id(),
1318                                       bv_->text->cursor.pos());
1319         if (i > 0) {
1320                 ostringstream str;
1321                 str << _("Saved bookmark") << ' ' << i;
1322                 owner_->message(str.str().c_str());
1323         }
1324 }
1325
1326
1327 void BufferView::Pimpl::restorePosition(unsigned int i)
1328 {
1329         if (i >= saved_positions_num)
1330                 return;
1331
1332         string const fname = saved_positions[i].filename;
1333
1334         beforeChange(bv_->text);
1335
1336         if (fname != buffer_->fileName()) {
1337                 Buffer * b = bufferlist.exists(fname) ?
1338                         bufferlist.getBuffer(fname) :
1339                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1340                 if (b != 0) buffer(b);
1341         }
1342
1343         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1344         if (!par)
1345                 return;
1346
1347         bv_->text->setCursor(bv_, par,
1348                              min(par->size(), saved_positions[i].par_pos));
1349
1350         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1351         if (i > 0) {
1352                 ostringstream str;
1353                 str << _("Moved to bookmark") << ' ' << i;
1354                 owner_->message(str.str().c_str());
1355         }
1356 }
1357
1358
1359 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1360 {
1361         if (i >= saved_positions_num)
1362                 return false;
1363
1364         return !saved_positions[i].filename.empty();
1365 }
1366
1367
1368 void BufferView::Pimpl::setState()
1369 {
1370         if (!lyxrc.rtl_support)
1371                 return;
1372
1373         LyXText * text = bv_->getLyXText();
1374         if (text->real_current_font.isRightToLeft()
1375             && !(bv_->theLockingInset()
1376                  && bv_->theLockingInset()->lyxCode()== Inset::ERT_CODE))
1377         {
1378                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1379                         owner_->getIntl()->KeyMapSec();
1380         } else {
1381                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1382                         owner_->getIntl()->KeyMapPrim();
1383         }
1384 }
1385
1386
1387 void BufferView::Pimpl::insetUnlock()
1388 {
1389         if (bv_->theLockingInset()) {
1390                 bv_->theLockingInset()->insetUnlock(bv_);
1391                 bv_->theLockingInset(0);
1392                 finishUndo();
1393         }
1394 }
1395
1396
1397 bool BufferView::Pimpl::focus() const
1398 {
1399         return workarea().hasFocus();
1400 }
1401
1402
1403 void BufferView::Pimpl::focus(bool f)
1404 {
1405         if (f) workarea().setFocus();
1406 }
1407
1408
1409 void BufferView::Pimpl::showCursor()
1410 {
1411         if (bv_->theLockingInset())
1412                 bv_->theLockingInset()->showInsetCursor(bv_);
1413         else
1414                 screen().showCursor(bv_->text, bv_);
1415 }
1416
1417
1418 void BufferView::Pimpl::hideCursor()
1419 {
1420         if (!bv_->theLockingInset())
1421                 screen().hideCursor();
1422 }
1423
1424
1425 void BufferView::Pimpl::toggleSelection(bool b)
1426 {
1427         if (bv_->theLockingInset())
1428                 bv_->theLockingInset()->toggleSelection(bv_, b);
1429         screen().toggleSelection(bv_->text, bv_, b);
1430 }
1431
1432
1433 void BufferView::Pimpl::toggleToggle()
1434 {
1435         screen().toggleToggle(bv_->text, bv_);
1436 }
1437
1438
1439 void BufferView::Pimpl::center()
1440 {
1441         beforeChange(bv_->text);
1442         if (bv_->text->cursor.y() > static_cast<int>((workarea().workHeight() / 2))) {
1443                 screen().draw(bv_->text, bv_, bv_->text->cursor.y() - workarea().workHeight() / 2);
1444         } else {
1445                 screen().draw(bv_->text, bv_, 0);
1446         }
1447         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1448         redraw();
1449 }
1450
1451
1452 void BufferView::Pimpl::pasteClipboard(bool asPara)
1453 {
1454         if (!buffer_)
1455                 return;
1456
1457         screen().hideCursor();
1458         beforeChange(bv_->text);
1459
1460         string const clip(workarea().getClipboard());
1461
1462         if (clip.empty())
1463                 return;
1464
1465         if (asPara) {
1466                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1467         } else {
1468                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1469         }
1470         bv_->getLyXText()->clearSelection();
1471         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1472 }
1473
1474
1475 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1476 {
1477         workarea().putClipboard(stuff);
1478 }
1479
1480
1481 /*
1482  * Dispatch functions for actions which can be valid for BufferView->text
1483  * and/or InsetText->text!!!
1484  */
1485
1486
1487 inline
1488 void BufferView::Pimpl::moveCursorUpdate(bool selecting, bool fitcur)
1489 {
1490         LyXText * lt = bv_->getLyXText();
1491
1492         if (selecting || lt->selection.mark()) {
1493                 lt->setSelection(bv_);
1494                 if (lt->bv_owner)
1495                         toggleToggle();
1496                 else
1497                         updateInset(lt->inset_owner, false);
1498         }
1499         if (lt->bv_owner) {
1500                 if (fitcur)
1501                         update(lt, BufferView::SELECT|BufferView::FITCUR);
1502                 else
1503                         update(lt, BufferView::SELECT);
1504                 showCursor();
1505         } else if (bv_->text->status() != LyXText::UNCHANGED) {
1506                 bv_->theLockingInset()->hideInsetCursor(bv_);
1507                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1508                 showCursor();
1509         }
1510
1511         if (!lt->selection.set())
1512                 workarea().haveSelection(false);
1513         
1514         /* ---> Everytime the cursor is moved, show the current font state. */
1515         // should this too me moved out of this func?
1516         //owner->showState();
1517         setState();
1518 }
1519
1520
1521 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1522 {
1523         LyXCursor cursor = bv_->getLyXText()->cursor;
1524         Buffer::inset_iterator it =
1525                 find_if(Buffer::inset_iterator(
1526                         cursor.par(), cursor.pos()),
1527                         buffer_->inset_iterator_end(),
1528                         lyx::compare_memfun(&Inset::lyxCode, code));
1529         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1530 }
1531
1532
1533 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1534 {
1535         string filename = filen;
1536
1537         if (filename.empty()) {
1538                 // Launch a file browser
1539                 string initpath = lyxrc.document_path;
1540
1541                 if (available()) {
1542                         string const trypath = owner_->buffer()->filePath();
1543                         // If directory is writeable, use this as default.
1544                         if (IsDirWriteable(trypath))
1545                                 initpath = trypath;
1546                 }
1547
1548                 FileDialog fileDlg(bv_->owner(),
1549                                    _("Select LyX document to insert"),
1550                         LFUN_FILE_INSERT,
1551                         make_pair(string(_("Documents|#o#O")),
1552                                   string(lyxrc.document_path)),
1553                         make_pair(string(_("Examples|#E#e")),
1554                                   string(AddPath(system_lyxdir, "examples"))));
1555
1556                 FileDialog::Result result =
1557                         fileDlg.Select(initpath,
1558                                        _("*.lyx| LyX Documents (*.lyx)"));
1559
1560                 if (result.first == FileDialog::Later)
1561                         return;
1562
1563                 filename = result.second;
1564
1565                 // check selected filename
1566                 if (filename.empty()) {
1567                         owner_->message(_("Canceled."));
1568                         return;
1569                 }
1570         }
1571
1572         // get absolute path of file and add ".lyx" to the filename if
1573         // necessary
1574         filename = FileSearch(string(), filename, "lyx");
1575
1576         string const disp_fn(MakeDisplayPath(filename));
1577
1578         ostringstream s1;
1579         s1 << _("Inserting document") << ' '
1580            << disp_fn << " ...";
1581         owner_->message(s1.str().c_str());
1582         bool const res = bv_->insertLyXFile(filename);
1583         if (res) {
1584                 ostringstream str;
1585                 str << _("Document") << ' ' << disp_fn
1586                     << ' ' << _("inserted.");
1587                 owner_->message(str.str().c_str());
1588         } else {
1589                 ostringstream str;
1590                 str << _("Could not insert document") << ' '
1591                     << disp_fn;
1592                 owner_->message(str.str().c_str());
1593         }
1594 }
1595
1596
1597 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1598 {
1599         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1600                               << action <<"] arg[" << argument << "]" << endl;
1601
1602         LyXTextClass const & tclass = textclasslist[buffer_->params.textclass];
1603
1604         switch (action) {
1605                 // --- Misc -------------------------------------------
1606         case LFUN_APPENDIX:
1607         {
1608                 if (available()) {
1609                         LyXText * lt = bv_->getLyXText();
1610                         lt->toggleAppendix(bv_);
1611                         update(lt,
1612                                BufferView::SELECT
1613                                | BufferView::FITCUR
1614                                | BufferView::CHANGE);
1615                 }
1616         }
1617         break;
1618
1619         case LFUN_TOC_INSERT:
1620         {
1621                 InsetCommandParams p;
1622                 p.setCmdName("tableofcontents");
1623                 Inset * inset = new InsetTOC(p);
1624                 if (!insertInset(inset, tclass.defaultLayoutName()))
1625                         delete inset;
1626                 break;
1627         }
1628
1629         case LFUN_SCROLL_INSET:
1630                 // this is not handled here as this funktion is only aktive
1631                 // if we have a locking_inset and that one is (or contains)
1632                 // a tabular-inset
1633                 break;
1634
1635         case LFUN_INSET_GRAPHICS:
1636         {
1637                 Inset * new_inset = new InsetGraphics;
1638                 if (!insertInset(new_inset)) {
1639                         delete new_inset;
1640                 } else {
1641                         // this is need because you don't use a inset->Edit()
1642                         updateInset(new_inset, true);
1643                         new_inset->edit(bv_);
1644                 }
1645                 break;
1646         }
1647
1648         case LFUN_PASTE:
1649                 bv_->paste();
1650                 setState();
1651                 break;
1652
1653         case LFUN_PASTESELECTION:
1654         {
1655                 bool asPara = false;
1656                 if (argument == "paragraph")
1657                         asPara = true;
1658                 pasteClipboard(asPara);
1659         }
1660         break;
1661
1662         case LFUN_CUT:
1663                 bv_->cut();
1664                 break;
1665
1666         case LFUN_COPY:
1667                 bv_->copy();
1668                 break;
1669
1670         case LFUN_LAYOUT_COPY:
1671                 bv_->copyEnvironment();
1672                 break;
1673
1674         case LFUN_LAYOUT_PASTE:
1675                 bv_->pasteEnvironment();
1676                 setState();
1677                 break;
1678
1679         case LFUN_GOTOERROR:
1680                 gotoInset(Inset::ERROR_CODE, false);
1681                 break;
1682
1683         case LFUN_GOTONOTE:
1684                 gotoInset(Inset::IGNORE_CODE, false);
1685                 break;
1686
1687         case LFUN_REFERENCE_GOTO:
1688         {
1689                 vector<Inset::Code> tmp;
1690                 tmp.push_back(Inset::LABEL_CODE);
1691                 tmp.push_back(Inset::REF_CODE);
1692                 gotoInset(tmp, true);
1693                 break;
1694         }
1695
1696         case LFUN_HYPHENATION:
1697                 specialChar(InsetSpecialChar::HYPHENATION);
1698                 break;
1699
1700         case LFUN_LIGATURE_BREAK:
1701                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1702                 break;
1703
1704         case LFUN_LDOTS:
1705                 specialChar(InsetSpecialChar::LDOTS);
1706                 break;
1707
1708         case LFUN_END_OF_SENTENCE:
1709                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1710                 break;
1711
1712         case LFUN_MENU_SEPARATOR:
1713                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1714                 break;
1715
1716         case LFUN_HFILL:
1717                 hfill();
1718                 break;
1719
1720         case LFUN_DEPTH_MIN:
1721                 changeDepth(bv_, bv_->getLyXText(), -1);
1722                 break;
1723
1724         case LFUN_DEPTH_PLUS:
1725                 changeDepth(bv_, bv_->getLyXText(), 1);
1726                 break;
1727
1728         case LFUN_FREE:
1729                 owner_->getDialogs()->setUserFreeFont();
1730                 break;
1731
1732         case LFUN_FILE_INSERT:
1733                 MenuInsertLyXFile(argument);
1734                 break;
1735
1736         case LFUN_FILE_INSERT_ASCII_PARA:
1737                 InsertAsciiFile(bv_, argument, true);
1738                 break;
1739
1740         case LFUN_FILE_INSERT_ASCII:
1741                 InsertAsciiFile(bv_, argument, false);
1742                 break;
1743
1744         case LFUN_LAYOUT:
1745         {
1746                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1747                                     << argument << endl;
1748
1749                 // This is not the good solution to the empty argument
1750                 // problem, but it will hopefully suffice for 1.2.0.
1751                 // The correct solution would be to augument the
1752                 // function list/array with information about what
1753                 // functions needs arguments and their type.
1754                 if (argument.empty()) {
1755                         owner_->getLyXFunc()->setErrorMessage(
1756                                 _("LyX function 'layout' needs an argument."));
1757                         break;
1758                 }
1759
1760                 // Derive layout number from given argument (string)
1761                 // and current buffer's textclass (number). */
1762                 bool hasLayout = tclass.hasLayout(argument);
1763                 string layout = argument;
1764
1765                 // If the entry is obsolete, use the new one instead.
1766                 if (hasLayout) {
1767                         string const & obs = tclass[layout].obsoleted_by();
1768                         if (!obs.empty())
1769                                 layout = obs;
1770                 }
1771
1772                 if (!hasLayout) {
1773                         owner_->getLyXFunc()->setErrorMessage(
1774                                 string(N_("Layout ")) + argument +
1775                                 N_(" not known"));
1776                         break;
1777                 }
1778
1779                 bool change_layout = (current_layout != layout);
1780                 LyXText * lt = bv_->getLyXText();
1781                 if (!change_layout && lt->selection.set() &&
1782                         lt->selection.start.par() != lt->selection.end.par())
1783                 {
1784                         Paragraph * spar = lt->selection.start.par();
1785                         Paragraph * epar = lt->selection.end.par()->next();
1786                         while(spar != epar) {
1787                                 if (spar->layout() != current_layout) {
1788                                         change_layout = true;
1789                                         break;
1790                                 }
1791                         }
1792                 }
1793                 if (change_layout) {
1794                         hideCursor();
1795                         current_layout = layout;
1796                         update(lt,
1797                                BufferView::SELECT
1798                                | BufferView::FITCUR);
1799                         lt->setLayout(bv_, layout);
1800                         owner_->setLayout(layout);
1801                         update(lt,
1802                                BufferView::SELECT
1803                                | BufferView::FITCUR
1804                                | BufferView::CHANGE);
1805                         setState();
1806                 }
1807         }
1808         break;
1809
1810         case LFUN_LANGUAGE:
1811                 lang(bv_, argument);
1812                 setState();
1813                 owner_->showState();
1814                 break;
1815
1816         case LFUN_EMPH:
1817                 emph(bv_);
1818                 owner_->showState();
1819                 break;
1820
1821         case LFUN_BOLD:
1822                 bold(bv_);
1823                 owner_->showState();
1824                 break;
1825
1826         case LFUN_NOUN:
1827                 noun(bv_);
1828                 owner_->showState();
1829                 break;
1830
1831         case LFUN_CODE:
1832                 code(bv_);
1833                 owner_->showState();
1834                 break;
1835
1836         case LFUN_SANS:
1837                 sans(bv_);
1838                 owner_->showState();
1839                 break;
1840
1841         case LFUN_ROMAN:
1842                 roman(bv_);
1843                 owner_->showState();
1844                 break;
1845
1846         case LFUN_DEFAULT:
1847                 styleReset(bv_);
1848                 owner_->showState();
1849                 break;
1850
1851         case LFUN_UNDERLINE:
1852                 underline(bv_);
1853                 owner_->showState();
1854                 break;
1855
1856         case LFUN_FONT_SIZE:
1857                 fontSize(bv_, argument);
1858                 owner_->showState();
1859                 break;
1860
1861         case LFUN_FONT_STATE:
1862                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1863                 break;
1864
1865         case LFUN_UPCASE_WORD:
1866         {
1867                 LyXText * lt = bv_->getLyXText();
1868
1869                 update(lt,
1870                        BufferView::SELECT
1871                        | BufferView::FITCUR);
1872                 lt->changeCase(bv_, LyXText::text_uppercase);
1873                 if (lt->inset_owner)
1874                         updateInset(lt->inset_owner, true);
1875                 update(lt,
1876                        BufferView::SELECT
1877                        | BufferView::FITCUR
1878                        | BufferView::CHANGE);
1879         }
1880         break;
1881
1882         case LFUN_LOWCASE_WORD:
1883         {
1884                 LyXText * lt = bv_->getLyXText();
1885
1886                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1887                 lt->changeCase(bv_, LyXText::text_lowercase);
1888                 if (lt->inset_owner)
1889                         updateInset(lt->inset_owner, true);
1890                 update(lt,
1891                        BufferView::SELECT
1892                        | BufferView::FITCUR
1893                        | BufferView::CHANGE);
1894         }
1895         break;
1896
1897         case LFUN_CAPITALIZE_WORD:
1898         {
1899                 LyXText * lt = bv_->getLyXText();
1900
1901                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1902                 lt->changeCase(bv_, LyXText::text_capitalization);
1903                 if (lt->inset_owner)
1904                         updateInset(lt->inset_owner, true);
1905                 update(lt,
1906                        BufferView::SELECT
1907                        | BufferView::FITCUR
1908                        | BufferView::CHANGE);
1909         }
1910         break;
1911
1912         case LFUN_TRANSPOSE_CHARS:
1913         {
1914                 LyXText * lt = bv_->getLyXText();
1915
1916                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1917                 lt->transposeChars(*bv_);
1918                 if (lt->inset_owner)
1919                         updateInset(lt->inset_owner, true);
1920                 update(lt,
1921                        BufferView::SELECT
1922                        | BufferView::FITCUR
1923                        | BufferView::CHANGE);
1924         }
1925         break;
1926
1927
1928         case LFUN_INSERT_LABEL:
1929                 MenuInsertLabel(bv_, argument);
1930                 break;
1931
1932         case LFUN_REF_INSERT:
1933                 if (argument.empty()) {
1934                         InsetCommandParams p("ref");
1935                         owner_->getDialogs()->createRef(p.getAsString());
1936                 } else {
1937                         InsetCommandParams p;
1938                         p.setFromString(argument);
1939
1940                         InsetRef * inset = new InsetRef(p, *buffer_);
1941                         if (!insertInset(inset))
1942                                 delete inset;
1943                         else
1944                                 updateInset(inset, true);
1945                 }
1946                 break;
1947
1948         case LFUN_BOOKMARK_SAVE:
1949                 savePosition(strToUnsignedInt(argument));
1950                 break;
1951
1952         case LFUN_BOOKMARK_GOTO:
1953                 restorePosition(strToUnsignedInt(argument));
1954                 break;
1955
1956         case LFUN_REF_GOTO:
1957         {
1958                 string label(argument);
1959                 if (label.empty()) {
1960                         InsetRef * inset =
1961                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1962                         if (inset) {
1963                                 label = inset->getContents();
1964                                 savePosition(0);
1965                         }
1966                 }
1967
1968                 if (!label.empty()) {
1969                         //bv_->savePosition(0);
1970                         if (!bv_->gotoLabel(label))
1971                                 Alert::alert(_("Error"),
1972                                            _("Couldn't find this label"),
1973                                            _("in current document."));
1974                 }
1975         }
1976         break;
1977
1978                 // --- Cursor Movements -----------------------------
1979         case LFUN_RIGHT:
1980         {
1981                 LyXText * lt = bv_->getLyXText();
1982
1983                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1984                 if (!lt->selection.mark())
1985                         beforeChange(lt);
1986                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1987                 if (is_rtl)
1988                         lt->cursorLeft(bv_, false);
1989                 if (lt->cursor.pos() < lt->cursor.par()->size()
1990                     && lt->cursor.par()->isInset(lt->cursor.pos())
1991                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1992                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1993                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1994                         if (is_rtl)
1995                                 tmpinset->edit(bv_, false);
1996                         else
1997                                 tmpinset->edit(bv_);
1998                         break;
1999                 }
2000                 if (!is_rtl)
2001                         lt->cursorRight(bv_, false);
2002                 finishUndo();
2003                 moveCursorUpdate(false);
2004                 owner_->showState();
2005         }
2006         break;
2007
2008         case LFUN_LEFT:
2009         {
2010                 // This is soooo ugly. Isn`t it possible to make
2011                 // it simpler? (Lgb)
2012                 LyXText * lt = bv_->getLyXText();
2013                 bool const is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
2014                 if (!lt->selection.mark())
2015                         beforeChange(lt);
2016                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2017                 LyXCursor const cur = lt->cursor;
2018                 if (!is_rtl)
2019                         lt->cursorLeft(bv_, false);
2020                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
2021                     lt->cursor.pos() < lt->cursor.par()->size() &&
2022                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
2023                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
2024                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
2025                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
2026                         if (is_rtl)
2027                                 tmpinset->edit(bv_);
2028                         else
2029                                 tmpinset->edit(bv_, false);
2030                         break;
2031                 }
2032                 if  (is_rtl)
2033                         lt->cursorRight(bv_, false);
2034
2035                 finishUndo();
2036                 moveCursorUpdate(false);
2037                 owner_->showState();
2038         }
2039         break;
2040
2041         case LFUN_UP:
2042         {
2043                 LyXText * lt = bv_->getLyXText();
2044
2045                 if (!lt->selection.mark())
2046                         beforeChange(lt);
2047                 update(lt, BufferView::UPDATE);
2048                 lt->cursorUp(bv_);
2049                 finishUndo();
2050                 moveCursorUpdate(false);
2051                 owner_->showState();
2052         }
2053         break;
2054
2055         case LFUN_DOWN:
2056         {
2057                 LyXText * lt = bv_->getLyXText();
2058
2059                 if (!lt->selection.mark())
2060                         beforeChange(lt);
2061                 update(lt, BufferView::UPDATE);
2062                 lt->cursorDown(bv_);
2063                 finishUndo();
2064                 moveCursorUpdate(false);
2065                 owner_->showState();
2066         }
2067         break;
2068
2069         case LFUN_UP_PARAGRAPH:
2070         {
2071                 LyXText * lt = bv_->getLyXText();
2072
2073                 if (!lt->selection.mark())
2074                         beforeChange(lt);
2075                 update(lt, BufferView::UPDATE);
2076                 lt->cursorUpParagraph(bv_);
2077                 finishUndo();
2078                 moveCursorUpdate(false);
2079                 owner_->showState();
2080         }
2081         break;
2082
2083         case LFUN_DOWN_PARAGRAPH:
2084         {
2085                 LyXText * lt = bv_->getLyXText();
2086
2087                 if (!lt->selection.mark())
2088                         beforeChange(lt);
2089                 update(lt, BufferView::UPDATE);
2090                 lt->cursorDownParagraph(bv_);
2091                 finishUndo();
2092                 moveCursorUpdate(false);
2093                 owner_->showState();
2094         }
2095         break;
2096
2097         case LFUN_PRIOR:
2098         {
2099                 LyXText * lt = bv_->getLyXText();
2100
2101                 if (!lt->selection.mark())
2102                         beforeChange(lt);
2103                 update(lt, BufferView::UPDATE);
2104                 cursorPrevious(lt);
2105                 finishUndo();
2106                 moveCursorUpdate(false, false);
2107                 owner_->showState();
2108         }
2109         break;
2110
2111         case LFUN_NEXT:
2112         {
2113                 LyXText * lt = bv_->getLyXText();
2114
2115                 if (!lt->selection.mark())
2116                         beforeChange(lt);
2117                 update(lt, BufferView::UPDATE);
2118                 cursorNext(lt);
2119                 finishUndo();
2120                 moveCursorUpdate(false, false);
2121                 owner_->showState();
2122         }
2123         break;
2124
2125         case LFUN_HOME:
2126         {
2127                 LyXText * lt = bv_->getLyXText();
2128
2129                 if (!lt->selection.mark())
2130                         beforeChange(lt);
2131                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2132                 lt->cursorHome(bv_);
2133                 finishUndo();
2134                 moveCursorUpdate(false);
2135                 owner_->showState();
2136         }
2137         break;
2138
2139         case LFUN_END:
2140         {
2141                 LyXText * lt = bv_->getLyXText();
2142
2143                 if (!lt->selection.mark())
2144                         beforeChange(lt);
2145                 update(lt,
2146                        BufferView::SELECT|BufferView::FITCUR);
2147                 lt->cursorEnd(bv_);
2148                 finishUndo();
2149                 moveCursorUpdate(false);
2150                 owner_->showState();
2151         }
2152         break;
2153
2154         case LFUN_SHIFT_TAB:
2155         case LFUN_TAB:
2156         {
2157                 LyXText * lt = bv_->getLyXText();
2158
2159                 if (!lt->selection.mark())
2160                         beforeChange(lt);
2161                 update(lt,
2162                        BufferView::SELECT|BufferView::FITCUR);
2163                 lt->cursorTab(bv_);
2164                 finishUndo();
2165                 moveCursorUpdate(false);
2166                 owner_->showState();
2167         }
2168         break;
2169
2170         case LFUN_WORDRIGHT:
2171         {
2172                 LyXText * lt = bv_->getLyXText();
2173
2174                 if (!lt->selection.mark())
2175                         beforeChange(lt);
2176                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2177                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2178                         lt->cursorLeftOneWord(bv_);
2179                 else
2180                         lt->cursorRightOneWord(bv_);
2181                 finishUndo();
2182                 moveCursorUpdate(false);
2183                 owner_->showState();
2184         }
2185         break;
2186
2187         case LFUN_WORDLEFT:
2188         {
2189                 LyXText * lt = bv_->getLyXText();
2190
2191                 if (!lt->selection.mark())
2192                         beforeChange(lt);
2193                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2194                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2195                         lt->cursorRightOneWord(bv_);
2196                 else
2197                         lt->cursorLeftOneWord(bv_);
2198                 finishUndo();
2199                 moveCursorUpdate(false);
2200                 owner_->showState();
2201         }
2202         break;
2203
2204         case LFUN_BEGINNINGBUF:
2205         {
2206                 LyXText * lt = bv_->getLyXText();
2207
2208                 if (!lt->selection.mark())
2209                         beforeChange(lt);
2210                 update(lt,
2211                        BufferView::SELECT|BufferView::FITCUR);
2212                 lt->cursorTop(bv_);
2213                 finishUndo();
2214                 moveCursorUpdate(false);
2215                 owner_->showState();
2216         }
2217         break;
2218
2219         case LFUN_ENDBUF:
2220         {
2221                 LyXText * lt = bv_->getLyXText();
2222
2223                 if (!lt->selection.mark())
2224                         beforeChange(lt);
2225                 update(lt,
2226                        BufferView::SELECT|BufferView::FITCUR);
2227                 lt->cursorBottom(bv_);
2228                 finishUndo();
2229                 moveCursorUpdate(false);
2230                 owner_->showState();
2231         }
2232         break;
2233
2234                 /* cursor selection ---------------------------- */
2235         case LFUN_RIGHTSEL:
2236         {
2237                 LyXText * lt = bv_->getLyXText();
2238
2239                 update(lt,
2240                        BufferView::SELECT|BufferView::FITCUR);
2241                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2242                         lt->cursorLeft(bv_);
2243                 else
2244                         lt->cursorRight(bv_);
2245                 finishUndo();
2246                 moveCursorUpdate(true);
2247                 owner_->showState();
2248         }
2249         break;
2250
2251         case LFUN_LEFTSEL:
2252         {
2253                 LyXText * lt = bv_->getLyXText();
2254
2255                 update(lt,
2256                        BufferView::SELECT|BufferView::FITCUR);
2257                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2258                         lt->cursorRight(bv_);
2259                 else
2260                         lt->cursorLeft(bv_);
2261                 finishUndo();
2262                 moveCursorUpdate(true);
2263                 owner_->showState();
2264         }
2265         break;
2266
2267         case LFUN_UPSEL:
2268         {
2269                 LyXText * lt = bv_->getLyXText();
2270
2271                 update(lt,
2272                        BufferView::SELECT|BufferView::FITCUR);
2273                 lt->cursorUp(bv_, true);
2274                 finishUndo();
2275                 moveCursorUpdate(true);
2276                 owner_->showState();
2277         }
2278         break;
2279
2280         case LFUN_DOWNSEL:
2281         {
2282                 LyXText * lt = bv_->getLyXText();
2283
2284                 update(lt,
2285                        BufferView::SELECT|BufferView::FITCUR);
2286                 lt->cursorDown(bv_, true);
2287                 finishUndo();
2288                 moveCursorUpdate(true);
2289                 owner_->showState();
2290         }
2291         break;
2292
2293         case LFUN_UP_PARAGRAPHSEL:
2294         {
2295                 LyXText * lt = bv_->getLyXText();
2296
2297                 update(lt,
2298                        BufferView::SELECT|BufferView::FITCUR);
2299                 lt->cursorUpParagraph(bv_);
2300                 finishUndo();
2301                 moveCursorUpdate(true);
2302                 owner_->showState();
2303         }
2304         break;
2305
2306         case LFUN_DOWN_PARAGRAPHSEL:
2307         {
2308                 LyXText * lt = bv_->getLyXText();
2309
2310                 update(lt,
2311                        BufferView::SELECT|BufferView::FITCUR);
2312                 lt->cursorDownParagraph(bv_);
2313                 finishUndo();
2314                 moveCursorUpdate(true);
2315                 owner_->showState();
2316         }
2317         break;
2318
2319         case LFUN_PRIORSEL:
2320         {
2321                 LyXText * lt = bv_->getLyXText();
2322
2323                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2324                 cursorPrevious(lt);
2325                 finishUndo();
2326                 moveCursorUpdate(true);
2327                 owner_->showState();
2328         }
2329         break;
2330
2331         case LFUN_NEXTSEL:
2332         {
2333                 LyXText * lt = bv_->getLyXText();
2334
2335                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2336                 cursorNext(lt);
2337                 finishUndo();
2338                 moveCursorUpdate(true);
2339                 owner_->showState();
2340         }
2341         break;
2342
2343         case LFUN_HOMESEL:
2344         {
2345                 LyXText * lt = bv_->getLyXText();
2346
2347                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2348                 lt->cursorHome(bv_);
2349                 finishUndo();
2350                 moveCursorUpdate(true);
2351                 owner_->showState();
2352         }
2353         break;
2354
2355         case LFUN_ENDSEL:
2356         {
2357                 LyXText * lt = bv_->getLyXText();
2358
2359                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2360                 lt->cursorEnd(bv_);
2361                 finishUndo();
2362                 moveCursorUpdate(true);
2363                 owner_->showState();
2364         }
2365         break;
2366
2367         case LFUN_WORDRIGHTSEL:
2368         {
2369                 LyXText * lt = bv_->getLyXText();
2370
2371                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2372                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2373                         lt->cursorLeftOneWord(bv_);
2374                 else
2375                         lt->cursorRightOneWord(bv_);
2376                 finishUndo();
2377                 moveCursorUpdate(true);
2378                 owner_->showState();
2379         }
2380         break;
2381
2382         case LFUN_WORDLEFTSEL:
2383         {
2384                 LyXText * lt = bv_->getLyXText();
2385
2386                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2387                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2388                         lt->cursorRightOneWord(bv_);
2389                 else
2390                         lt->cursorLeftOneWord(bv_);
2391                 finishUndo();
2392                 moveCursorUpdate(true);
2393                 owner_->showState();
2394         }
2395         break;
2396
2397         case LFUN_BEGINNINGBUFSEL:
2398         {
2399                 LyXText * lt = bv_->getLyXText();
2400
2401                 if (lt->inset_owner)
2402                         break;
2403                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2404                 lt->cursorTop(bv_);
2405                 finishUndo();
2406                 moveCursorUpdate(true);
2407                 owner_->showState();
2408         }
2409         break;
2410
2411         case LFUN_ENDBUFSEL:
2412         {
2413                 LyXText * lt = bv_->getLyXText();
2414
2415                 if (lt->inset_owner)
2416                         break;
2417                 update(lt,
2418                        BufferView::SELECT|BufferView::FITCUR);
2419                 lt->cursorBottom(bv_);
2420                 finishUndo();
2421                 moveCursorUpdate(true);
2422                 owner_->showState();
2423         }
2424         break;
2425
2426                 // --- text changing commands ------------------------
2427         case LFUN_BREAKLINE:
2428         {
2429                 LyXText * lt = bv_->getLyXText();
2430
2431                 beforeChange(lt);
2432                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2433                 update(lt,
2434                        BufferView::SELECT
2435                        | BufferView::FITCUR
2436                        | BufferView::CHANGE);
2437                 lt->setCursor(bv_, lt->cursor.par(), lt->cursor.pos());
2438                 moveCursorUpdate(false);
2439         }
2440         break;
2441
2442         case LFUN_PROTECTEDSPACE:
2443         {
2444                 LyXText * lt = bv_->getLyXText();
2445
2446                 LyXLayout const & style = tclass[lt->cursor.par()->layout()];
2447
2448                 if (style.free_spacing) {
2449                         lt->insertChar(bv_, ' ');
2450                         update(lt,
2451                                BufferView::SELECT
2452                                | BufferView::FITCUR
2453                                | BufferView::CHANGE);
2454                 } else {
2455                         specialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
2456                 }
2457                 moveCursorUpdate(false);
2458         }
2459         break;
2460
2461         case LFUN_SETMARK:
2462         {
2463                 LyXText * lt = bv_->getLyXText();
2464
2465                 if (lt->selection.mark()) {
2466                         beforeChange(lt);
2467                         update(lt,
2468                                BufferView::SELECT
2469                                | BufferView::FITCUR);
2470                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2471                 } else {
2472                         beforeChange(lt);
2473                         lt->selection.mark(true);
2474                         update(lt,
2475                                BufferView::SELECT
2476                                | BufferView::FITCUR);
2477                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2478                 }
2479                 lt->selection.cursor = lt->cursor;
2480         }
2481         break;
2482
2483         case LFUN_DELETE:
2484         {
2485                 LyXText * lt = bv_->getLyXText();
2486
2487                 if (!lt->selection.set()) {
2488                         lt->Delete(bv_);
2489                         lt->selection.cursor = lt->cursor;
2490                         update(lt,
2491                                BufferView::SELECT
2492                                | BufferView::FITCUR
2493                                | BufferView::CHANGE);
2494                         // It is possible to make it a lot faster still
2495                         // just comment out the line below...
2496                         showCursor();
2497                 } else {
2498                         bv_->cut(false);
2499                 }
2500                 moveCursorUpdate(false);
2501                 owner_->showState();
2502                 setState();
2503         }
2504         break;
2505
2506         case LFUN_DELETE_SKIP:
2507         {
2508                 LyXText * lt = bv_->getLyXText();
2509
2510                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2511
2512                 LyXCursor cursor = lt->cursor;
2513
2514                 if (!lt->selection.set()) {
2515                         if (cursor.pos() == cursor.par()->size()) {
2516                                 lt->cursorRight(bv_);
2517                                 cursor = lt->cursor;
2518                                 if (cursor.pos() == 0
2519                                     && !(cursor.par()->params().spaceTop()
2520                                          == VSpace (VSpace::NONE))) {
2521                                         lt->setParagraph
2522                                                 (bv_,
2523                                                  cursor.par()->params().lineTop(),
2524                                                  cursor.par()->params().lineBottom(),
2525                                                  cursor.par()->params().pagebreakTop(),
2526                                                  cursor.par()->params().pagebreakBottom(),
2527                                                  VSpace(VSpace::NONE),
2528                                                  cursor.par()->params().spaceBottom(),
2529                                                  cursor.par()->params().spacing(),
2530                                                  cursor.par()->params().align(),
2531                                                  cursor.par()->params().labelWidthString(), 0);
2532                                         lt->cursorLeft(bv_);
2533                                         update(lt,
2534                                                BufferView::SELECT
2535                                                | BufferView::FITCUR
2536                                                | BufferView::CHANGE);
2537                                 } else {
2538                                         lt->cursorLeft(bv_);
2539                                         lt->Delete(bv_);
2540                                         lt->selection.cursor = lt->cursor;
2541                                         update(lt,
2542                                                BufferView::SELECT
2543                                                | BufferView::FITCUR
2544                                                | BufferView::CHANGE);
2545                                 }
2546                         } else {
2547                                 lt->Delete(bv_);
2548                                 lt->selection.cursor = lt->cursor;
2549                                 update(lt,
2550                                        BufferView::SELECT
2551                                        | BufferView::FITCUR
2552                                        | BufferView::CHANGE);
2553                         }
2554                 } else {
2555                         bv_->cut(false);
2556                 }
2557         }
2558         break;
2559
2560         /* -------> Delete word forward. */
2561         case LFUN_DELETE_WORD_FORWARD:
2562                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2563                 bv_->getLyXText()->deleteWordForward(bv_);
2564                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2565                 moveCursorUpdate(false);
2566                 owner_->showState();
2567                 break;
2568
2569                 /* -------> Delete word backward. */
2570         case LFUN_DELETE_WORD_BACKWARD:
2571         {
2572                 LyXText * lt = bv_->getLyXText();
2573
2574                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2575                 lt->deleteWordBackward(bv_);
2576                 update(lt,
2577                        BufferView::SELECT
2578                        | BufferView::FITCUR
2579                        | BufferView::CHANGE);
2580                 moveCursorUpdate(false);
2581                 owner_->showState();
2582         }
2583         break;
2584
2585                 /* -------> Kill to end of line. */
2586         case LFUN_DELETE_LINE_FORWARD:
2587         {
2588                 LyXText * lt = bv_->getLyXText();
2589
2590                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2591                 lt->deleteLineForward(bv_);
2592                 update(lt,
2593                        BufferView::SELECT
2594                        | BufferView::FITCUR
2595                        | BufferView::CHANGE);
2596                 moveCursorUpdate(false);
2597         }
2598         break;
2599
2600                 /* -------> Set mark off. */
2601         case LFUN_MARK_OFF:
2602         {
2603                 LyXText * lt = bv_->getLyXText();
2604
2605                 beforeChange(lt);
2606                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2607                 lt->selection.cursor = lt->cursor;
2608                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2609         }
2610         break;
2611
2612                 /* -------> Set mark on. */
2613         case LFUN_MARK_ON:
2614         {
2615                 LyXText * lt = bv_->getLyXText();
2616
2617                 beforeChange(lt);
2618                 lt->selection.mark(true);
2619                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2620                 lt->selection.cursor = lt->cursor;
2621                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2622         }
2623         break;
2624
2625         case LFUN_BACKSPACE:
2626         {
2627                 LyXText * lt = bv_->getLyXText();
2628
2629                 if (!lt->selection.set()) {
2630                         if (owner_->getIntl()->getTrans().backspace()) {
2631                                 lt->backspace(bv_);
2632                                 lt->selection.cursor = lt->cursor;
2633                                 update(lt,
2634                                        BufferView::SELECT
2635                                        | BufferView::FITCUR
2636                                        | BufferView::CHANGE);
2637                                 // It is possible to make it a lot faster still
2638                                 // just comment out the line below...
2639                                 showCursor();
2640                         }
2641                 } else {
2642                         bv_->cut(false);
2643                 }
2644                 owner_->showState();
2645                 setState();
2646         }
2647         break;
2648
2649         case LFUN_BACKSPACE_SKIP:
2650         {
2651                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2652                 LyXText * lt = bv_->getLyXText();
2653
2654                 LyXCursor cursor = lt->cursor;
2655
2656                 if (!lt->selection.set()) {
2657                         if (cursor.pos() == 0
2658                             && !(cursor.par()->params().spaceTop()
2659                                  == VSpace (VSpace::NONE))) {
2660                                 lt->setParagraph
2661                                         (bv_,
2662                                          cursor.par()->params().lineTop(),
2663                                          cursor.par()->params().lineBottom(),
2664                                          cursor.par()->params().pagebreakTop(),
2665                                          cursor.par()->params().pagebreakBottom(),
2666                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2667                                          cursor.par()->params().spacing(),
2668                                          cursor.par()->params().align(),
2669                                          cursor.par()->params().labelWidthString(), 0);
2670                                 update(lt,
2671                                        BufferView::SELECT
2672                                        | BufferView::FITCUR
2673                                        | BufferView::CHANGE);
2674                         } else {
2675                                 lt->backspace(bv_);
2676                                 lt->selection.cursor = cursor;
2677                                 update(lt,
2678                                        BufferView::SELECT
2679                                        | BufferView::FITCUR
2680                                        | BufferView::CHANGE);
2681                         }
2682                 } else
2683                         bv_->cut(false);
2684         }
2685         break;
2686
2687         case LFUN_BREAKPARAGRAPH:
2688         {
2689                 LyXText * lt = bv_->getLyXText();
2690
2691                 beforeChange(lt);
2692                 lt->breakParagraph(bv_, 0);
2693                 update(lt,
2694                        BufferView::SELECT
2695                        | BufferView::FITCUR
2696                        | BufferView::CHANGE);
2697                 lt->selection.cursor = lt->cursor;
2698                 setState();
2699                 owner_->showState();
2700                 break;
2701         }
2702
2703         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2704         {
2705                 LyXText * lt = bv_->getLyXText();
2706
2707                 beforeChange(lt);
2708                 lt->breakParagraph(bv_, 1);
2709                 update(lt,
2710                        BufferView::SELECT
2711                        | BufferView::FITCUR
2712                        | BufferView::CHANGE);
2713                 lt->selection.cursor = lt->cursor;
2714                 setState();
2715                 owner_->showState();
2716                 break;
2717         }
2718
2719         case LFUN_BREAKPARAGRAPH_SKIP:
2720         {
2721                 // When at the beginning of a paragraph, remove
2722                 // indentation and add a "defskip" at the top.
2723                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2724                 LyXText * lt = bv_->getLyXText();
2725
2726                 LyXCursor cursor = lt->cursor;
2727
2728                 beforeChange(lt);
2729                 if (cursor.pos() == 0) {
2730                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2731                                 lt->setParagraph
2732                                         (bv_,
2733                                          cursor.par()->params().lineTop(),
2734                                          cursor.par()->params().lineBottom(),
2735                                          cursor.par()->params().pagebreakTop(),
2736                                          cursor.par()->params().pagebreakBottom(),
2737                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2738                                          cursor.par()->params().spacing(),
2739                                          cursor.par()->params().align(),
2740                                          cursor.par()->params().labelWidthString(), 1);
2741                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2742                         }
2743                 }
2744                 else {
2745                         lt->breakParagraph(bv_, 0);
2746                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2747                 }
2748
2749                 update(lt,
2750                        BufferView::SELECT
2751                        | BufferView::FITCUR
2752                        | BufferView::CHANGE);
2753                 lt->selection.cursor = cursor;
2754                 setState();
2755                 owner_->showState();
2756         }
2757         break;
2758
2759         case LFUN_PARAGRAPH_SPACING:
2760         {
2761                 LyXText * lt = bv_->getLyXText();
2762
2763                 Paragraph * par = lt->cursor.par();
2764                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2765                 float cur_value = 1.0;
2766                 if (cur_spacing == Spacing::Other) {
2767                         cur_value = par->params().spacing().getValue();
2768                 }
2769
2770                 istringstream istr(argument.c_str());
2771
2772                 string tmp;
2773                 istr >> tmp;
2774                 Spacing::Space new_spacing = cur_spacing;
2775                 float new_value = cur_value;
2776                 if (tmp.empty()) {
2777                         lyxerr << "Missing argument to `paragraph-spacing'"
2778                                << endl;
2779                 } else if (tmp == "single") {
2780                         new_spacing = Spacing::Single;
2781                 } else if (tmp == "onehalf") {
2782                         new_spacing = Spacing::Onehalf;
2783                 } else if (tmp == "double") {
2784                         new_spacing = Spacing::Double;
2785                 } else if (tmp == "other") {
2786                         new_spacing = Spacing::Other;
2787                         float tmpval = 0.0;
2788                         istr >> tmpval;
2789                         lyxerr << "new_value = " << tmpval << endl;
2790                         if (tmpval != 0.0)
2791                                 new_value = tmpval;
2792                 } else if (tmp == "default") {
2793                         new_spacing = Spacing::Default;
2794                 } else {
2795                         lyxerr << _("Unknown spacing argument: ")
2796                                << argument << endl;
2797                 }
2798                 if (cur_spacing != new_spacing || cur_value != new_value) {
2799                         par->params().spacing(Spacing(new_spacing, new_value));
2800                         lt->redoParagraph(bv_);
2801                         update(lt,
2802                                BufferView::SELECT
2803                                | BufferView::FITCUR
2804                                | BufferView::CHANGE);
2805                 }
2806         }
2807         break;
2808
2809         case LFUN_INSET_TOGGLE:
2810         {
2811                 LyXText * lt = bv_->getLyXText();
2812                 hideCursor();
2813                 beforeChange(lt);
2814                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2815                 lt->toggleInset(bv_);
2816                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2817                 setState();
2818         }
2819                 break;
2820
2821         case LFUN_QUOTE:
2822                 smartQuote();
2823                 break;
2824
2825         case LFUN_HTMLURL:
2826         case LFUN_URL:
2827         {
2828                 InsetCommandParams p;
2829                 if (action == LFUN_HTMLURL)
2830                         p.setCmdName("htmlurl");
2831                 else
2832                         p.setCmdName("url");
2833                 owner_->getDialogs()->createUrl(p.getAsString());
2834         }
2835         break;
2836
2837         case LFUN_INSERT_URL:
2838         {
2839                 InsetCommandParams p;
2840                 p.setFromString(argument);
2841
2842                 InsetUrl * inset = new InsetUrl(p);
2843                 if (!insertInset(inset))
2844                         delete inset;
2845                 else
2846                         updateInset(inset, true);
2847         }
2848         break;
2849
2850         case LFUN_INSET_ERT:
2851                 insertAndEditInset(new InsetERT(buffer_->params));
2852                 break;
2853
2854         case LFUN_INSET_EXTERNAL:
2855                 insertAndEditInset(new InsetExternal);
2856                 break;
2857
2858         case LFUN_INSET_FOOTNOTE:
2859                 insertAndEditInset(new InsetFoot(buffer_->params));
2860                 break;
2861
2862         case LFUN_INSET_MARGINAL:
2863                 insertAndEditInset(new InsetMarginal(buffer_->params));
2864                 break;
2865
2866         case LFUN_INSET_MINIPAGE:
2867                 insertAndEditInset(new InsetMinipage(buffer_->params));
2868                 break;
2869
2870         case LFUN_INSERT_NOTE:
2871                 insertAndEditInset(new InsetNote(buffer_->params));
2872                 break;
2873
2874         case LFUN_INSET_FLOAT:
2875                 // check if the float type exist
2876                 if (floatList.typeExist(argument)) {
2877                         insertAndEditInset(new InsetFloat(buffer_->params,
2878                                                           argument));
2879                 } else {
2880                         lyxerr << "Non-existent float type: "
2881                                << argument << endl;
2882                 }
2883                 break;
2884
2885         case LFUN_INSET_WIDE_FLOAT:
2886                 // check if the float type exist
2887                 if (floatList.typeExist(argument)) {
2888                         InsetFloat * new_inset =
2889                                 new InsetFloat(buffer_->params, argument);
2890                         new_inset->wide(true);
2891                         insertAndEditInset(new_inset);
2892                 } else {
2893                         lyxerr << "Non-existent float type: "
2894                                << argument << endl;
2895                 }
2896                 break;
2897
2898 #if 0
2899         case LFUN_INSET_LIST:
2900                 insertAndEditInset(new InsetList);
2901                 break;
2902
2903         case LFUN_INSET_THEOREM:
2904                 insertAndEditInset(new InsetTheorem);
2905                 break;
2906 #endif
2907
2908         case LFUN_INSET_CAPTION:
2909         {
2910                 // Do we have a locking inset...
2911                 if (bv_->theLockingInset()) {
2912                         lyxerr << "Locking inset code: "
2913                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2914                         InsetCaption * new_inset =
2915                                 new InsetCaption(buffer_->params);
2916                         new_inset->setOwner(bv_->theLockingInset());
2917                         new_inset->setAutoBreakRows(true);
2918                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2919                         new_inset->setFrameColor(0, LColor::captionframe);
2920                         if (insertInset(new_inset))
2921                                 new_inset->edit(bv_);
2922                         else
2923                                 delete new_inset;
2924                 }
2925         }
2926         break;
2927
2928         case LFUN_INSET_TABULAR:
2929         {
2930                 int r = 2;
2931                 int c = 2;
2932                 if (!argument.empty())
2933                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2934                 InsetTabular * new_inset =
2935                         new InsetTabular(*buffer_, r, c);
2936                 bool const rtl =
2937                         bv_->getLyXText()->real_current_font.isRightToLeft();
2938                 if (!open_new_inset(new_inset, rtl))
2939                         delete new_inset;
2940         }
2941         break;
2942
2943         // --- lyxserver commands ----------------------------
2944
2945         case LFUN_CHARATCURSOR:
2946         {
2947                 pos_type pos = bv_->getLyXText()->cursor.pos();
2948                 if (pos < bv_->getLyXText()->cursor.par()->size())
2949                         owner_->getLyXFunc()->setMessage(
2950                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2951                 else
2952                         owner_->getLyXFunc()->setMessage("EOF");
2953         }
2954         break;
2955
2956         case LFUN_GETXY:
2957                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2958                                                  + ' '
2959                                                  + tostr(bv_->getLyXText()->cursor.y()));
2960                 break;
2961
2962         case LFUN_SETXY:
2963         {
2964                 int x = 0;
2965                 int y = 0;
2966                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2967                         lyxerr << "SETXY: Could not parse coordinates in '"
2968                                << argument << std::endl;
2969                 }
2970                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2971         }
2972         break;
2973
2974         case LFUN_GETLAYOUT:
2975                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout()));
2976                 break;
2977
2978         case LFUN_GETFONT:
2979         {
2980                 LyXFont & font = bv_->getLyXText()->current_font;
2981                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2982                         owner_->getLyXFunc()->setMessage("E");
2983                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2984                         owner_->getLyXFunc()->setMessage("N");
2985                 else
2986                         owner_->getLyXFunc()->setMessage("0");
2987
2988         }
2989         break;
2990
2991         // --- accented characters ---------------------------
2992
2993         case LFUN_UMLAUT:
2994         case LFUN_CIRCUMFLEX:
2995         case LFUN_GRAVE:
2996         case LFUN_ACUTE:
2997         case LFUN_TILDE:
2998         case LFUN_CEDILLA:
2999         case LFUN_MACRON:
3000         case LFUN_DOT:
3001         case LFUN_UNDERDOT:
3002         case LFUN_UNDERBAR:
3003         case LFUN_CARON:
3004         case LFUN_SPECIAL_CARON:
3005         case LFUN_BREVE:
3006         case LFUN_TIE:
3007         case LFUN_HUNG_UMLAUT:
3008         case LFUN_CIRCLE:
3009         case LFUN_OGONEK:
3010                 if (argument.empty()) {
3011                         // As always...
3012                         owner_->getLyXFunc()->handleKeyFunc(action);
3013                 } else {
3014                         owner_->getLyXFunc()->handleKeyFunc(action);
3015                         owner_->getIntl()->getTrans()
3016                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
3017                         update(bv_->getLyXText(),
3018                                BufferView::SELECT
3019                                | BufferView::FITCUR
3020                                | BufferView::CHANGE);
3021                 }
3022                 break;
3023
3024         case LFUN_MATH_MACRO:
3025                 mathDispatchMathMacro(bv_, argument);
3026                 break;
3027
3028         case LFUN_MATH_DELIM:
3029                 mathDispatchMathDelim(bv_, argument);
3030                 break;
3031
3032         case LFUN_INSERT_MATRIX:
3033                 mathDispatchInsertMatrix(bv_, argument);
3034                 break;
3035
3036         case LFUN_INSERT_MATH:
3037                 mathDispatchInsertMath(bv_, argument);
3038                 break;
3039
3040         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
3041                 mathDispatchMathImportSelection(bv_, argument);
3042                 break;
3043
3044         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
3045                 mathDispatchMathDisplay(bv_, argument);
3046                 break;
3047
3048         case LFUN_MATH_MODE:             // Open or create an inlined math inset
3049                 mathDispatchMathMode(bv_, argument);
3050                 break;
3051
3052         case LFUN_GREEK:                 // Insert a single greek letter
3053                 mathDispatchGreek(bv_, argument);
3054                 break;
3055
3056         case LFUN_CITATION_INSERT:
3057         {
3058                 InsetCommandParams p;
3059                 p.setFromString(argument);
3060
3061                 InsetCitation * inset = new InsetCitation(p);
3062                 if (!insertInset(inset))
3063                         delete inset;
3064                 else
3065                         updateInset(inset, true);
3066         }
3067         break;
3068
3069         case LFUN_INSERT_BIBTEX:
3070         {
3071                 // ale970405+lasgoutt970425
3072                 // The argument can be up to two tokens separated
3073                 // by a space. The first one is the bibstyle.
3074                 string const db       = token(argument, ' ', 0);
3075                 string const bibstyle = token(argument, ' ', 1);
3076
3077                 InsetCommandParams p("BibTeX", db, bibstyle);
3078                 InsetBibtex * inset = new InsetBibtex(p);
3079
3080                 if (insertInset(inset)) {
3081                         if (argument.empty())
3082                                 inset->edit(bv_);
3083                 } else
3084                         delete inset;
3085         }
3086         break;
3087
3088         // BibTeX data bases
3089         case LFUN_BIBDB_ADD:
3090         {
3091                 InsetBibtex * inset =
3092                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3093                 if (inset) {
3094                         inset->addDatabase(argument);
3095                 }
3096         }
3097         break;
3098
3099         case LFUN_BIBDB_DEL:
3100         {
3101                 InsetBibtex * inset =
3102                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3103                 if (inset) {
3104                         inset->delDatabase(argument);
3105                 }
3106         }
3107         break;
3108
3109         case LFUN_BIBTEX_STYLE:
3110         {
3111                 InsetBibtex * inset =
3112                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3113                 if (inset) {
3114                         inset->setOptions(argument);
3115                 }
3116         }
3117         break;
3118
3119         case LFUN_INDEX_CREATE:
3120         {
3121                 InsetCommandParams p("index");
3122                 if (argument.empty()) {
3123                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3124                         p.setContents(idxstring);
3125                 } else {
3126                         p.setContents(argument);
3127                 }
3128
3129                 owner_->getDialogs()->createIndex(p.getAsString());
3130         }
3131         break;
3132
3133         case LFUN_INDEX_INSERT:
3134         {
3135                 InsetCommandParams p;
3136                 p.setFromString(argument);
3137                 InsetIndex * inset = new InsetIndex(p);
3138
3139                 if (!insertInset(inset))
3140                         delete inset;
3141                 else
3142                         updateInset(inset, true);
3143         }
3144         break;
3145
3146         case LFUN_INDEX_INSERT_LAST:
3147         {
3148                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3149                 if (!idxstring.empty()) {
3150                         owner_->message(_("Word `")
3151                                         + idxstring + _(("' indexed.")));
3152                         InsetCommandParams p("index", idxstring);
3153                         InsetIndex * inset = new InsetIndex(p);
3154
3155                         if (!insertInset(inset))
3156                                 delete inset;
3157                         else
3158                                 updateInset(inset, true);
3159                 }
3160         }
3161         break;
3162
3163         case LFUN_INDEX_PRINT:
3164         {
3165                 InsetCommandParams p("printindex");
3166                 Inset * inset = new InsetPrintIndex(p);
3167                 if (!insertInset(inset, tclass.defaultLayoutName()))
3168                         delete inset;
3169         }
3170         break;
3171
3172         case LFUN_PARENTINSERT:
3173         {
3174                 InsetCommandParams p("lyxparent", argument);
3175                 Inset * inset = new InsetParent(p, *buffer_);
3176                 if (!insertInset(inset, tclass.defaultLayoutName()))
3177                         delete inset;
3178         }
3179
3180         break;
3181
3182         case LFUN_CHILD_INSERT:
3183         {
3184                 InsetInclude::Params p;
3185                 p.cparams.setFromString(argument);
3186                 p.masterFilename_ = buffer_->fileName();
3187
3188                 InsetInclude * inset = new InsetInclude(p);
3189                 if (!insertInset(inset))
3190                         delete inset;
3191                 else {
3192                         updateInset(inset, true);
3193                         bv_->owner()->getDialogs()->showInclude(inset);
3194                 }
3195         }
3196         break;
3197
3198         case LFUN_FLOAT_LIST:
3199                 if (floatList.typeExist(argument)) {
3200                         Inset * inset = new InsetFloatList(argument);
3201                         if (!insertInset(inset, tclass.defaultLayoutName()))
3202                                 delete inset;
3203                 } else {
3204                         lyxerr << "Non-existent float type: "
3205                                << argument << endl;
3206                 }
3207                 break;
3208
3209         case LFUN_THESAURUS_ENTRY:
3210         {
3211                 string arg = argument;
3212
3213                 if (arg.empty()) {
3214                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3215                                                                    false);
3216
3217                         // FIXME
3218                         if (arg.size() > 100 || arg.empty()) {
3219                                 // Get word or selection
3220                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3221                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3222                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3223                         }
3224                 }
3225
3226                 bv_->owner()->getDialogs()->showThesaurus(arg);
3227         }
3228                 break;
3229
3230         case LFUN_SELFINSERT:
3231         {
3232                 if (argument.empty()) break;
3233
3234                 /* Automatically delete the currently selected
3235                  * text and replace it with what is being
3236                  * typed in now. Depends on lyxrc settings
3237                  * "auto_region_delete", which defaults to
3238                  * true (on). */
3239
3240                 LyXText * lt = bv_->getLyXText();
3241
3242                 if (lyxrc.auto_region_delete) {
3243                         if (lt->selection.set()) {
3244                                 lt->cutSelection(bv_, false, false);
3245                                 bv_->update(lt,
3246                                             BufferView::SELECT
3247                                             | BufferView::FITCUR
3248                                             | BufferView::CHANGE);
3249                         }
3250                         workarea().haveSelection(false);
3251                 }
3252
3253                 beforeChange(lt);
3254                 LyXFont const old_font(lt->real_current_font);
3255
3256                 string::const_iterator cit = argument.begin();
3257                 string::const_iterator end = argument.end();
3258                 for (; cit != end; ++cit) {
3259                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3260                 }
3261
3262                 bv_->update(lt,
3263                             BufferView::SELECT
3264                             | BufferView::FITCUR
3265                             | BufferView::CHANGE);
3266
3267                 lt->selection.cursor = lt->cursor;
3268                 moveCursorUpdate(false);
3269
3270                 // real_current_font.number can change so we need to
3271                 // update the minibuffer
3272                 if (old_font != lt->real_current_font)
3273                         owner_->showState();
3274                 //return string();
3275         }
3276         break;
3277
3278         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3279         {
3280                 time_t now_time_t = time(NULL);
3281                 struct tm * now_tm = localtime(&now_time_t);
3282                 setlocale(LC_TIME, "");
3283                 string arg;
3284                 if (!argument.empty())
3285                         arg = argument;
3286                 else
3287                         arg = lyxrc.date_insert_format;
3288                 char datetmp[32];
3289                 int const datetmp_len =
3290                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3291
3292                 LyXText * lt = bv_->getLyXText();
3293
3294                 for (int i = 0; i < datetmp_len; i++) {
3295                         lt->insertChar(bv_, datetmp[i]);
3296                         update(lt,
3297                                BufferView::SELECT
3298                                | BufferView::FITCUR
3299                                | BufferView::CHANGE);
3300                 }
3301
3302                 lt->selection.cursor = lt->cursor;
3303                 moveCursorUpdate(false);
3304         }
3305         break;
3306
3307         case LFUN_UNKNOWN_ACTION:
3308                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3309                 break;
3310
3311         default:
3312                 return false;
3313         } // end of switch
3314
3315         return true;
3316 }
3317
3318
3319 void BufferView::Pimpl::newline()
3320 {
3321         if (available()) {
3322                 LyXText * lt = bv_->getLyXText();
3323                 hideCursor();
3324                 update(lt,
3325                        BufferView::SELECT
3326                        | BufferView::FITCUR);
3327                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3328                 update(lt,
3329                        BufferView::SELECT
3330                        | BufferView::FITCUR
3331                        | BufferView::CHANGE);
3332         }
3333 }
3334
3335
3336 void BufferView::Pimpl::hfill()
3337 {
3338         if (available()) {
3339                 LyXText * lt = bv_->getLyXText();
3340                 hideCursor();
3341                 update(lt,
3342                        BufferView::SELECT
3343                        | BufferView::FITCUR);
3344                 lt->insertChar(bv_, Paragraph::META_HFILL);
3345                 update(lt,
3346                        BufferView::SELECT
3347                        | BufferView::FITCUR
3348                        | BufferView::CHANGE);
3349         }
3350 }
3351
3352
3353 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3354 {
3355         if (available()) {
3356                 LyXText * lt = bv_->getLyXText();
3357
3358                 hideCursor();
3359                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3360                 InsetSpecialChar * new_inset =
3361                         new InsetSpecialChar(kind);
3362                 if (!insertInset(new_inset))
3363                         delete new_inset;
3364                 else
3365                         updateInset(new_inset, true);
3366         }
3367 }
3368
3369
3370 void BufferView::Pimpl::smartQuote()
3371 {
3372         LyXText const * lt = bv_->getLyXText();
3373         Paragraph const * par = lt->cursor.par();
3374         pos_type pos = lt->cursor.pos();
3375         char c;
3376
3377         if (!pos
3378             || (par->isInset(pos - 1)
3379                 && par->getInset(pos - 1)->isSpace()))
3380                 c = ' ';
3381         else
3382                 c = par->getChar(pos - 1);
3383
3384
3385         hideCursor();
3386
3387         LyXLayout const & style =
3388                 textclasslist[bv_->buffer()->params.textclass][par->layout()];
3389
3390         if (style.pass_thru ||
3391                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3392                 bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
3393 }
3394
3395
3396 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3397 {
3398         if (insertInset(inset))
3399                 inset->edit(bv_);
3400         else
3401                 delete inset;
3402 }
3403
3404
3405 // Open and lock an updatable inset
3406 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3407 {
3408         LyXText * lt = bv_->getLyXText();
3409
3410         beforeChange(lt);
3411         finishUndo();
3412         if (!insertInset(new_inset)) {
3413                 delete new_inset;
3414                 return false;
3415         }
3416         new_inset->edit(bv_, !behind);
3417         return true;
3418 }
3419
3420
3421 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3422 {
3423         // if we are in a locking inset we should try to insert the
3424         // inset there otherwise this is a illegal function now
3425         if (bv_->theLockingInset()) {
3426                 if (bv_->theLockingInset()->insetAllowed(inset))
3427                     return bv_->theLockingInset()->insertInset(bv_, inset);
3428                 return false;
3429         }
3430
3431         // not quite sure if we want this...
3432         setCursorParUndo(bv_);
3433         freezeUndo();
3434
3435         beforeChange(bv_->text);
3436         if (!lout.empty()) {
3437                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3438                 bv_->text->breakParagraph(bv_);
3439                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3440
3441                 if (bv_->text->cursor.par()->size()) {
3442                         bv_->text->cursorLeft(bv_);
3443
3444                         bv_->text->breakParagraph(bv_);
3445                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3446                 }
3447
3448                 string lres = lout;
3449                 LyXTextClass const & tclass =
3450                         textclasslist[buffer_->params.textclass];
3451                 bool hasLayout = tclass.hasLayout(lres);
3452                 string lay = tclass.defaultLayoutName();
3453
3454                 if (hasLayout != false) {
3455                         // layout found
3456                         lay = lres;
3457                 } else {
3458                         // layout not fount using default
3459                         lay = tclass.defaultLayoutName();
3460                 }
3461
3462                 bv_->text->setLayout(bv_, lay);
3463
3464                 bv_->text->setParagraph(bv_, 0, 0,
3465                                    0, 0,
3466                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3467                                    Spacing(),
3468                                    LYX_ALIGN_LAYOUT,
3469                                    string(),
3470                                    0);
3471                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3472         }
3473
3474         bv_->text->insertInset(bv_, inset);
3475         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3476
3477         unFreezeUndo();
3478         return true;
3479 }
3480
3481
3482 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3483 {
3484         if (!inset || !available())
3485                 return;
3486
3487         // first check for locking insets
3488         if (bv_->theLockingInset()) {
3489                 if (bv_->theLockingInset() == inset) {
3490                         if (bv_->text->updateInset(bv_, inset)) {
3491                                 update();
3492                                 if (mark_dirty) {
3493                                         buffer_->markDirty();
3494                                 }
3495                                 updateScrollbar();
3496                                 return;
3497                         }
3498                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3499                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3500                                 update();
3501                                 if (mark_dirty) {
3502                                         buffer_->markDirty();
3503                                 }
3504                                 updateScrollbar();
3505                                 return;
3506                         }
3507                 }
3508         }
3509
3510         // then check if the inset is a top_level inset (has no owner)
3511         // if yes do the update as always otherwise we have to update the
3512         // toplevel inset where this inset is inside
3513         Inset * tl_inset = inset;
3514         while(tl_inset->owner())
3515                 tl_inset = tl_inset->owner();
3516         hideCursor();
3517         if (tl_inset == inset) {
3518                 update(bv_->text, BufferView::UPDATE);
3519                 if (bv_->text->updateInset(bv_, inset)) {
3520                         if (mark_dirty) {
3521                                 update(bv_->text,
3522                                        BufferView::SELECT
3523                                        | BufferView::FITCUR
3524                                        | BufferView::CHANGE);
3525                         } else {
3526                                 update(bv_->text, SELECT);
3527                         }
3528                         return;
3529                 }
3530         } else if (static_cast<UpdatableInset *>(tl_inset)
3531                            ->updateInsetInInset(bv_, inset))
3532         {
3533                         if (bv_->text->updateInset(bv_,  tl_inset)) {
3534                                 update();
3535                                 updateScrollbar();
3536                         }
3537         }
3538 }
3539
3540
3541 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3542                                   bool same_content)
3543 {
3544         if (!available()) return;
3545
3546         hideCursor();
3547         beforeChange(bv_->text);
3548         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3549
3550         LyXCursor const & cursor = bv_->text->cursor;
3551
3552         string contents;
3553         if (same_content &&
3554             cursor.par()->isInset(cursor.pos())) {
3555                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3556                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3557                     != codes.end())
3558                         contents =
3559                                 static_cast<InsetCommand const *>(inset)->getContents();
3560         }
3561
3562
3563         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3564                 if (bv_->text->cursor.pos()
3565                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3566                         LyXCursor tmp = bv_->text->cursor;
3567                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3568                         bv_->text->cursor.pos(0);
3569                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3570                                 bv_->text->cursor = tmp;
3571                                 bv_->owner()->message(_("No more insets"));
3572                         }
3573                 } else {
3574                         bv_->owner()->message(_("No more insets"));
3575                 }
3576         }
3577         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3578         bv_->text->selection.cursor = bv_->text->cursor;
3579 }
3580
3581
3582 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3583 {
3584         gotoInset(vector<Inset::Code>(1, code), same_content);
3585 }