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