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/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"
71 #include "graphics/Previews.h"
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"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
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;
103 using std::istringstream;
105 using std::make_pair;
108 using std::mem_fun_ref;
112 extern BufferList bufferlist;
117 unsigned int const saved_positions_num = 20;
120 /// Return an inset of this class if it exists at the current cursor position
122 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
125 DocIterator it = cur;
126 if (it.nextInset() &&
127 it.nextInset()->lyxCode() == code) {
128 inset = static_cast<T*>(it.nextInset());
136 BufferView::BufferView(LyXView * owner)
137 : owner_(owner), buffer_(0), wh_(0),
139 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
141 xsel_cache_.set = false;
143 saved_positions.resize(saved_positions_num);
144 // load saved bookmarks
145 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
146 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
147 bm != bmList.end(); ++bm)
148 if (bm->get<0>() < saved_positions_num)
149 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
150 // and then clear them
155 BufferView::~BufferView()
160 void BufferView::unsetXSel()
162 xsel_cache_.set = false;
166 Buffer * BufferView::buffer() const
172 LyXView * BufferView::owner() const
178 void BufferView::setBuffer(Buffer * b)
180 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
181 << "[ b = " << b << "]" << endl;
184 // Save the actual cursor position and anchor inside the
185 // buffer so that it can be restored in case we rechange
186 // to this buffer later on.
187 buffer_->saveCursor(cursor_.selectionBegin(),
188 cursor_.selectionEnd());
189 // current buffer is going to be switched-off, save cursor pos
190 LyX::ref().session().saveFilePosition(buffer_->fileName(),
191 boost::tie(cursor_.pit(), cursor_.pos()) );
194 // If we're quitting lyx, don't bother updating stuff
200 // If we are closing current buffer, switch to the first in
203 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
204 << " No Buffer!" << endl;
205 // We are closing the buffer, use the first buffer as current
206 buffer_ = bufferlist.first();
208 // Set current buffer
213 cursor_ = LCursor(*this);
218 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
219 << "Buffer addr: " << buffer_ << endl;
220 cursor_.push(buffer_->inset());
221 cursor_.resetAnchor();
222 buffer_->text().init(this);
223 buffer_->text().setCurrentFont(cursor_);
224 if (buffer_->getCursor().size() > 0 &&
225 buffer_->getAnchor().size() > 0)
227 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
228 cursor_.resetAnchor();
229 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
230 cursor_.setSelection();
236 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
237 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
241 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
243 // Get absolute path of file and add ".lyx"
244 // to the filename if necessary
245 string s = fileSearch(string(), filename, "lyx");
247 bool const found = !s.empty();
252 // File already open?
253 if (bufferlist.exists(s)) {
254 docstring const file = makeDisplayPath(s, 20);
255 docstring text = bformat(_("The document %1$s is already "
256 "loaded.\n\nDo you want to revert "
257 "to the saved version?"), file);
258 int const ret = Alert::prompt(_("Revert to saved document?"),
259 text, 0, 1, _("&Revert"), _("&Switch to document"));
262 setBuffer(bufferlist.getBuffer(s));
265 // FIXME: should be LFUN_REVERT
266 if (!bufferlist.close(bufferlist.getBuffer(s), false))
268 // Fall through to new load. (Asger)
274 b = bufferlist.newBuffer(s);
275 if (!::loadLyXFile(b, s)) {
276 bufferlist.release(b);
280 docstring text = bformat(_("The document %1$s does not yet "
281 "exist.\n\nDo you want to create "
282 "a new document?"), lyx::from_utf8(s));
283 int const ret = Alert::prompt(_("Create new document?"),
284 text, 0, 1, _("&Create"), _("Cancel"));
287 b = newFile(s, string(), true);
295 // Send the "errors" signal in case of parsing errors
298 // scroll to the position when the file was last closed
299 if (lyxrc.use_lastfilepos) {
302 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
303 // I am not sure how to separate the following part to a function
304 // so I will leave this to Lars.
306 // check pit since the document may be externally changed.
307 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
308 ParIterator it = b->par_iterator_begin();
309 ParIterator const end = b->par_iterator_end();
310 for (; it != end; ++it)
311 if (it.pit() == pit) {
312 // restored pos may be bigger than it->size
313 setCursor(makeDocIterator(it, min(pos, it->size())));
314 update(Update::FitCursor);
321 LyX::ref().session().addLastFile(b->fileName());
327 void BufferView::reload()
329 string const fn = buffer_->fileName();
330 if (bufferlist.close(buffer_, false))
335 void BufferView::resize()
340 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
342 buffer_->text().init(this);
348 bool BufferView::fitCursor()
350 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
351 LyXFont const font = cursor_.getFont();
352 int const asc = font_metrics::maxAscent(font);
353 int const des = font_metrics::maxDescent(font);
354 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
355 if (p.y_ - asc >= 0 && p.y_ + des < height_)
363 bool BufferView::multiParSel()
365 if (!cursor_.selection())
367 bool ret = multiparsel_cache_;
368 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
369 // Either this, or previous selection spans paragraphs
370 return ret || multiparsel_cache_;
374 bool BufferView::update(Update::flags flags)
376 // This is close to a hot-path.
377 if (lyxerr.debugging(Debug::DEBUG)) {
379 << BOOST_CURRENT_FUNCTION
380 << "[fitcursor = " << (flags & Update::FitCursor)
381 << ", forceupdate = " << (flags & Update::Force)
382 << ", singlepar = " << (flags & Update::SinglePar)
383 << "] buffer: " << buffer_ << endl;
386 // Check needed to survive LyX startup
390 // Update macro store
391 buffer_->buildMacros();
393 // First drawing step
394 updateMetrics(flags & Update::SinglePar);
396 // The second drawing step is done in WorkArea::redraw() if needed.
397 bool const need_second_step =
398 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
399 && (fitCursor() || multiParSel());
401 return need_second_step;
405 void BufferView::updateScrollbar()
408 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
409 << " no text in updateScrollbar" << endl;
410 scrollbarParameters_.reset();
414 LyXText & t = buffer_->text();
415 int const parsize = int(t.paragraphs().size() - 1);
416 if (anchor_ref_ > parsize) {
417 anchor_ref_ = parsize;
422 << BOOST_CURRENT_FUNCTION
423 << " Updating scrollbar: height: " << t.paragraphs().size()
424 << " curr par: " << cursor_.bottom().pit()
425 << " default height " << defaultRowHeight() << endl;
427 // It would be better to fix the scrollbar to understand
428 // values in [0..1] and divide everything by wh
430 // estimated average paragraph height:
433 int h = t.getPar(anchor_ref_).height();
435 // Normalize anchor/offset (MV):
436 while (offset_ref_ > h && anchor_ref_ < parsize) {
439 h = t.getPar(anchor_ref_).height();
441 // Look at paragraph heights on-screen
444 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
447 int const h2 = t.getPar(pit).height();
451 int const hav = sumh / nh;
452 // More realistic average paragraph height
456 scrollbarParameters_.height = (parsize + 1) * wh_;
457 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
458 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
462 ScrollbarParameters const & BufferView::scrollbarParameters() const
464 return scrollbarParameters_;
468 void BufferView::scrollDocView(int value)
470 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
471 << "[ value = " << value << "]" << endl;
476 LyXText & t = buffer_->text();
478 float const bar = value / float(wh_ * t.paragraphs().size());
480 anchor_ref_ = int(bar * t.paragraphs().size());
481 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
482 anchor_ref_ = int(t.paragraphs().size()) - 1;
483 t.redoParagraph(anchor_ref_);
484 int const h = t.getPar(anchor_ref_).height();
485 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
489 void BufferView::setCursorFromScrollbar()
491 LyXText & t = buffer_->text();
493 int const height = 2 * defaultRowHeight();
494 int const first = height;
495 int const last = height_ - height;
496 LCursor & cur = cursor_;
498 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
501 case bv_funcs::CUR_ABOVE:
502 t.setCursorFromCoordinates(cur, 0, first);
503 cur.clearSelection();
505 case bv_funcs::CUR_BELOW:
506 t.setCursorFromCoordinates(cur, 0, last);
507 cur.clearSelection();
509 case bv_funcs::CUR_INSIDE:
510 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
511 int const newy = min(last, max(y, first));
513 cur.reset(buffer_->inset());
514 t.setCursorFromCoordinates(cur, 0, newy);
520 bool BufferView::available() const
526 Change const BufferView::getCurrentChange()
528 if (!buffer_->params().tracking_changes || !cursor_.selection())
529 return Change(Change::UNCHANGED);
531 DocIterator dit = cursor_.selectionBegin();
532 return dit.paragraph().lookupChange(dit.pos());
536 void BufferView::savePosition(unsigned int i)
538 if (i >= saved_positions_num)
540 BOOST_ASSERT(cursor_.inTexted());
541 saved_positions[i] = Position(buffer_->fileName(),
542 cursor_.paragraph().id(),
545 // emit message signal.
546 message(bformat(_("Saved bookmark %1$d"), i));
550 void BufferView::restorePosition(unsigned int i)
552 if (i >= saved_positions_num)
555 string const fname = saved_positions[i].filename;
557 cursor_.clearSelection();
559 if (fname != buffer_->fileName()) {
561 if (bufferlist.exists(fname))
562 b = bufferlist.getBuffer(fname);
564 b = bufferlist.newBuffer(fname);
565 // Don't ask, just load it
566 ::loadLyXFile(b, fname);
572 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
573 if (par == buffer_->par_iterator_end())
576 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
579 // emit message signal.
580 message(bformat(_("Moved to bookmark %1$d"), i));
584 bool BufferView::isSavedPosition(unsigned int i)
586 return i < saved_positions_num && !saved_positions[i].filename.empty();
589 void BufferView::saveSavedPositions()
591 // save bookmarks. It is better to use the pit interface
592 // but I do not know how to effectively convert between
594 for (unsigned int i=1; i < saved_positions_num; ++i) {
595 if ( isSavedPosition(i) )
596 LyX::ref().session().saveBookmark( boost::tie(
598 saved_positions[i].filename,
599 saved_positions[i].par_id,
600 saved_positions[i].par_pos) );
604 void BufferView::switchKeyMap()
606 if (!lyxrc.rtl_support)
609 Intl & intl = owner_->getIntl();
610 if (getLyXText()->real_current_font.isRightToLeft()) {
611 if (intl.keymap == Intl::PRIMARY)
614 if (intl.keymap == Intl::SECONDARY)
620 int BufferView::workWidth() const
626 void BufferView::center()
628 CursorSlice & bot = cursor_.bottom();
629 lyx::pit_type const pit = bot.pit();
630 bot.text()->redoParagraph(pit);
631 Paragraph const & par = bot.text()->paragraphs()[pit];
633 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
634 + par.ascent() - height_ / 2;
638 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
642 switch (cmd.action) {
645 flag.enabled(!buffer_->undostack().empty());
648 flag.enabled(!buffer_->redostack().empty());
650 case LFUN_FILE_INSERT:
651 case LFUN_FILE_INSERT_ASCII_PARA:
652 case LFUN_FILE_INSERT_ASCII:
653 case LFUN_BOOKMARK_SAVE:
654 // FIXME: Actually, these LFUNS should be moved to LyXText
655 flag.enabled(cursor_.inTexted());
657 case LFUN_FONT_STATE:
658 case LFUN_LABEL_INSERT:
659 case LFUN_PARAGRAPH_GOTO:
660 // FIXME handle non-trivially
661 case LFUN_OUTLINE_UP:
662 case LFUN_OUTLINE_DOWN:
663 case LFUN_OUTLINE_IN:
664 case LFUN_OUTLINE_OUT:
666 case LFUN_REFERENCE_NEXT:
668 case LFUN_WORD_REPLACE:
671 case LFUN_MARK_TOGGLE:
672 case LFUN_SCREEN_RECENTER:
673 case LFUN_BIBTEX_DATABASE_ADD:
674 case LFUN_BIBTEX_DATABASE_DEL:
675 case LFUN_WORDS_COUNT:
676 case LFUN_NEXT_INSET_TOGGLE:
680 case LFUN_LABEL_GOTO: {
681 flag.enabled(!cmd.argument().empty()
682 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
686 case LFUN_BOOKMARK_GOTO:
687 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
689 case LFUN_CHANGES_TRACK:
691 flag.setOnOff(buffer_->params().tracking_changes);
694 case LFUN_CHANGES_OUTPUT: {
695 OutputParams runparams;
696 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
697 flag.enabled(buffer_ && buffer_->params().tracking_changes
698 && features.isAvailable("dvipost"));
699 flag.setOnOff(buffer_->params().output_changes);
703 case LFUN_CHANGES_MERGE:
704 case LFUN_CHANGE_ACCEPT: // what about these two
705 case LFUN_CHANGE_REJECT: // what about these two
706 case LFUN_ALL_CHANGES_ACCEPT:
707 case LFUN_ALL_CHANGES_REJECT:
708 flag.enabled(buffer_ && buffer_->params().tracking_changes);
711 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
712 flag.setOnOff(buffer_->params().compressed);
724 bool BufferView::dispatch(FuncRequest const & cmd)
726 //lyxerr << BOOST_CURRENT_FUNCTION
727 // << [ cmd = " << cmd << "]" << endl;
729 // Make sure that the cached BufferView is correct.
730 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
731 << " action[" << cmd.action << ']'
732 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
733 << " x[" << cmd.x << ']'
734 << " y[" << cmd.y << ']'
735 << " button[" << cmd.button() << ']'
738 LCursor & cur = cursor_;
740 switch (cmd.action) {
744 cur.message(_("Undo"));
745 cur.clearSelection();
746 if (!textUndo(*this))
747 cur.message(_("No further undo information"));
755 cur.message(_("Redo"));
756 cur.clearSelection();
757 if (!textRedo(*this))
758 cur.message(_("No further redo information"));
764 case LFUN_FILE_INSERT:
765 // FIXME: We don't know the encoding of filenames
766 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
769 case LFUN_FILE_INSERT_ASCII_PARA:
770 // FIXME: We don't know the encoding of filenames
771 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
774 case LFUN_FILE_INSERT_ASCII:
775 // FIXME: We don't know the encoding of filenames
776 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
779 case LFUN_FONT_STATE:
780 cur.message(lyx::from_utf8(cur.currentState()));
783 case LFUN_BOOKMARK_SAVE:
784 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
787 case LFUN_BOOKMARK_GOTO:
788 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
791 case LFUN_LABEL_GOTO: {
792 string label = lyx::to_utf8(cmd.argument());
795 getInsetByCode<InsetRef>(cursor_,
796 InsetBase::REF_CODE);
798 label = inset->getContents();
808 case LFUN_PARAGRAPH_GOTO: {
809 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
810 ParIterator par = buffer_->getParFromID(id);
811 if (par == buffer_->par_iterator_end()) {
812 lyxerr[Debug::INFO] << "No matching paragraph found! ["
813 << id << ']' << endl;
816 lyxerr[Debug::INFO] << "Paragraph " << par->id()
817 << " found." << endl;
821 setCursor(makeDocIterator(par, 0));
828 case LFUN_OUTLINE_UP:
829 lyx::toc::outline(lyx::toc::Up, cursor_);
830 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
831 updateLabels(*buffer_);
833 case LFUN_OUTLINE_DOWN:
834 lyx::toc::outline(lyx::toc::Down, cursor_);
835 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
836 updateLabels(*buffer_);
838 case LFUN_OUTLINE_IN:
839 lyx::toc::outline(lyx::toc::In, cursor_);
840 updateLabels(*buffer_);
842 case LFUN_OUTLINE_OUT:
843 lyx::toc::outline(lyx::toc::Out, cursor_);
844 updateLabels(*buffer_);
848 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
851 case LFUN_REFERENCE_NEXT: {
852 vector<InsetBase_code> tmp;
853 tmp.push_back(InsetBase::LABEL_CODE);
854 tmp.push_back(InsetBase::REF_CODE);
855 bv_funcs::gotoInset(this, tmp, true);
859 case LFUN_CHANGES_TRACK:
863 case LFUN_CHANGES_OUTPUT: {
864 bool const state = buffer_->params().output_changes;
865 buffer_->params().output_changes = !state;
869 case LFUN_CHANGES_MERGE:
870 if (lyx::find::findNextChange(this))
871 owner_->getDialogs().show("changes");
874 case LFUN_ALL_CHANGES_ACCEPT: {
875 cursor_.reset(buffer_->inset());
877 #warning FIXME changes
879 while (lyx::find::findNextChange(this))
880 getLyXText()->acceptChange(cursor_);
885 case LFUN_ALL_CHANGES_REJECT: {
886 cursor_.reset(buffer_->inset());
888 #warning FIXME changes
890 while (lyx::find::findNextChange(this))
891 getLyXText()->rejectChange(cursor_);
896 lyx::find::find(this, cmd);
899 case LFUN_WORD_REPLACE:
900 lyx::find::replace(this, cmd);
904 cur.clearSelection();
906 cur.message(lyx::from_utf8(N_("Mark off")));
910 cur.clearSelection();
913 cur.message(lyx::from_utf8(N_("Mark on")));
916 case LFUN_MARK_TOGGLE:
917 cur.clearSelection();
920 cur.message(lyx::from_utf8(N_("Mark removed")));
923 cur.message(lyx::from_utf8(N_("Mark set")));
928 case LFUN_SCREEN_RECENTER:
932 case LFUN_BIBTEX_DATABASE_ADD: {
933 LCursor tmpcur = cursor_;
934 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
935 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
936 InsetBase::BIBTEX_CODE);
938 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
939 buffer_->updateBibfilesCache();
944 case LFUN_BIBTEX_DATABASE_DEL: {
945 LCursor tmpcur = cursor_;
946 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
947 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
948 InsetBase::BIBTEX_CODE);
950 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
951 buffer_->updateBibfilesCache();
956 case LFUN_WORDS_COUNT: {
957 DocIterator from, to;
958 if (cur.selection()) {
959 from = cur.selectionBegin();
960 to = cur.selectionEnd();
962 from = doc_iterator_begin(buffer_->inset());
963 to = doc_iterator_end(buffer_->inset());
965 int const count = countWords(from, to);
969 message = bformat(_("%1$d words in selection."),
972 message = bformat(_("%1$d words in document."),
977 message = _("One word in selection.");
979 message = _("One word in document.");
982 Alert::information(_("Count words"), message);
986 case LFUN_BUFFER_TOGGLE_COMPRESSION:
987 // turn compression on/off
988 buffer_->params().compressed = !buffer_->params().compressed;
991 case LFUN_NEXT_INSET_TOGGLE: {
992 // this is the real function we want to invoke
993 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
994 // if there is an inset at cursor, see whether it
996 InsetBase * inset = cur.nextInset();
997 if (inset && inset->isActive()) {
998 LCursor tmpcur = cur;
999 tmpcur.pushLeft(*inset);
1000 inset->dispatch(tmpcur, tmpcmd);
1001 if (tmpcur.result().dispatched()) {
1005 // if it did not work, try the underlying inset.
1006 if (!cur.result().dispatched())
1007 cur.dispatch(tmpcmd);
1009 if (cur.result().dispatched())
1010 cur.clearSelection();
1023 void BufferView::selectionRequested()
1025 static docstring sel;
1030 LCursor & cur = cursor_;
1032 if (!cur.selection()) {
1033 xsel_cache_.set = false;
1037 if (!xsel_cache_.set ||
1038 cur.top() != xsel_cache_.cursor ||
1039 cur.anchor_.top() != xsel_cache_.anchor)
1041 xsel_cache_.cursor = cur.top();
1042 xsel_cache_.anchor = cur.anchor_.top();
1043 xsel_cache_.set = cur.selection();
1044 sel = cur.selectionAsString(false);
1046 owner_->gui().selection().put(sel);
1051 void BufferView::selectionLost()
1054 cursor_.clearSelection();
1055 xsel_cache_.set = false;
1060 void BufferView::workAreaResize(int width, int height)
1062 bool const widthChange = width != width_;
1063 bool const heightChange = height != height_;
1065 // Update from work area
1069 if (buffer_ && widthChange) {
1070 // The WorkArea content needs a resize
1074 if (widthChange || heightChange)
1079 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1081 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1083 // This is only called for mouse related events including
1084 // LFUN_FILE_OPEN generated by drag-and-drop.
1085 FuncRequest cmd = cmd0;
1091 cur.push(buffer_->inset());
1092 cur.selection() = cursor_.selection();
1094 // Doesn't go through lyxfunc, so we need to update
1095 // the layout choice etc. ourselves
1097 // E.g. Qt mouse press when no buffer
1101 // Either the inset under the cursor or the
1102 // surrounding LyXText will handle this event.
1104 // Build temporary cursor.
1105 cmd.y = min(max(cmd.y, -1), height_);
1106 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1107 //lyxerr << BOOST_CURRENT_FUNCTION
1108 // << " * hit inset at tip: " << inset << endl;
1109 //lyxerr << BOOST_CURRENT_FUNCTION
1110 // << " * created temp cursor:" << cur << endl;
1112 // Put anchor at the same position.
1115 // Try to dispatch to an non-editable inset near this position
1116 // via the temp cursor. If the inset wishes to change the real
1117 // cursor it has to do so explicitly by using
1118 // cur.bv().cursor() = cur; (or similar)
1120 inset->dispatch(cur, cmd);
1122 // Now dispatch to the temporary cursor. If the real cursor should
1123 // be modified, the inset's dispatch has to do so explicitly.
1124 if (!cur.result().dispatched())
1127 if (cur.result().dispatched()) {
1128 // Redraw if requested or necessary.
1129 if (cur.result().update())
1130 update(Update::FitCursor | Update::Force);
1132 update(Update::FitCursor | Update::MultiParSel);
1139 void BufferView::scroll(int lines)
1144 // LyXText const * t = &buffer_->text();
1145 // int const line_height = defaultRowHeight();
1147 // // The new absolute coordinate
1148 // int new_top_y = top_y() + lines * line_height;
1150 // // Restrict to a valid value
1151 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1152 // new_top_y = std::max(0, new_top_y);
1154 // scrollDocView(new_top_y);
1156 // // Update the scrollbar.
1157 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1161 void BufferView::setCursorFromRow(int row)
1166 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1169 buffer_->text().setCursor(cursor_, 0, 0);
1171 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1175 void BufferView::gotoLabel(string const & label)
1177 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1178 vector<string> labels;
1179 it->getLabelList(*buffer_, labels);
1180 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1189 LyXText * BufferView::getLyXText()
1191 LyXText * text = cursor_.innerText();
1197 LyXText const * BufferView::getLyXText() const
1199 LyXText const * text = cursor_.innerText();
1205 int BufferView::workHeight() const
1211 void BufferView::setCursor(DocIterator const & dit)
1213 size_t const n = dit.depth();
1214 for (size_t i = 0; i < n; ++i)
1215 dit[i].inset().edit(cursor_, true);
1217 cursor_.setCursor(dit);
1218 cursor_.selection() = false;
1222 void BufferView::mouseSetCursor(LCursor & cur)
1224 BOOST_ASSERT(&cur.bv() == this);
1226 // Has the cursor just left the inset?
1227 bool badcursor = false;
1228 if (&cursor_.inset() != &cur.inset())
1229 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1231 // do the dEPM magic if needed
1232 // FIXME: move this to InsetText::notifyCursorLeaves?
1233 if (!badcursor && cursor_.inTexted())
1234 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1237 cursor_.clearSelection();
1238 cursor_.setTargetX();
1244 void BufferView::putSelectionAt(DocIterator const & cur,
1245 int length, bool backwards)
1247 cursor_.clearSelection();
1253 cursor_.pos() += length;
1254 cursor_.setSelection(cursor_, -length);
1256 cursor_.setSelection(cursor_, length);
1261 LCursor & BufferView::cursor()
1267 LCursor const & BufferView::cursor() const
1273 lyx::pit_type BufferView::anchor_ref() const
1279 int BufferView::offset_ref() const
1285 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1287 return metrics_info_;
1291 void BufferView::updateMetrics(bool singlepar)
1293 // Remove old position cache
1295 LyXText & buftext = buffer_->text();
1296 lyx::pit_type size = int(buftext.paragraphs().size());
1298 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1299 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1303 lyx::pit_type const pit = anchor_ref_;
1306 size_t const npit = buftext.paragraphs().size();
1308 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1309 // the (main text, not inset!) paragraph containing the cursor.
1310 // (if this paragraph contains insets etc., rebreaking will
1311 // recursively descend)
1312 if (!singlepar || pit == cursor_.bottom().pit())
1313 buftext.redoParagraph(pit);
1314 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1316 // Redo paragraphs above anchor if necessary; again, in Single Par
1317 // mode, only if we encounter the (main text) one having the cursor.
1319 while (y1 > 0 && pit1 > 0) {
1320 y1 -= buftext.getPar(pit1).ascent();
1322 if (!singlepar || pit1 == cursor_.bottom().pit())
1323 buftext.redoParagraph(pit1);
1324 y1 -= buftext.getPar(pit1).descent();
1328 // Take care of ascent of first line
1329 y1 -= buftext.getPar(pit1).ascent();
1331 // Normalize anchor for next time
1335 // Grey at the beginning is ugly
1336 if (pit1 == 0 && y1 > 0) {
1342 // Redo paragraphs below the anchor if necessary. Single par mode:
1343 // only the one containing the cursor if encountered.
1345 while (y2 < height_ && pit2 < int(npit) - 1) {
1346 y2 += buftext.getPar(pit2).descent();
1348 if (!singlepar || pit2 == cursor_.bottom().pit())
1349 buftext.redoParagraph(pit2);
1350 y2 += buftext.getPar(pit2).ascent();
1353 // Take care of descent of last line
1354 y2 += buftext.getPar(pit2).descent();
1356 // The coordinates of all these paragraphs are correct, cache them
1358 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1359 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1360 Paragraph const & par = buftext.getPar(pit);
1362 parPos[pit] = Point(0, y);
1363 if (singlepar && pit == cursor_.bottom().pit()) {
1364 // In Single Paragraph mode, collect here the
1365 // y1 and y2 of the (one) paragraph the cursor is in
1366 y1 = y - par.ascent();
1367 y2 = y + par.descent();
1373 // collect cursor paragraph iter bounds
1374 pit1 = cursor_.bottom().pit();
1375 pit2 = cursor_.bottom().pit();
1378 lyxerr[Debug::DEBUG]
1379 << BOOST_CURRENT_FUNCTION
1382 << " pit1: " << pit1
1383 << " pit2: " << pit2
1384 << " npit: " << npit
1385 << " singlepar: " << singlepar
1389 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1393 void BufferView::menuInsertLyXFile(string const & filenm)
1395 BOOST_ASSERT(cursor_.inTexted());
1396 string filename = filenm;
1398 if (filename.empty()) {
1399 // Launch a file browser
1400 string initpath = lyxrc.document_path;
1403 string const trypath = buffer_->filePath();
1404 // If directory is writeable, use this as default.
1405 if (isDirWriteable(trypath))
1409 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1411 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1412 string(lyxrc.document_path)),
1413 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1414 string(addPath(package().system_support(), "examples"))));
1416 FileDialog::Result result =
1417 fileDlg.open(initpath,
1418 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1421 if (result.first == FileDialog::Later)
1424 filename = result.second;
1426 // check selected filename
1427 if (filename.empty()) {
1428 // emit message signal.
1429 message(_("Canceled."));
1434 // Get absolute path of file and add ".lyx"
1435 // to the filename if necessary
1436 filename = fileSearch(string(), filename, "lyx");
1438 docstring const disp_fn = makeDisplayPath(filename);
1439 // emit message signal.
1440 message(bformat(_("Inserting document %1$s..."), disp_fn));
1443 Buffer buf("", false);
1444 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1445 ErrorList & el = buffer_->errorList("Parse");
1446 // Copy the inserted document error list into the current buffer one.
1447 el = buf.errorList("Parse");
1448 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1449 buf.params().textclass, el);
1450 res = _("Document %1$s inserted.");
1452 res = _("Could not insert document %1$s");
1454 // emit message signal.
1455 message(bformat(res, disp_fn));
1456 buffer_->errors("Parse");
1461 void BufferView::trackChanges()
1463 bool const tracking = buffer_->params().tracking_changes;
1466 for_each(buffer_->par_iterator_begin(),
1467 buffer_->par_iterator_end(),
1468 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1469 buffer_->params().tracking_changes = true;
1471 // We cannot allow undos beyond the freeze point
1472 buffer_->undostack().clear();
1474 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1475 if (lyx::find::findNextChange(this)) {
1476 owner_->getDialogs().show("changes");
1480 for_each(buffer_->par_iterator_begin(),
1481 buffer_->par_iterator_end(),
1482 mem_fun_ref(&Paragraph::untrackChanges));
1484 buffer_->params().tracking_changes = false;
1487 buffer_->redostack().clear();