]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
Hopefully temporary fix for the Tabular crash problem. Of course, this is not the...
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
73
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
76
77 #include <functional>
78 #include <vector>
79
80
81 using lyx::CoordCache;
82 using lyx::docstring;
83 using lyx::pos_type;
84 using lyx::Point;
85
86 using lyx::support::addPath;
87 using lyx::support::bformat;
88 using lyx::support::FileFilterList;
89 using lyx::support::fileSearch;
90 using lyx::support::isDirWriteable;
91 using lyx::support::makeDisplayPath;
92 using lyx::support::makeAbsPath;
93 using lyx::support::package;
94
95 using std::distance;
96 using std::endl;
97 using std::istringstream;
98 using std::find;
99 using std::make_pair;
100 using std::min;
101 using std::max;
102 using std::mem_fun_ref;
103 using std::string;
104 using std::vector;
105
106 namespace Alert = lyx::frontend::Alert;
107
108 namespace {
109
110 unsigned int const saved_positions_num = 20;
111
112
113 /// Return an inset of this class if it exists at the current cursor position
114 template <class T>
115 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
116 {
117         T * inset = 0;
118         DocIterator it = cur;
119         if (it.nextInset() &&
120             it.nextInset()->lyxCode() == code) {
121                 inset = static_cast<T*>(it.nextInset());
122         }
123         return inset;
124 }
125
126 } // anon namespace
127
128
129 BufferView::BufferView()
130         : buffer_(0), wh_(0),
131           cursor_(*this),
132           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
133           intl_(new Intl)
134 {
135         xsel_cache_.set = false;
136
137         saved_positions.resize(saved_positions_num);
138         // load saved bookmarks
139         lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
140         for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
141                 bm != bmList.end(); ++bm)
142                 if (bm->get<0>() < saved_positions_num)
143                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
144         // and then clear them
145         bmList.clear();
146
147         intl_->initKeyMapper(lyxrc.use_kbmap);
148 }
149
150
151 BufferView::~BufferView()
152 {
153 }
154
155
156 Buffer * BufferView::buffer() const
157 {
158         return buffer_;
159 }
160
161
162 void BufferView::setBuffer(Buffer * b)
163 {
164         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
165                             << "[ b = " << b << "]" << endl;
166
167         if (buffer_) {
168                 // Save the actual cursor position and anchor inside the
169                 // buffer so that it can be restored in case we rechange
170                 // to this buffer later on.
171                 buffer_->saveCursor(cursor_.selectionBegin(),
172                                     cursor_.selectionEnd());
173                 // current buffer is going to be switched-off, save cursor pos
174                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
175                         boost::tie(cursor_.pit(), cursor_.pos()) );
176         }
177
178         // If we're quitting lyx, don't bother updating stuff
179         if (quitting) {
180                 buffer_ = 0;
181                 return;
182         }
183
184         // If we are closing current buffer, switch to the first in
185         // buffer list.
186         if (!b) {
187                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
188                                     << " No Buffer!" << endl;
189                 // We are closing the buffer, use the first buffer as current
190                 buffer_ = theBufferList().first();
191         } else {
192                 // Set current buffer
193                 buffer_ = b;
194         }
195
196         // Reset old cursor
197         cursor_ = LCursor(*this);
198         anchor_ref_ = 0;
199         offset_ref_ = 0;
200
201         if (buffer_) {
202                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
203                                     << "Buffer addr: " << buffer_ << endl;
204                 cursor_.push(buffer_->inset());
205                 cursor_.resetAnchor();
206                 buffer_->text().init(this);
207                 buffer_->text().setCurrentFont(cursor_);
208                 if (buffer_->getCursor().size() > 0 &&
209                     buffer_->getAnchor().size() > 0)
210                 {
211                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
212                         cursor_.resetAnchor();
213                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
214                         cursor_.setSelection();
215                 }
216         }
217
218         update();
219
220         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
221                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
222 }
223
224
225 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
226 {
227         // Get absolute path of file and add ".lyx"
228         // to the filename if necessary
229         string s = fileSearch(string(), filename, "lyx");
230
231         bool const found = !s.empty();
232
233         if (!found)
234                 s = filename;
235
236         // File already open?
237         if (theBufferList().exists(s)) {
238                 docstring const file = makeDisplayPath(s, 20);
239                 docstring text = bformat(_("The document %1$s is already "
240                                                      "loaded.\n\nDo you want to revert "
241                                                      "to the saved version?"), file);
242                 int const ret = Alert::prompt(_("Revert to saved document?"),
243                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
244
245                 if (ret != 0) {
246                         setBuffer(theBufferList().getBuffer(s));
247                         return true;
248                 }
249                 // FIXME: should be LFUN_REVERT
250                 if (!theBufferList().close(theBufferList().getBuffer(s), false))
251                         return false;
252                 // Fall through to new load. (Asger)
253         }
254
255         Buffer * b = 0;
256
257         if (found) {
258                 b = theBufferList().newBuffer(s);
259                 if (!::loadLyXFile(b, s)) {
260                         theBufferList().release(b);
261                         return false;
262                 }
263         } else {
264                 docstring text = bformat(_("The document %1$s does not yet "
265                                                      "exist.\n\nDo you want to create "
266                                                      "a new document?"), lyx::from_utf8(s));
267                 int const ret = Alert::prompt(_("Create new document?"),
268                          text, 0, 1, _("&Create"), _("Cancel"));
269
270                 if (ret == 0) {
271                         b = newFile(s, string(), true);
272                         if (!b)
273                                 return false;
274                 } else
275                         return false;
276         }
277
278         setBuffer(b);
279         // Send the "errors" signal in case of parsing errors
280         b->errors("Parse");
281
282         // scroll to the position when the file was last closed
283         if (lyxrc.use_lastfilepos) {
284                 lyx::pit_type pit;
285                 lyx::pos_type pos;
286                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
287                 // I am not sure how to separate the following part to a function
288                 // so I will leave this to Lars.
289                 //
290                 // check pit since the document may be externally changed.
291                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
292                         ParIterator it = b->par_iterator_begin();
293                         ParIterator const end = b->par_iterator_end();
294                         for (; it != end; ++it)
295                                 if (it.pit() == pit) {
296                                         // restored pos may be bigger than it->size
297                                         setCursor(makeDocIterator(it, min(pos, it->size())));
298                                         update(Update::FitCursor);
299                                         break;
300                                 }
301                 }
302         }
303
304         if (tolastfiles)
305                 LyX::ref().session().addLastFile(b->fileName());
306
307         return true;
308 }
309
310
311 void BufferView::reload()
312 {
313         string const fn = buffer_->fileName();
314         if (theBufferList().close(buffer_, false))
315                 loadLyXFile(fn);
316 }
317
318
319 void BufferView::resize()
320 {
321         if (!buffer_)
322                 return;
323
324         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
325
326         buffer_->text().init(this);
327         update();
328         switchKeyMap();
329 }
330
331
332 bool BufferView::fitCursor()
333 {
334         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
335                 lyx::frontend::FontMetrics const & fm =
336                         theFontMetrics(cursor_.getFont());
337                 int const asc = fm.maxAscent();
338                 int const des = fm.maxDescent();
339                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
340                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
341                         return false;
342         }
343         center();
344         return true;
345 }
346
347
348 bool BufferView::multiParSel()
349 {
350         if (!cursor_.selection())
351                 return false;
352         bool ret = multiparsel_cache_;
353         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
354         // Either this, or previous selection spans paragraphs
355         return ret || multiparsel_cache_;
356 }
357
358
359 bool BufferView::update(Update::flags flags)
360 {
361         // This is close to a hot-path.
362         if (lyxerr.debugging(Debug::DEBUG)) {
363                 lyxerr[Debug::DEBUG]
364                         << BOOST_CURRENT_FUNCTION
365                         << "[fitcursor = " << (flags & Update::FitCursor)
366                         << ", forceupdate = " << (flags & Update::Force)
367                         << ", singlepar = " << (flags & Update::SinglePar)
368                         << "]  buffer: " << buffer_ << endl;
369         }
370
371         // Check needed to survive LyX startup
372         if (!buffer_)
373                 return false;
374
375         // Update macro store
376         buffer_->buildMacros();
377
378         // First drawing step
379         updateMetrics(flags & Update::SinglePar);
380
381         // The second drawing step is done in WorkArea::redraw() if needed.
382         bool const need_second_step =
383                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
384                 && (fitCursor() || multiParSel());
385
386         return need_second_step;
387 }
388
389
390 void BufferView::updateScrollbar()
391 {
392         if (!buffer_) {
393                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
394                                      << " no text in updateScrollbar" << endl;
395                 scrollbarParameters_.reset();
396                 return;
397         }
398
399         LyXText & t = buffer_->text();
400         int const parsize = int(t.paragraphs().size() - 1);
401         if (anchor_ref_ >  parsize)  {
402                 anchor_ref_ = parsize;
403                 offset_ref_ = 0;
404         }
405
406         lyxerr[Debug::GUI]
407                 << BOOST_CURRENT_FUNCTION
408                 << " Updating scrollbar: height: " << t.paragraphs().size()
409                 << " curr par: " << cursor_.bottom().pit()
410                 << " default height " << defaultRowHeight() << endl;
411
412         // It would be better to fix the scrollbar to understand
413         // values in [0..1] and divide everything by wh
414
415         // estimated average paragraph height:
416         if (wh_ == 0)
417                 wh_ = height_ / 4;
418         int h = t.getPar(anchor_ref_).height();
419
420         // Normalize anchor/offset (MV):
421         while (offset_ref_ > h && anchor_ref_ < parsize) {
422                 anchor_ref_++;
423                 offset_ref_ -= h;
424                 h = t.getPar(anchor_ref_).height();
425         }
426         // Look at paragraph heights on-screen
427         int sumh = 0;
428         int nh = 0;
429         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
430                 if (sumh > height_)
431                         break;
432                 int const h2 = t.getPar(pit).height();
433                 sumh += h2;
434                 nh++;
435         }
436         int const hav = sumh / nh;
437         // More realistic average paragraph height
438         if (hav > wh_)
439                 wh_ = hav;
440
441         scrollbarParameters_.height = (parsize + 1) * wh_;
442         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
443         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
444 }
445
446
447 ScrollbarParameters const & BufferView::scrollbarParameters() const
448 {
449         return scrollbarParameters_;
450 }
451
452
453 void BufferView::scrollDocView(int value)
454 {
455         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
456                            << "[ value = " << value << "]" << endl;
457
458         if (!buffer_)
459                 return;
460
461         LyXText & t = buffer_->text();
462
463         float const bar = value / float(wh_ * t.paragraphs().size());
464
465         anchor_ref_ = int(bar * t.paragraphs().size());
466         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
467                 anchor_ref_ = int(t.paragraphs().size()) - 1;
468         t.redoParagraph(anchor_ref_);
469         int const h = t.getPar(anchor_ref_).height();
470         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
471 }
472
473
474 void BufferView::setCursorFromScrollbar()
475 {
476         LyXText & t = buffer_->text();
477
478         int const height = 2 * defaultRowHeight();
479         int const first = height;
480         int const last = height_ - height;
481         LCursor & cur = cursor_;
482
483         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
484
485         switch (st) {
486         case bv_funcs::CUR_ABOVE:
487                 t.setCursorFromCoordinates(cur, 0, first);
488                 cur.clearSelection();
489                 break;
490         case bv_funcs::CUR_BELOW:
491                 t.setCursorFromCoordinates(cur, 0, last);
492                 cur.clearSelection();
493                 break;
494         case bv_funcs::CUR_INSIDE:
495                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
496                 int const newy = min(last, max(y, first));
497                 if (y != newy) {
498                         cur.reset(buffer_->inset());
499                         t.setCursorFromCoordinates(cur, 0, newy);
500                 }
501         }
502 }
503
504
505 Change const BufferView::getCurrentChange() const
506 {
507         if (!cursor_.selection())
508                 return Change(Change::UNCHANGED);
509
510         DocIterator dit = cursor_.selectionBegin();
511         return dit.paragraph().lookupChange(dit.pos());
512 }
513
514
515 void BufferView::savePosition(unsigned int i)
516 {
517         if (i >= saved_positions_num)
518                 return;
519         BOOST_ASSERT(cursor_.inTexted());
520         saved_positions[i] = Position(buffer_->fileName(),
521                                       cursor_.paragraph().id(),
522                                       cursor_.pos());
523         if (i > 0)
524                 // emit message signal.
525                 message(bformat(_("Saved bookmark %1$d"), i));
526 }
527
528
529 void BufferView::restorePosition(unsigned int i)
530 {
531         if (i >= saved_positions_num)
532                 return;
533
534         string const fname = saved_positions[i].filename;
535
536         cursor_.clearSelection();
537
538         if (fname != buffer_->fileName()) {
539                 Buffer * b = 0;
540                 if (theBufferList().exists(fname))
541                         b = theBufferList().getBuffer(fname);
542                 else {
543                         b = theBufferList().newBuffer(fname);
544                         // Don't ask, just load it
545                         ::loadLyXFile(b, fname);
546                 }
547                 if (b)
548                         setBuffer(b);
549         }
550
551         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
552         if (par == buffer_->par_iterator_end())
553                 return;
554
555         setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
556
557         if (i > 0)
558                 // emit message signal.
559                 message(bformat(_("Moved to bookmark %1$d"), i));
560 }
561
562
563 bool BufferView::isSavedPosition(unsigned int i)
564 {
565         return i < saved_positions_num && !saved_positions[i].filename.empty();
566 }
567
568 void BufferView::saveSavedPositions()
569 {
570         // save bookmarks. It is better to use the pit interface
571         // but I do not know how to effectively convert between
572         // par_id and pit.
573         for (unsigned int i=1; i < saved_positions_num; ++i) {
574                 if ( isSavedPosition(i) )
575                         LyX::ref().session().saveBookmark( boost::tie(
576                                 i,
577                                 saved_positions[i].filename,
578                                 saved_positions[i].par_id,
579                                 saved_positions[i].par_pos) );
580         }
581 }
582
583 void BufferView::switchKeyMap()
584 {
585         if (!lyxrc.rtl_support)
586                 return;
587
588         if (getLyXText()->real_current_font.isRightToLeft()) {
589                 if (intl_->keymap == Intl::PRIMARY)
590                         intl_->keyMapSec();
591         } else {
592                 if (intl_->keymap == Intl::SECONDARY)
593                         intl_->keyMapPrim();
594         }
595 }
596
597
598 int BufferView::workWidth() const
599 {
600         return width_;
601 }
602
603
604 void BufferView::center()
605 {
606         CursorSlice & bot = cursor_.bottom();
607         lyx::pit_type const pit = bot.pit();
608         bot.text()->redoParagraph(pit);
609         Paragraph const & par = bot.text()->paragraphs()[pit];
610         anchor_ref_ = pit;
611         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
612                 + par.ascent() - height_ / 2;
613 }
614
615
616 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
617 {
618         FuncStatus flag;
619
620         switch (cmd.action) {
621
622         case LFUN_UNDO:
623                 flag.enabled(!buffer_->undostack().empty());
624                 break;
625         case LFUN_REDO:
626                 flag.enabled(!buffer_->redostack().empty());
627                 break;
628         case LFUN_FILE_INSERT:
629         case LFUN_FILE_INSERT_ASCII_PARA:
630         case LFUN_FILE_INSERT_ASCII:
631         case LFUN_BOOKMARK_SAVE:
632                 // FIXME: Actually, these LFUNS should be moved to LyXText
633                 flag.enabled(cursor_.inTexted());
634                 break;
635         case LFUN_FONT_STATE:
636         case LFUN_LABEL_INSERT:
637         case LFUN_PARAGRAPH_GOTO:
638         // FIXME handle non-trivially
639         case LFUN_OUTLINE_UP:
640         case LFUN_OUTLINE_DOWN:
641         case LFUN_OUTLINE_IN:
642         case LFUN_OUTLINE_OUT:
643         case LFUN_NOTE_NEXT:
644         case LFUN_REFERENCE_NEXT:
645         case LFUN_WORD_FIND:
646         case LFUN_WORD_REPLACE:
647         case LFUN_MARK_OFF:
648         case LFUN_MARK_ON:
649         case LFUN_MARK_TOGGLE:
650         case LFUN_SCREEN_RECENTER:
651         case LFUN_BIBTEX_DATABASE_ADD:
652         case LFUN_BIBTEX_DATABASE_DEL:
653         case LFUN_WORDS_COUNT:
654         case LFUN_NEXT_INSET_TOGGLE:
655                 flag.enabled(true);
656                 break;
657
658         case LFUN_LABEL_GOTO: {
659                 flag.enabled(!cmd.argument().empty()
660                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
661                 break;
662         }
663
664         case LFUN_BOOKMARK_GOTO:
665                 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
666                 break;
667
668         case LFUN_CHANGES_TRACK:
669                 flag.enabled(true);
670                 flag.setOnOff(buffer_->params().trackChanges);
671                 break;
672
673         case LFUN_CHANGES_OUTPUT: {
674                 OutputParams runparams;
675                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
676                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
677                 flag.setOnOff(buffer_->params().outputChanges);
678                 break;
679         }
680
681         case LFUN_CHANGES_MERGE:
682         case LFUN_CHANGE_NEXT:
683         case LFUN_ALL_CHANGES_ACCEPT:
684         case LFUN_ALL_CHANGES_REJECT:
685                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
686                 break;
687
688         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
689                 flag.setOnOff(buffer_->params().compressed);
690                 break;
691         }
692
693         default:
694                 flag.enabled(false);
695         }
696
697         return flag;
698 }
699
700
701 bool BufferView::dispatch(FuncRequest const & cmd)
702 {
703         //lyxerr << BOOST_CURRENT_FUNCTION
704         //       << [ cmd = " << cmd << "]" << endl;
705
706         // Make sure that the cached BufferView is correct.
707         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
708                 << " action[" << cmd.action << ']'
709                 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
710                 << " x[" << cmd.x << ']'
711                 << " y[" << cmd.y << ']'
712                 << " button[" << cmd.button() << ']'
713                 << endl;
714
715         LCursor & cur = cursor_;
716
717         switch (cmd.action) {
718
719         case LFUN_UNDO:
720                 if (buffer_) {
721                         cur.message(_("Undo"));
722                         cur.clearSelection();
723                         if (!textUndo(*this))
724                                 cur.message(_("No further undo information"));
725                         update();
726                         switchKeyMap();
727                 }
728                 break;
729
730         case LFUN_REDO:
731                 if (buffer_) {
732                         cur.message(_("Redo"));
733                         cur.clearSelection();
734                         if (!textRedo(*this))
735                                 cur.message(_("No further redo information"));
736                         update();
737                         switchKeyMap();
738                 }
739                 break;
740
741         case LFUN_FILE_INSERT:
742                 // FIXME: We don't know the encoding of filenames
743                 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
744                 break;
745
746         case LFUN_FILE_INSERT_ASCII_PARA:
747                 // FIXME: We don't know the encoding of filenames
748                 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
749                 break;
750
751         case LFUN_FILE_INSERT_ASCII:
752                 // FIXME: We don't know the encoding of filenames
753                 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
754                 break;
755
756         case LFUN_FONT_STATE:
757                 cur.message(lyx::from_utf8(cur.currentState()));
758                 break;
759
760         case LFUN_BOOKMARK_SAVE:
761                 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
762                 break;
763
764         case LFUN_BOOKMARK_GOTO:
765                 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
766                 break;
767
768         case LFUN_LABEL_GOTO: {
769                 docstring label = cmd.argument();
770                 if (label.empty()) {
771                         InsetRef * inset =
772                                 getInsetByCode<InsetRef>(cursor_,
773                                                          InsetBase::REF_CODE);
774                         if (inset) {
775                                 label = lyx::from_utf8(inset->getContents());
776                                 savePosition(0);
777                         }
778                 }
779
780                 if (!label.empty())
781                         gotoLabel(label);
782                 break;
783         }
784
785         case LFUN_PARAGRAPH_GOTO: {
786                 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
787                 ParIterator par = buffer_->getParFromID(id);
788                 if (par == buffer_->par_iterator_end()) {
789                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
790                                             << id << ']' << endl;
791                         break;
792                 } else {
793                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
794                                             << " found." << endl;
795                 }
796
797                 // Set the cursor
798                 setCursor(makeDocIterator(par, 0));
799
800                 update();
801                 switchKeyMap();
802                 break;
803         }
804
805         case LFUN_OUTLINE_UP:
806                 lyx::toc::outline(lyx::toc::Up, cursor_);
807                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
808                 updateLabels(*buffer_);
809                 break;
810         case LFUN_OUTLINE_DOWN:
811                 lyx::toc::outline(lyx::toc::Down, cursor_);
812                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
813                 updateLabels(*buffer_);
814                 break;
815         case LFUN_OUTLINE_IN:
816                 lyx::toc::outline(lyx::toc::In, cursor_);
817                 updateLabels(*buffer_);
818                 break;
819         case LFUN_OUTLINE_OUT:
820                 lyx::toc::outline(lyx::toc::Out, cursor_);
821                 updateLabels(*buffer_);
822                 break;
823
824         case LFUN_NOTE_NEXT:
825                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
826                 break;
827
828         case LFUN_REFERENCE_NEXT: {
829                 vector<InsetBase_code> tmp;
830                 tmp.push_back(InsetBase::LABEL_CODE);
831                 tmp.push_back(InsetBase::REF_CODE);
832                 bv_funcs::gotoInset(this, tmp, true);
833                 break;
834         }
835
836         case LFUN_CHANGES_TRACK:
837                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
838                 break;
839
840         case LFUN_CHANGES_OUTPUT: {
841                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
842                 break;
843         }
844
845         case LFUN_CHANGE_NEXT:
846                 lyx::find::findNextChange(this);
847                 break;
848
849         case LFUN_CHANGES_MERGE:
850                 if (lyx::find::findNextChange(this))
851                         showDialog("changes");
852                 break;
853
854         case LFUN_ALL_CHANGES_ACCEPT: {
855                 cursor_.reset(buffer_->inset());
856 #ifdef WITH_WARNINGS
857 #warning FIXME changes
858 #endif
859                 while (lyx::find::findNextChange(this))
860                         getLyXText()->acceptChange(cursor_);
861                 update();
862                 break;
863         }
864
865         case LFUN_ALL_CHANGES_REJECT: {
866                 cursor_.reset(buffer_->inset());
867 #ifdef WITH_WARNINGS
868 #warning FIXME changes
869 #endif
870                 while (lyx::find::findNextChange(this))
871                         getLyXText()->rejectChange(cursor_);
872                 break;
873         }
874
875         case LFUN_WORD_FIND:
876                 lyx::find::find(this, cmd);
877                 break;
878
879         case LFUN_WORD_REPLACE:
880                 lyx::find::replace(this, cmd);
881                 break;
882
883         case LFUN_MARK_OFF:
884                 cur.clearSelection();
885                 cur.resetAnchor();
886                 cur.message(lyx::from_utf8(N_("Mark off")));
887                 break;
888
889         case LFUN_MARK_ON:
890                 cur.clearSelection();
891                 cur.mark() = true;
892                 cur.resetAnchor();
893                 cur.message(lyx::from_utf8(N_("Mark on")));
894                 break;
895
896         case LFUN_MARK_TOGGLE:
897                 cur.clearSelection();
898                 if (cur.mark()) {
899                         cur.mark() = false;
900                         cur.message(lyx::from_utf8(N_("Mark removed")));
901                 } else {
902                         cur.mark() = true;
903                         cur.message(lyx::from_utf8(N_("Mark set")));
904                 }
905                 cur.resetAnchor();
906                 break;
907
908         case LFUN_SCREEN_RECENTER:
909                 center();
910                 break;
911
912         case LFUN_BIBTEX_DATABASE_ADD: {
913                 LCursor tmpcur = cursor_;
914                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
915                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
916                                                 InsetBase::BIBTEX_CODE);
917                 if (inset) {
918                         if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
919                                 buffer_->updateBibfilesCache();
920                 }
921                 break;
922         }
923
924         case LFUN_BIBTEX_DATABASE_DEL: {
925                 LCursor tmpcur = cursor_;
926                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
927                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
928                                                 InsetBase::BIBTEX_CODE);
929                 if (inset) {
930                         if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
931                                 buffer_->updateBibfilesCache();
932                 }
933                 break;
934         }
935
936         case LFUN_WORDS_COUNT: {
937                 DocIterator from, to;
938                 if (cur.selection()) {
939                         from = cur.selectionBegin();
940                         to = cur.selectionEnd();
941                 } else {
942                         from = doc_iterator_begin(buffer_->inset());
943                         to = doc_iterator_end(buffer_->inset());
944                 }
945                 int const count = countWords(from, to);
946                 docstring message;
947                 if (count != 1) {
948                         if (cur.selection())
949                                 message = bformat(_("%1$d words in selection."),
950                                           count);
951                                 else
952                                         message = bformat(_("%1$d words in document."),
953                                                           count);
954                 }
955                 else {
956                         if (cur.selection())
957                                 message = _("One word in selection.");
958                         else
959                                 message = _("One word in document.");
960                 }
961
962                 Alert::information(_("Count words"), message);
963         }
964                 break;
965
966         case LFUN_BUFFER_TOGGLE_COMPRESSION:
967                 // turn compression on/off
968                 buffer_->params().compressed = !buffer_->params().compressed;
969                 break;
970
971         case LFUN_NEXT_INSET_TOGGLE: {
972                 // this is the real function we want to invoke
973                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
974                 // if there is an inset at cursor, see whether it
975                 // wants to toggle.
976                 InsetBase * inset = cur.nextInset();
977                 if (inset && inset->isActive()) {
978                         LCursor tmpcur = cur;
979                         tmpcur.pushLeft(*inset);
980                         inset->dispatch(tmpcur, tmpcmd);
981                         if (tmpcur.result().dispatched()) {
982                                 cur.dispatched();
983                         }
984                 }
985                 // if it did not work, try the underlying inset.
986                 if (!cur.result().dispatched())
987                         cur.dispatch(tmpcmd);
988
989                 if (cur.result().dispatched())
990                         cur.clearSelection();
991
992                 break;
993         }
994
995         default:
996                 return false;
997         }
998
999         return true;
1000 }
1001
1002
1003 docstring const BufferView::requestSelection()
1004 {
1005         if (!buffer_)
1006                 return docstring();
1007
1008         LCursor & cur = cursor_;
1009
1010         if (!cur.selection()) {
1011                 xsel_cache_.set = false;
1012                 return docstring();
1013         }
1014
1015         if (!xsel_cache_.set ||
1016             cur.top() != xsel_cache_.cursor ||
1017             cur.anchor_.top() != xsel_cache_.anchor)
1018         {
1019                 xsel_cache_.cursor = cur.top();
1020                 xsel_cache_.anchor = cur.anchor_.top();
1021                 xsel_cache_.set = cur.selection();
1022                 return cur.selectionAsString(false);
1023         }
1024         return docstring();
1025 }
1026
1027
1028 void BufferView::clearSelection()
1029 {
1030         if (buffer_) {
1031                 cursor_.clearSelection();
1032                 xsel_cache_.set = false;
1033         }
1034 }
1035
1036
1037 void BufferView::workAreaResize(int width, int height)
1038 {
1039         bool const widthChange = width != width_;
1040         bool const heightChange = height != height_;
1041
1042         // Update from work area
1043         width_ = width;
1044         height_ = height;
1045
1046         if (buffer_ && widthChange) {
1047                 // The WorkArea content needs a resize
1048                 resize();
1049         }
1050
1051         if (widthChange || heightChange)
1052                 update();
1053 }
1054
1055
1056 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1057 {
1058         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1059
1060         // This is only called for mouse related events including
1061         // LFUN_FILE_OPEN generated by drag-and-drop.
1062         FuncRequest cmd = cmd0;
1063
1064         if (!buffer_)
1065                 return false;
1066
1067         LCursor cur(*this);
1068         cur.push(buffer_->inset());
1069         cur.selection() = cursor_.selection();
1070
1071         // Doesn't go through lyxfunc, so we need to update
1072         // the layout choice etc. ourselves
1073
1074         // E.g. Qt mouse press when no buffer
1075         if (!buffer_)
1076                 return false;
1077
1078         // Either the inset under the cursor or the
1079         // surrounding LyXText will handle this event.
1080
1081         // Build temporary cursor.
1082         cmd.y = min(max(cmd.y, -1), height_);
1083         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1084         //lyxerr << BOOST_CURRENT_FUNCTION
1085         //       << " * hit inset at tip: " << inset << endl;
1086         //lyxerr << BOOST_CURRENT_FUNCTION
1087         //       << " * created temp cursor:" << cur << endl;
1088
1089         // Put anchor at the same position.
1090         cur.resetAnchor();
1091
1092         // Try to dispatch to an non-editable inset near this position
1093         // via the temp cursor. If the inset wishes to change the real
1094         // cursor it has to do so explicitly by using
1095         //  cur.bv().cursor() = cur;  (or similar)
1096         if (inset)
1097                 inset->dispatch(cur, cmd);
1098
1099         // Now dispatch to the temporary cursor. If the real cursor should
1100         // be modified, the inset's dispatch has to do so explicitly.
1101         if (!cur.result().dispatched())
1102                 cur.dispatch(cmd);
1103
1104         if (cur.result().dispatched()) {
1105                 // Redraw if requested or necessary.
1106                 if (cur.result().update())
1107                         update(Update::FitCursor | Update::Force);
1108                 else
1109                         update(Update::FitCursor | Update::MultiParSel);
1110         }
1111
1112         return true;
1113 }
1114
1115
1116 void BufferView::scroll(int lines)
1117 {
1118 //      if (!buffer_)
1119 //              return;
1120 //
1121 //      LyXText const * t = &buffer_->text();
1122 //      int const line_height = defaultRowHeight();
1123 //
1124 //      // The new absolute coordinate
1125 //      int new_top_y = top_y() + lines * line_height;
1126 //
1127 //      // Restrict to a valid value
1128 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1129 //      new_top_y = std::max(0, new_top_y);
1130 //
1131 //      scrollDocView(new_top_y);
1132 //
1133 //      // Update the scrollbar.
1134 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1135 }
1136
1137
1138 void BufferView::setCursorFromRow(int row)
1139 {
1140         int tmpid = -1;
1141         int tmppos = -1;
1142
1143         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1144
1145         if (tmpid == -1)
1146                 buffer_->text().setCursor(cursor_, 0, 0);
1147         else
1148                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1149 }
1150
1151
1152 void BufferView::gotoLabel(docstring const & label)
1153 {
1154         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1155                 vector<docstring> labels;
1156                 it->getLabelList(*buffer_, labels);
1157                 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1158                         setCursor(it);
1159                         update();
1160                         return;
1161                 }
1162         }
1163 }
1164
1165
1166 LyXText * BufferView::getLyXText()
1167 {
1168         LyXText * text = cursor_.innerText();
1169         BOOST_ASSERT(text);
1170         return text;
1171 }
1172
1173
1174 LyXText const * BufferView::getLyXText() const
1175 {
1176         LyXText const * text = cursor_.innerText();
1177         BOOST_ASSERT(text);
1178         return text;
1179 }
1180
1181
1182 int BufferView::workHeight() const
1183 {
1184         return height_;
1185 }
1186
1187
1188 void BufferView::setCursor(DocIterator const & dit)
1189 {
1190         size_t const n = dit.depth();
1191         for (size_t i = 0; i < n; ++i)
1192                 dit[i].inset().edit(cursor_, true);
1193
1194         cursor_.setCursor(dit);
1195         cursor_.selection() = false;
1196 }
1197
1198
1199 void BufferView::mouseSetCursor(LCursor & cur)
1200 {
1201         BOOST_ASSERT(&cur.bv() == this);
1202
1203         // Has the cursor just left the inset?
1204         bool badcursor = false;
1205         if (&cursor_.inset() != &cur.inset())
1206                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1207
1208         // do the dEPM magic if needed
1209         // FIXME: move this to InsetText::notifyCursorLeaves?
1210         if (!badcursor && cursor_.inTexted())
1211                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1212
1213         cursor_ = cur;
1214         cursor_.clearSelection();
1215         cursor_.setTargetX();
1216         finishUndo();
1217
1218 }
1219
1220
1221 void BufferView::putSelectionAt(DocIterator const & cur,
1222                                 int length, bool backwards)
1223 {
1224         cursor_.clearSelection();
1225
1226         setCursor(cur);
1227
1228         if (length) {
1229                 if (backwards) {
1230                         cursor_.pos() += length;
1231                         cursor_.setSelection(cursor_, -length);
1232                 } else
1233                         cursor_.setSelection(cursor_, length);
1234         }
1235 }
1236
1237
1238 LCursor & BufferView::cursor()
1239 {
1240         return cursor_;
1241 }
1242
1243
1244 LCursor const & BufferView::cursor() const
1245 {
1246         return cursor_;
1247 }
1248
1249
1250 lyx::pit_type BufferView::anchor_ref() const
1251 {
1252         return anchor_ref_;
1253 }
1254
1255
1256 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1257 {
1258         return metrics_info_;
1259 }
1260
1261
1262 void BufferView::updateMetrics(bool singlepar)
1263 {
1264         // FIXME (Abdel 19/10/2006):
1265         // There's something fishy in tabular. The coord_cache_ is not
1266         // correctly reconstructed when a character is trying to be inserted.
1267         // Not clearing out the coord_cache_ fixes the crash but I don't know
1268         // what side effect this could have on other insets.
1269         //
1270         // Remove old position cache
1271         // coord_cache_.clear();
1272
1273         LyXText & buftext = buffer_->text();
1274         lyx::pit_type size = int(buftext.paragraphs().size());
1275
1276         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1277                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1278                 offset_ref_ = 0;
1279         }
1280
1281         lyx::pit_type const pit = anchor_ref_;
1282         int pit1 = pit;
1283         int pit2 = pit;
1284         size_t const npit = buftext.paragraphs().size();
1285
1286         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1287         // the (main text, not inset!) paragraph containing the cursor.
1288         // (if this paragraph contains insets etc., rebreaking will
1289         // recursively descend)
1290         if (!singlepar || pit == cursor_.bottom().pit())
1291                 buftext.redoParagraph(pit);
1292         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1293
1294         // Redo paragraphs above anchor if necessary; again, in Single Par
1295         // mode, only if we encounter the (main text) one having the cursor.
1296         int y1 = y0;
1297         while (y1 > 0 && pit1 > 0) {
1298                 y1 -= buftext.getPar(pit1).ascent();
1299                 --pit1;
1300                 if (!singlepar || pit1 == cursor_.bottom().pit())
1301                         buftext.redoParagraph(pit1);
1302                 y1 -= buftext.getPar(pit1).descent();
1303         }
1304
1305
1306         // Take care of ascent of first line
1307         y1 -= buftext.getPar(pit1).ascent();
1308
1309         // Normalize anchor for next time
1310         anchor_ref_ = pit1;
1311         offset_ref_ = -y1;
1312
1313         // Grey at the beginning is ugly
1314         if (pit1 == 0 && y1 > 0) {
1315                 y0 -= y1;
1316                 y1 = 0;
1317                 anchor_ref_ = 0;
1318         }
1319
1320         // Redo paragraphs below the anchor if necessary. Single par mode:
1321         // only the one containing the cursor if encountered.
1322         int y2 = y0;
1323         while (y2 < height_ && pit2 < int(npit) - 1) {
1324                 y2 += buftext.getPar(pit2).descent();
1325                 ++pit2;
1326                 if (!singlepar || pit2 == cursor_.bottom().pit())
1327                         buftext.redoParagraph(pit2);
1328                 y2 += buftext.getPar(pit2).ascent();
1329         }
1330
1331         // Take care of descent of last line
1332         y2 += buftext.getPar(pit2).descent();
1333
1334         // The coordinates of all these paragraphs are correct, cache them
1335         int y = y1;
1336         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1337         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1338                 Paragraph const & par = buftext.getPar(pit);
1339                 y += par.ascent();
1340                 parPos[pit] = Point(0, y);
1341                 if (singlepar && pit == cursor_.bottom().pit()) {
1342                         // In Single Paragraph mode, collect here the
1343                         // y1 and y2 of the (one) paragraph the cursor is in
1344                         y1 = y - par.ascent();
1345                         y2 = y + par.descent();
1346                 }
1347                 y += par.descent();
1348         }
1349
1350         if (singlepar) {
1351                 // collect cursor paragraph iter bounds
1352                 pit1 = cursor_.bottom().pit();
1353                 pit2 = cursor_.bottom().pit();
1354         }
1355
1356         lyxerr[Debug::DEBUG]
1357                 << BOOST_CURRENT_FUNCTION
1358                 << " y1: " << y1
1359                 << " y2: " << y2
1360                 << " pit1: " << pit1
1361                 << " pit2: " << pit2
1362                 << " npit: " << npit
1363                 << " singlepar: " << singlepar
1364                 << "size: " << size
1365                 << endl;
1366
1367         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1368 }
1369
1370
1371 void BufferView::menuInsertLyXFile(string const & filenm)
1372 {
1373         BOOST_ASSERT(cursor_.inTexted());
1374         string filename = filenm;
1375
1376         if (filename.empty()) {
1377                 // Launch a file browser
1378                 // FIXME UNICODE
1379                 string initpath = lyxrc.document_path;
1380
1381                 if (buffer_) {
1382                         string const trypath = buffer_->filePath();
1383                         // If directory is writeable, use this as default.
1384                         if (isDirWriteable(trypath))
1385                                 initpath = trypath;
1386                 }
1387
1388                 // FIXME UNICODE
1389                 FileDialog fileDlg(_("Select LyX document to insert"),
1390                         LFUN_FILE_INSERT,
1391                         make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
1392                         make_pair(_("Examples|#E#e"), lyx::from_utf8(addPath(package().system_support(), "examples"))));
1393
1394                 FileDialog::Result result =
1395                         fileDlg.open(lyx::from_utf8(initpath),
1396                                      FileFilterList(_("LyX Documents (*.lyx)")),
1397                                      docstring());
1398
1399                 if (result.first == FileDialog::Later)
1400                         return;
1401
1402                 // FIXME UNICODE
1403                 filename = lyx::to_utf8(result.second);
1404
1405                 // check selected filename
1406                 if (filename.empty()) {
1407                         // emit message signal.
1408                         message(_("Canceled."));
1409                         return;
1410                 }
1411         }
1412
1413         // Get absolute path of file and add ".lyx"
1414         // to the filename if necessary
1415         filename = fileSearch(string(), filename, "lyx");
1416
1417         docstring const disp_fn = makeDisplayPath(filename);
1418         // emit message signal.
1419         message(bformat(_("Inserting document %1$s..."), disp_fn));
1420
1421         docstring res;
1422         Buffer buf("", false);
1423         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1424                 ErrorList & el = buffer_->errorList("Parse");
1425                 // Copy the inserted document error list into the current buffer one.
1426                 el = buf.errorList("Parse");
1427                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1428                                              buf.params().textclass, el);
1429                 res = _("Document %1$s inserted.");
1430         } else
1431                 res = _("Could not insert document %1$s");
1432
1433         // emit message signal.
1434         message(bformat(res, disp_fn));
1435         buffer_->errors("Parse");
1436         resize();
1437 }