3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
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"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
94 using std::istringstream;
98 using std::mem_fun_ref;
102 namespace Alert = frontend::Alert;
106 /// Return an inset of this class if it exists at the current cursor position
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
111 DocIterator it = cur;
112 if (it.nextInset() &&
113 it.nextInset()->lyxCode() == code) {
114 inset = static_cast<T*>(it.nextInset());
122 BufferView::BufferView()
123 : width_(0), height_(0), buffer_(0), wh_(0),
125 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 xsel_cache_.set = false;
129 intl_->initKeyMapper(lyxrc.use_kbmap);
133 BufferView::~BufferView()
138 Buffer * BufferView::buffer() const
144 void BufferView::setBuffer(Buffer * b)
146 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147 << "[ b = " << b << "]" << endl;
150 // Save the actual cursor position and anchor inside the
151 // buffer so that it can be restored in case we rechange
152 // to this buffer later on.
153 buffer_->saveCursor(cursor_.selectionBegin(),
154 cursor_.selectionEnd());
155 // current buffer is going to be switched-off, save cursor pos
156 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157 boost::tie(cursor_.pit(), cursor_.pos()) );
160 // If we're quitting lyx, don't bother updating stuff
166 // If we are closing current buffer, switch to the first in
169 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170 << " No Buffer!" << endl;
171 // We are closing the buffer, use the first buffer as current
172 buffer_ = theBufferList().first();
174 // Set current buffer
179 cursor_ = LCursor(*this);
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << "Buffer addr: " << buffer_ << endl;
186 cursor_.push(buffer_->inset());
187 cursor_.resetAnchor();
188 buffer_->text().init(this);
189 buffer_->text().setCurrentFont(cursor_);
190 if (buffer_->getCursor().size() > 0 &&
191 buffer_->getAnchor().size() > 0)
193 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194 cursor_.resetAnchor();
195 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196 cursor_.setSelection();
201 updateMetrics(false);
203 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
204 graphics::Previews::get().generateBufferPreviews(*buffer_);
208 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
210 // Get absolute path of file and add ".lyx"
211 // to the filename if necessary
212 string s = fileSearch(string(), filename, "lyx");
214 bool const found = !s.empty();
219 // File already open?
220 if (theBufferList().exists(s)) {
221 docstring const file = makeDisplayPath(s, 20);
222 docstring text = bformat(_("The document %1$s is already "
223 "loaded.\n\nDo you want to revert "
224 "to the saved version?"), file);
225 int const ret = Alert::prompt(_("Revert to saved document?"),
226 text, 0, 1, _("&Revert"), _("&Switch to document"));
229 setBuffer(theBufferList().getBuffer(s));
232 // FIXME: should be LFUN_REVERT
233 if (!theBufferList().close(theBufferList().getBuffer(s), false))
235 // Fall through to new load. (Asger)
242 b = theBufferList().newBuffer(s);
243 if (!lyx::loadLyXFile(b, s)) {
244 theBufferList().release(b);
248 docstring text = bformat(_("The document %1$s does not yet "
249 "exist.\n\nDo you want to create "
250 "a new document?"), from_utf8(s));
251 int const ret = Alert::prompt(_("Create new document?"),
252 text, 0, 1, _("&Create"), _("Cancel"));
255 b = newFile(s, string(), true);
263 // Send the "errors" signal in case of parsing errors
266 // scroll to the position when the file was last closed
267 if (lyxrc.use_lastfilepos) {
270 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
271 // I am not sure how to separate the following part to a function
272 // so I will leave this to Lars.
274 // check pit since the document may be externally changed.
275 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
276 ParIterator it = b->par_iterator_begin();
277 ParIterator const end = b->par_iterator_end();
278 for (; it != end; ++it)
279 if (it.pit() == pit) {
280 // restored pos may be bigger than it->size
281 setCursor(makeDocIterator(it, min(pos, it->size())));
282 // No need to update the metrics if fitCursor returns false.
284 updateMetrics(false);
291 LyX::ref().session().lastFiles().add(b->fileName());
297 void BufferView::reload()
299 string const fn = buffer_->fileName();
300 if (theBufferList().close(buffer_, false))
305 void BufferView::resize()
310 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
312 buffer_->text().init(this);
318 bool BufferView::fitCursor()
320 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
321 frontend::FontMetrics const & fm =
322 theFontMetrics(cursor_.getFont());
323 int const asc = fm.maxAscent();
324 int const des = fm.maxDescent();
325 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
326 if (p.y_ - asc >= 0 && p.y_ + des < height_)
334 bool BufferView::multiParSel()
336 if (!cursor_.selection())
338 bool ret = multiparsel_cache_;
339 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
340 // Either this, or previous selection spans paragraphs
341 return ret || multiparsel_cache_;
345 std::pair<bool, bool> BufferView::update(Update::flags flags)
347 // This is close to a hot-path.
348 if (lyxerr.debugging(Debug::DEBUG)) {
350 << BOOST_CURRENT_FUNCTION
351 << "[fitcursor = " << (flags & Update::FitCursor)
352 << ", forceupdate = " << (flags & Update::Force)
353 << ", singlepar = " << (flags & Update::SinglePar)
354 << "] buffer: " << buffer_ << endl;
357 // Check needed to survive LyX startup
359 return make_pair(false, false);
361 if (lyxerr.debugging(Debug::WORKAREA)) {
362 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
365 // Update macro store
366 buffer_->buildMacros();
368 // Now do the first drawing step if needed. This consists on updating
369 // the CoordCache in updateMetrics().
370 // The second drawing step is done in WorkArea::redraw() if needed.
372 // Case when no explicit update is requested.
374 // no need to do anything.
375 return make_pair(false, false);
378 if (flags == Update::FitCursor) {
379 bool const fit_cursor = fitCursor();
381 updateMetrics(false);
382 // tell the frontend to update the screen.
383 return make_pair(fit_cursor, false);
386 bool full_metrics = flags & Update::Force;
387 if (flags & Update::MultiParSel)
388 full_metrics |= multiParSel();
390 bool const single_par = !full_metrics;
391 updateMetrics(single_par);
393 if (flags & Update::FitCursor && fitCursor())
394 updateMetrics(false);
396 // tell the frontend to update the screen.
397 return make_pair(true, single_par);
401 void BufferView::updateScrollbar()
404 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
405 << " no text in updateScrollbar" << endl;
406 scrollbarParameters_.reset();
410 LyXText & t = buffer_->text();
411 int const parsize = int(t.paragraphs().size() - 1);
412 if (anchor_ref_ > parsize) {
413 anchor_ref_ = parsize;
417 if (lyxerr.debugging(Debug::GUI)) {
419 << BOOST_CURRENT_FUNCTION
420 << " Updating scrollbar: height: " << t.paragraphs().size()
421 << " curr par: " << cursor_.bottom().pit()
422 << " default height " << defaultRowHeight() << endl;
425 // It would be better to fix the scrollbar to understand
426 // values in [0..1] and divide everything by wh
428 // estimated average paragraph height:
431 int h = t.getPar(anchor_ref_).height();
433 // Normalize anchor/offset (MV):
434 while (offset_ref_ > h && anchor_ref_ < parsize) {
437 h = t.getPar(anchor_ref_).height();
439 // Look at paragraph heights on-screen
442 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
445 int const h2 = t.getPar(pit).height();
451 int const hav = sumh / nh;
452 // More realistic average paragraph height
457 scrollbarParameters_.height = (parsize + 1) * wh_;
458 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
459 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
463 ScrollbarParameters const & BufferView::scrollbarParameters() const
465 return scrollbarParameters_;
469 void BufferView::scrollDocView(int value)
471 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
472 << "[ value = " << value << "]" << endl;
477 LyXText & t = buffer_->text();
479 float const bar = value / float(wh_ * t.paragraphs().size());
481 anchor_ref_ = int(bar * t.paragraphs().size());
482 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
483 anchor_ref_ = int(t.paragraphs().size()) - 1;
484 t.redoParagraph(*this, anchor_ref_);
485 int const h = t.getPar(anchor_ref_).height();
486 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
487 updateMetrics(false);
491 void BufferView::setCursorFromScrollbar()
493 LyXText & t = buffer_->text();
495 int const height = 2 * defaultRowHeight();
496 int const first = height;
497 int const last = height_ - height;
498 LCursor & cur = cursor_;
500 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
503 case bv_funcs::CUR_ABOVE:
504 t.setCursorFromCoordinates(cur, 0, first);
505 cur.clearSelection();
507 case bv_funcs::CUR_BELOW:
508 t.setCursorFromCoordinates(cur, 0, last);
509 cur.clearSelection();
511 case bv_funcs::CUR_INSIDE:
512 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
513 int const newy = min(last, max(y, first));
515 cur.reset(buffer_->inset());
516 t.setCursorFromCoordinates(cur, 0, newy);
522 Change const BufferView::getCurrentChange() const
524 if (!cursor_.selection())
525 return Change(Change::UNCHANGED);
527 DocIterator dit = cursor_.selectionBegin();
528 return dit.paragraph().lookupChange(dit.pos());
532 void BufferView::saveBookmark(bool persistent)
534 LyX::ref().session().bookmarks().save(
536 cursor_.paragraph().id(),
541 // emit message signal.
542 message(_("Save bookmark"));
546 void BufferView::moveToPosition(int par_id, pos_type par_pos)
548 cursor_.clearSelection();
550 ParIterator par = buffer_->getParFromID(par_id);
551 if (par == buffer_->par_iterator_end())
554 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
558 void BufferView::switchKeyMap()
560 if (!lyxrc.rtl_support)
563 if (getLyXText()->real_current_font.isRightToLeft()) {
564 if (intl_->keymap == Intl::PRIMARY)
567 if (intl_->keymap == Intl::SECONDARY)
573 int BufferView::workWidth() const
579 void BufferView::center()
581 CursorSlice & bot = cursor_.bottom();
582 pit_type const pit = bot.pit();
583 bot.text()->redoParagraph(*this, pit);
584 Paragraph const & par = bot.text()->paragraphs()[pit];
586 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
587 + par.ascent() - height_ / 2;
591 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
595 switch (cmd.action) {
598 flag.enabled(!buffer_->undostack().empty());
601 flag.enabled(!buffer_->redostack().empty());
603 case LFUN_FILE_INSERT:
604 case LFUN_FILE_INSERT_ASCII_PARA:
605 case LFUN_FILE_INSERT_ASCII:
606 case LFUN_BOOKMARK_SAVE:
607 // FIXME: Actually, these LFUNS should be moved to LyXText
608 flag.enabled(cursor_.inTexted());
610 case LFUN_FONT_STATE:
611 case LFUN_LABEL_INSERT:
612 case LFUN_PARAGRAPH_GOTO:
613 // FIXME handle non-trivially
614 case LFUN_OUTLINE_UP:
615 case LFUN_OUTLINE_DOWN:
616 case LFUN_OUTLINE_IN:
617 case LFUN_OUTLINE_OUT:
619 case LFUN_REFERENCE_NEXT:
621 case LFUN_WORD_REPLACE:
624 case LFUN_MARK_TOGGLE:
625 case LFUN_SCREEN_RECENTER:
626 case LFUN_BIBTEX_DATABASE_ADD:
627 case LFUN_BIBTEX_DATABASE_DEL:
628 case LFUN_WORDS_COUNT:
629 case LFUN_NEXT_INSET_TOGGLE:
633 case LFUN_LABEL_GOTO: {
634 flag.enabled(!cmd.argument().empty()
635 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
639 case LFUN_CHANGES_TRACK:
641 flag.setOnOff(buffer_->params().trackChanges);
644 case LFUN_CHANGES_OUTPUT: {
645 OutputParams runparams;
646 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
647 flag.enabled(buffer_ && features.isAvailable("dvipost"));
648 flag.setOnOff(buffer_->params().outputChanges);
652 case LFUN_CHANGES_MERGE:
653 case LFUN_CHANGE_NEXT:
654 case LFUN_ALL_CHANGES_ACCEPT:
655 case LFUN_ALL_CHANGES_REJECT:
656 flag.enabled(buffer_); // FIXME: Change tracking (MG)
659 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
660 flag.setOnOff(buffer_->params().compressed);
672 bool BufferView::dispatch(FuncRequest const & cmd)
674 //lyxerr << BOOST_CURRENT_FUNCTION
675 // << [ cmd = " << cmd << "]" << endl;
677 // Make sure that the cached BufferView is correct.
678 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
679 << " action[" << cmd.action << ']'
680 << " arg[" << to_utf8(cmd.argument()) << ']'
681 << " x[" << cmd.x << ']'
682 << " y[" << cmd.y << ']'
683 << " button[" << cmd.button() << ']'
686 LCursor & cur = cursor_;
688 switch (cmd.action) {
692 cur.message(_("Undo"));
693 cur.clearSelection();
694 if (!textUndo(*this))
695 cur.message(_("No further undo information"));
703 cur.message(_("Redo"));
704 cur.clearSelection();
705 if (!textRedo(*this))
706 cur.message(_("No further redo information"));
712 case LFUN_FILE_INSERT:
713 // FIXME: We don't know the encoding of filenames
714 menuInsertLyXFile(to_utf8(cmd.argument()));
717 case LFUN_FILE_INSERT_ASCII_PARA:
718 // FIXME: We don't know the encoding of filenames
719 insertAsciiFile(this, to_utf8(cmd.argument()), true);
722 case LFUN_FILE_INSERT_ASCII:
723 // FIXME: We don't know the encoding of filenames
724 insertAsciiFile(this, to_utf8(cmd.argument()), false);
727 case LFUN_FONT_STATE:
728 cur.message(from_utf8(cur.currentState()));
731 case LFUN_BOOKMARK_SAVE:
732 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
735 case LFUN_LABEL_GOTO: {
736 docstring label = cmd.argument();
739 getInsetByCode<InsetRef>(cursor_,
740 InsetBase::REF_CODE);
742 label = inset->getParam("reference");
743 // persistent=false: use temp_bookmark
753 case LFUN_PARAGRAPH_GOTO: {
754 int const id = convert<int>(to_utf8(cmd.argument()));
756 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
757 ParIterator par = b->getParFromID(id);
758 if (par == b->par_iterator_end()) {
760 << "No matching paragraph found! ["
761 << id << "]." << endl;
764 << "Paragraph " << par->id()
765 << " found in buffer `"
766 << b->fileName() << "'." << endl;
770 setCursor(makeDocIterator(par, 0));
774 // Switch to other buffer view and resend cmd
775 theLyXFunc().dispatch(FuncRequest(
776 LFUN_BUFFER_SWITCH, b->fileName()));
777 theLyXFunc().dispatch(cmd);
786 case LFUN_OUTLINE_UP:
787 toc::outline(toc::Up, cursor_);
788 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
789 updateLabels(*buffer_);
791 case LFUN_OUTLINE_DOWN:
792 toc::outline(toc::Down, cursor_);
793 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
794 updateLabels(*buffer_);
796 case LFUN_OUTLINE_IN:
797 toc::outline(toc::In, cursor_);
798 updateLabels(*buffer_);
800 case LFUN_OUTLINE_OUT:
801 toc::outline(toc::Out, cursor_);
802 updateLabels(*buffer_);
806 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
809 case LFUN_REFERENCE_NEXT: {
810 vector<InsetBase_code> tmp;
811 tmp.push_back(InsetBase::LABEL_CODE);
812 tmp.push_back(InsetBase::REF_CODE);
813 bv_funcs::gotoInset(this, tmp, true);
817 case LFUN_CHANGES_TRACK:
818 buffer_->params().trackChanges = !buffer_->params().trackChanges;
821 case LFUN_CHANGES_OUTPUT: {
822 buffer_->params().outputChanges = !buffer_->params().outputChanges;
826 case LFUN_CHANGE_NEXT:
827 findNextChange(this);
830 case LFUN_CHANGES_MERGE:
831 if (findNextChange(this))
832 showDialog("changes");
835 case LFUN_ALL_CHANGES_ACCEPT: {
836 cursor_.reset(buffer_->inset());
838 #warning FIXME changes
840 while (findNextChange(this))
841 getLyXText()->acceptChange(cursor_);
846 case LFUN_ALL_CHANGES_REJECT: {
847 cursor_.reset(buffer_->inset());
849 #warning FIXME changes
851 while (findNextChange(this))
852 getLyXText()->rejectChange(cursor_);
860 case LFUN_WORD_REPLACE:
865 cur.clearSelection();
867 cur.message(from_utf8(N_("Mark off")));
871 cur.clearSelection();
874 cur.message(from_utf8(N_("Mark on")));
877 case LFUN_MARK_TOGGLE:
878 cur.clearSelection();
881 cur.message(from_utf8(N_("Mark removed")));
884 cur.message(from_utf8(N_("Mark set")));
889 case LFUN_SCREEN_RECENTER:
893 case LFUN_BIBTEX_DATABASE_ADD: {
894 LCursor tmpcur = cursor_;
895 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
896 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
897 InsetBase::BIBTEX_CODE);
899 if (inset->addDatabase(to_utf8(cmd.argument())))
900 buffer_->updateBibfilesCache();
905 case LFUN_BIBTEX_DATABASE_DEL: {
906 LCursor tmpcur = cursor_;
907 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
908 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
909 InsetBase::BIBTEX_CODE);
911 if (inset->delDatabase(to_utf8(cmd.argument())))
912 buffer_->updateBibfilesCache();
917 case LFUN_WORDS_COUNT: {
918 DocIterator from, to;
919 if (cur.selection()) {
920 from = cur.selectionBegin();
921 to = cur.selectionEnd();
923 from = doc_iterator_begin(buffer_->inset());
924 to = doc_iterator_end(buffer_->inset());
926 int const count = countWords(from, to);
930 message = bformat(_("%1$d words in selection."),
933 message = bformat(_("%1$d words in document."),
938 message = _("One word in selection.");
940 message = _("One word in document.");
943 Alert::information(_("Count words"), message);
947 case LFUN_BUFFER_TOGGLE_COMPRESSION:
948 // turn compression on/off
949 buffer_->params().compressed = !buffer_->params().compressed;
952 case LFUN_NEXT_INSET_TOGGLE: {
953 // this is the real function we want to invoke
954 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
955 // if there is an inset at cursor, see whether it
957 InsetBase * inset = cur.nextInset();
958 if (inset && inset->isActive()) {
959 LCursor tmpcur = cur;
960 tmpcur.pushLeft(*inset);
961 inset->dispatch(tmpcur, tmpcmd);
962 if (tmpcur.result().dispatched()) {
966 // if it did not work, try the underlying inset.
967 if (!cur.result().dispatched())
968 cur.dispatch(tmpcmd);
970 if (cur.result().dispatched())
971 cur.clearSelection();
984 docstring const BufferView::requestSelection()
989 LCursor & cur = cursor_;
991 if (!cur.selection()) {
992 xsel_cache_.set = false;
996 if (!xsel_cache_.set ||
997 cur.top() != xsel_cache_.cursor ||
998 cur.anchor_.top() != xsel_cache_.anchor)
1000 xsel_cache_.cursor = cur.top();
1001 xsel_cache_.anchor = cur.anchor_.top();
1002 xsel_cache_.set = cur.selection();
1003 return cur.selectionAsString(false);
1009 void BufferView::clearSelection()
1012 cursor_.clearSelection();
1013 xsel_cache_.set = false;
1018 void BufferView::workAreaResize(int width, int height)
1020 bool const widthChange = width != width_;
1021 bool const heightChange = height != height_;
1023 // Update from work area
1034 std::pair<bool, bool> BufferView::workAreaDispatch(FuncRequest const & cmd0)
1036 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1038 // This is only called for mouse related events including
1039 // LFUN_FILE_OPEN generated by drag-and-drop.
1040 FuncRequest cmd = cmd0;
1042 // E.g. Qt mouse press when no buffer
1044 return make_pair(false, false);
1047 cur.push(buffer_->inset());
1048 cur.selection() = cursor_.selection();
1050 // Either the inset under the cursor or the
1051 // surrounding LyXText will handle this event.
1053 // Build temporary cursor.
1054 cmd.y = min(max(cmd.y, -1), height_);
1055 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1057 //lyxerr << BOOST_CURRENT_FUNCTION
1058 // << " * hit inset at tip: " << inset << endl;
1059 //lyxerr << BOOST_CURRENT_FUNCTION
1060 // << " * created temp cursor:" << cur << endl;
1062 // Put anchor at the same position.
1065 // Try to dispatch to an non-editable inset near this position
1066 // via the temp cursor. If the inset wishes to change the real
1067 // cursor it has to do so explicitly by using
1068 // cur.bv().cursor() = cur; (or similar)
1070 inset->dispatch(cur, cmd);
1073 // Now dispatch to the temporary cursor. If the real cursor should
1074 // be modified, the inset's dispatch has to do so explicitly.
1075 if (!cur.result().dispatched())
1078 // Redraw if requested and necessary.
1079 if (cur.result().dispatched() && cur.result().update())
1080 return update(cur.result().update());
1082 // When the above and the inner function are fixed, we can do this:
1083 return make_pair(false, false);
1087 void BufferView::scroll(int /*lines*/)
1092 // LyXText const * t = &buffer_->text();
1093 // int const line_height = defaultRowHeight();
1095 // // The new absolute coordinate
1096 // int new_top_y = top_y() + lines * line_height;
1098 // // Restrict to a valid value
1099 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1100 // new_top_y = std::max(0, new_top_y);
1102 // scrollDocView(new_top_y);
1104 // // Update the scrollbar.
1105 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1109 void BufferView::setCursorFromRow(int row)
1114 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1117 buffer_->text().setCursor(cursor_, 0, 0);
1119 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1123 void BufferView::gotoLabel(docstring const & label)
1125 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1126 vector<docstring> labels;
1127 it->getLabelList(*buffer_, labels);
1128 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1137 LyXText * BufferView::getLyXText()
1139 LyXText * text = cursor_.innerText();
1145 LyXText const * BufferView::getLyXText() const
1147 LyXText const * text = cursor_.innerText();
1153 int BufferView::workHeight() const
1159 void BufferView::setCursor(DocIterator const & dit)
1161 size_t const n = dit.depth();
1162 for (size_t i = 0; i < n; ++i)
1163 dit[i].inset().edit(cursor_, true);
1165 cursor_.setCursor(dit);
1166 cursor_.selection() = false;
1170 void BufferView::mouseSetCursor(LCursor & cur)
1172 BOOST_ASSERT(&cur.bv() == this);
1174 // Has the cursor just left the inset?
1175 bool badcursor = false;
1176 if (&cursor_.inset() != &cur.inset())
1177 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1179 // do the dEPM magic if needed
1180 // FIXME: move this to InsetText::notifyCursorLeaves?
1181 if (!badcursor && cursor_.inTexted())
1182 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1185 cursor_.clearSelection();
1186 cursor_.setTargetX();
1192 void BufferView::putSelectionAt(DocIterator const & cur,
1193 int length, bool backwards)
1195 cursor_.clearSelection();
1201 cursor_.pos() += length;
1202 cursor_.setSelection(cursor_, -length);
1204 cursor_.setSelection(cursor_, length);
1209 LCursor & BufferView::cursor()
1215 LCursor const & BufferView::cursor() const
1221 pit_type BufferView::anchor_ref() const
1227 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1229 return metrics_info_;
1233 void BufferView::updateMetrics(bool singlepar)
1235 // Clear out the position cache in case of full screen redraw.
1237 coord_cache_.clear();
1239 LyXText & buftext = buffer_->text();
1240 pit_type size = int(buftext.paragraphs().size());
1242 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1243 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1247 pit_type const pit = anchor_ref_;
1250 size_t const npit = buftext.paragraphs().size();
1252 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1253 // the (main text, not inset!) paragraph containing the cursor.
1254 // (if this paragraph contains insets etc., rebreaking will
1255 // recursively descend)
1256 if (!singlepar || pit == cursor_.bottom().pit())
1257 buftext.redoParagraph(*this, pit);
1258 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1260 // Redo paragraphs above anchor if necessary; again, in Single Par
1261 // mode, only if we encounter the (main text) one having the cursor.
1263 while (y1 > 0 && pit1 > 0) {
1264 y1 -= buftext.getPar(pit1).ascent();
1266 if (!singlepar || pit1 == cursor_.bottom().pit())
1267 buftext.redoParagraph(*this, pit1);
1268 y1 -= buftext.getPar(pit1).descent();
1272 // Take care of ascent of first line
1273 y1 -= buftext.getPar(pit1).ascent();
1275 // Normalize anchor for next time
1279 // Grey at the beginning is ugly
1280 if (pit1 == 0 && y1 > 0) {
1286 // Redo paragraphs below the anchor if necessary. Single par mode:
1287 // only the one containing the cursor if encountered.
1289 while (y2 < height_ && pit2 < int(npit) - 1) {
1290 y2 += buftext.getPar(pit2).descent();
1292 if (!singlepar || pit2 == cursor_.bottom().pit())
1293 buftext.redoParagraph(*this, pit2);
1294 y2 += buftext.getPar(pit2).ascent();
1297 // Take care of descent of last line
1298 y2 += buftext.getPar(pit2).descent();
1300 // The coordinates of all these paragraphs are correct, cache them
1302 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1303 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1304 Paragraph const & par = buftext.getPar(pit);
1306 parPos[pit] = Point(0, y);
1307 if (singlepar && pit == cursor_.bottom().pit()) {
1308 // In Single Paragraph mode, collect here the
1309 // y1 and y2 of the (one) paragraph the cursor is in
1310 y1 = y - par.ascent();
1311 y2 = y + par.descent();
1317 // collect cursor paragraph iter bounds
1318 pit1 = cursor_.bottom().pit();
1319 pit2 = cursor_.bottom().pit();
1322 lyxerr[Debug::DEBUG]
1323 << BOOST_CURRENT_FUNCTION
1326 << " pit1: " << pit1
1327 << " pit2: " << pit2
1328 << " npit: " << npit
1329 << " singlepar: " << singlepar
1333 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1335 if (lyxerr.debugging(Debug::WORKAREA)) {
1336 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1337 coord_cache_.dump();
1342 void BufferView::menuInsertLyXFile(string const & filenm)
1344 BOOST_ASSERT(cursor_.inTexted());
1345 string filename = filenm;
1347 if (filename.empty()) {
1348 // Launch a file browser
1350 string initpath = lyxrc.document_path;
1353 string const trypath = buffer_->filePath();
1354 // If directory is writeable, use this as default.
1355 if (isDirWriteable(trypath))
1360 FileDialog fileDlg(_("Select LyX document to insert"),
1362 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1363 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1365 FileDialog::Result result =
1366 fileDlg.open(from_utf8(initpath),
1367 FileFilterList(_("LyX Documents (*.lyx)")),
1370 if (result.first == FileDialog::Later)
1374 filename = to_utf8(result.second);
1376 // check selected filename
1377 if (filename.empty()) {
1378 // emit message signal.
1379 message(_("Canceled."));
1384 // Get absolute path of file and add ".lyx"
1385 // to the filename if necessary
1386 filename = fileSearch(string(), filename, "lyx");
1388 docstring const disp_fn = makeDisplayPath(filename);
1389 // emit message signal.
1390 message(bformat(_("Inserting document %1$s..."), disp_fn));
1393 Buffer buf("", false);
1394 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1395 ErrorList & el = buffer_->errorList("Parse");
1396 // Copy the inserted document error list into the current buffer one.
1397 el = buf.errorList("Parse");
1398 recordUndo(cursor_);
1399 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1400 buf.params().textclass, el);
1401 res = _("Document %1$s inserted.");
1403 res = _("Could not insert document %1$s");
1405 // emit message signal.
1406 message(bformat(res, disp_fn));
1407 buffer_->errors("Parse");