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