2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
21 #include "ErrorList.h"
23 #include "FloatList.h"
27 #include "TextClass.h"
28 #include "Paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "ParIterator.h"
35 #include "TocBackend.h"
36 #include "VCBackend.h"
38 #include "frontends/alert.h"
40 #include "insets/InsetBibitem.h"
41 #include "insets/InsetCaption.h"
42 #include "insets/InsetInclude.h"
43 #include "insets/InsetTabular.h"
45 #include "support/filetools.h"
46 #include "support/fs_extras.h"
47 #include "support/lyxlib.h"
49 #include <boost/bind.hpp>
50 #include <boost/filesystem/operations.hpp>
60 using support::bformat;
61 using support::FileName;
62 using support::libFileSearch;
63 using support::makeAbsPath;
64 using support::makeDisplayPath;
65 using support::onlyFilename;
66 using support::onlyPath;
67 using support::unlink;
69 namespace Alert = frontend::Alert;
70 namespace fs = boost::filesystem;
74 bool readFile(Buffer * const b, FileName const & s)
78 // File information about normal file
79 if (!fs::exists(s.toFilesystemEncoding())) {
80 docstring const file = makeDisplayPath(s.absFilename(), 50);
81 docstring text = bformat(_("The specified document\n%1$s"
82 "\ncould not be read."), file);
83 Alert::error(_("Could not read document"), text);
87 // Check if emergency save file exists and is newer.
88 FileName const e(s.absFilename() + ".emergency");
90 if (fs::exists(e.toFilesystemEncoding()) &&
91 fs::exists(s.toFilesystemEncoding()) &&
92 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
94 docstring const file = makeDisplayPath(s.absFilename(), 20);
95 docstring const text =
96 bformat(_("An emergency save of the document "
98 "Recover emergency save?"), file);
99 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
100 _("&Recover"), _("&Load Original"),
104 // the file is not saved if we load the emergency file.
106 return b->readFile(e);
114 // Now check if autosave file is newer.
115 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
117 if (fs::exists(a.toFilesystemEncoding()) &&
118 fs::exists(s.toFilesystemEncoding()) &&
119 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
121 docstring const file = makeDisplayPath(s.absFilename(), 20);
122 docstring const text =
123 bformat(_("The backup of the document "
124 "%1$s is newer.\n\nLoad the "
125 "backup instead?"), file);
126 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
127 _("&Load backup"), _("Load &original"),
131 // the file is not saved if we load the autosave file.
133 return b->readFile(a);
135 // Here we delete the autosave
142 return b->readFile(s);
150 bool loadLyXFile(Buffer * b, FileName const & s)
154 if (fs::is_readable(s.toFilesystemEncoding())) {
155 if (readFile(b, s)) {
156 b->lyxvc().file_found_hook(s);
157 if (!fs::is_writable(s.toFilesystemEncoding()))
158 b->setReadonly(true);
162 docstring const file = makeDisplayPath(s.absFilename(), 20);
163 // Here we probably should run
164 if (LyXVC::file_not_found_hook(s)) {
165 docstring const text =
166 bformat(_("Do you want to retrieve the document"
167 " %1$s from version control?"), file);
168 int const ret = Alert::prompt(_("Retrieve from version control?"),
169 text, 0, 1, _("&Retrieve"), _("&Cancel"));
172 // How can we know _how_ to do the checkout?
173 // With the current VC support it has to be,
174 // a RCS file since CVS do not have special ,v files.
176 return loadLyXFile(b, s);
184 bool checkIfLoaded(FileName const & fn)
186 return theBufferList().getBuffer(fn.absFilename());
190 Buffer * checkAndLoadLyXFile(FileName const & filename)
192 // File already open?
193 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
195 if (checkBuffer->isClean())
197 docstring const file = makeDisplayPath(filename.absFilename(), 20);
198 docstring text = bformat(_(
199 "The document %1$s is already loaded and has unsaved changes.\n"
200 "Do you want to abandon your changes and reload the version on disk?"), file);
201 if (Alert::prompt(_("Reload saved document?"),
202 text, 0, 1, _("&Reload"), _("&Keep Changes")))
205 // FIXME: should be LFUN_REVERT
206 if (theBufferList().close(checkBuffer, false))
208 return checkAndLoadLyXFile(filename);
210 // The file could not be closed.
214 if (isFileReadable(filename)) {
215 Buffer * b = theBufferList().newBuffer(filename.absFilename());
216 if (!lyx::loadLyXFile(b, filename)) {
217 theBufferList().release(b);
223 docstring text = bformat(_("The document %1$s does not yet "
224 "exist.\n\nDo you want to create a new document?"),
225 from_utf8(filename.absFilename()));
226 if (!Alert::prompt(_("Create new document?"),
227 text, 0, 1, _("&Create"), _("Cancel")))
228 return newFile(filename.absFilename(), string(), true);
233 // FIXME newFile() should probably be a member method of Application...
234 Buffer * newFile(string const & filename, string const & templatename,
238 Buffer * b = theBufferList().newBuffer(filename);
242 // use defaults.lyx as a default template if it exists.
243 if (templatename.empty())
244 tname = libFileSearch("templates", "defaults.lyx");
246 tname = makeAbsPath(templatename);
248 if (!tname.empty()) {
249 if (!b->readFile(tname)) {
250 docstring const file = makeDisplayPath(tname.absFilename(), 50);
251 docstring const text = bformat(
252 _("The specified document template\n%1$s\ncould not be read."),
254 Alert::error(_("Could not read template"), text);
255 theBufferList().release(b);
262 b->setFileName(filename);
265 b->setReadonly(false);
266 b->fully_loaded(true);
272 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
273 ErrorList & errorList)
275 TeXErrors::Errors::const_iterator cit = terr.begin();
276 TeXErrors::Errors::const_iterator end = terr.end();
278 for (; cit != end; ++cit) {
281 int errorrow = cit->error_in_line;
282 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
288 found = buf.texrow().getIdFromRow(errorrow, id_end,
290 } while (found && id_start == id_end && pos_start == pos_end);
292 errorList.push_back(ErrorItem(cit->error_desc,
293 cit->error_text, id_start, pos_start, pos_end));
298 string const bufferFormat(Buffer const & buffer)
300 if (buffer.isDocBook())
302 else if (buffer.isLiterate())
309 int countWords(DocIterator const & from, DocIterator const & to)
313 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
314 // Copied and adapted from isLetter() in ControlSpellChecker
316 && dit.pos() != dit.lastpos()
317 && dit.paragraph().isLetter(dit.pos())
318 && !dit.paragraph().isDeleted(dit.pos())) {
333 depth_type getDepth(DocIterator const & it)
335 depth_type depth = 0;
336 for (size_t i = 0 ; i < it.depth() ; ++i)
337 if (!it[i].inset().inMathed())
338 depth += it[i].paragraph().getDepth() + 1;
339 // remove 1 since the outer inset does not count
343 depth_type getItemDepth(ParIterator const & it)
345 Paragraph const & par = *it;
346 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
348 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
351 // this will hold the lowest depth encountered up to now.
352 depth_type min_depth = getDepth(it);
353 ParIterator prev_it = it;
356 --prev_it.top().pit();
358 // start of nested inset: go to outer par
360 if (prev_it.empty()) {
361 // start of document: nothing to do
366 // We search for the first paragraph with same label
367 // that is not more deeply nested.
368 Paragraph & prev_par = *prev_it;
369 depth_type const prev_depth = getDepth(prev_it);
370 if (labeltype == prev_par.layout()->labeltype) {
371 if (prev_depth < min_depth) {
372 return prev_par.itemdepth + 1;
374 else if (prev_depth == min_depth) {
375 return prev_par.itemdepth;
378 min_depth = std::min(min_depth, prev_depth);
379 // small optimization: if we are at depth 0, we won't
380 // find anything else
381 if (prev_depth == 0) {
388 bool needEnumCounterReset(ParIterator const & it)
390 Paragraph const & par = *it;
391 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
392 depth_type const cur_depth = par.getDepth();
393 ParIterator prev_it = it;
394 while (prev_it.pit()) {
395 --prev_it.top().pit();
396 Paragraph const & prev_par = *prev_it;
397 if (prev_par.getDepth() <= cur_depth)
398 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
400 // start of nested inset: reset
405 void setCaptionLabels(Inset & inset, string const & type,
406 docstring const label, Counters & counters)
408 Text * text = inset.getText(0);
412 ParagraphList & pars = text->paragraphs();
416 docstring const counter = from_ascii(type);
418 ParagraphList::iterator p = pars.begin();
419 for (; p != pars.end(); ++p) {
420 InsetList::iterator it2 = p->insetlist.begin();
421 InsetList::iterator end2 = p->insetlist.end();
422 // Any caption within this float should have the same
423 // label prefix but different numbers.
424 for (; it2 != end2; ++it2) {
425 Inset & icap = *it2->inset;
426 // Look deeper just in case.
427 setCaptionLabels(icap, type, label, counters);
428 if (icap.lyxCode() == Inset::CAPTION_CODE) {
429 // We found a caption!
430 counters.step(counter);
431 int number = counters.value(counter);
432 InsetCaption & ic = static_cast<InsetCaption &>(icap);
435 ic.setCustomLabel(label);
442 void setCaptions(Paragraph & par, TextClass const & textclass)
444 if (par.insetlist.empty())
447 Counters & counters = textclass.counters();
449 InsetList::iterator it = par.insetlist.begin();
450 InsetList::iterator end = par.insetlist.end();
451 for (; it != end; ++it) {
452 Inset & inset = *it->inset;
453 if (inset.lyxCode() == Inset::FLOAT_CODE
454 || inset.lyxCode() == Inset::WRAP_CODE) {
455 docstring const name = inset.name();
459 Floating const & fl = textclass.floats().getType(to_ascii(name));
461 string const & type = fl.type();
462 docstring const label = from_utf8(fl.name());
463 setCaptionLabels(inset, type, label, counters);
465 else if (inset.lyxCode() == Inset::TABULAR_CODE
466 && static_cast<InsetTabular &>(inset).tabular.isLongTabular()) {
467 // FIXME: are "table" and "Table" the correct type and label?
468 setCaptionLabels(inset, "table", from_ascii("Table"), counters);
470 else if (inset.lyxCode() == Inset::LISTINGS_CODE)
471 setCaptionLabels(inset, "listing", from_ascii("Listing"), counters);
472 else if (inset.lyxCode() == Inset::INCLUDE_CODE)
473 // if this include inset contains lstinputlisting, and has a caption
474 // it will increase the 'listing' counter by one
475 static_cast<InsetInclude &>(inset).updateCounter(counters);
479 // set the label of a paragraph. This includes the counters.
480 void setLabel(Buffer const & buf, ParIterator & it, TextClass const & textclass)
482 Paragraph & par = *it;
483 Layout_ptr const & layout = par.layout();
484 Counters & counters = textclass.counters();
486 if (par.params().startOfAppendix()) {
487 // FIXME: only the counter corresponding to toplevel
488 // sectionning should be reset
490 counters.appendix(true);
492 par.params().appendix(counters.appendix());
494 // Compute the item depth of the paragraph
495 par.itemdepth = getItemDepth(it);
497 if (layout->margintype == MARGIN_MANUAL) {
498 if (par.params().labelWidthString().empty())
499 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
501 par.params().labelWidthString(docstring());
504 // Optimisation: setLabel() can be called for each for each
505 // paragraph of the document. So we make the string static to
506 // avoid the repeated instanciation.
507 static docstring itemlabel;
509 // is it a layout that has an automatic label?
510 if (layout->labeltype == LABEL_COUNTER) {
511 if (layout->toclevel <= buf.params().secnumdepth
512 && (layout->latextype != LATEX_ENVIRONMENT
513 || isFirstInSequence(it.pit(), it.plist()))) {
514 counters.step(layout->counter);
515 par.params().labelString(
516 par.expandLabel(layout, buf.params()));
518 par.params().labelString(docstring());
520 } else if (layout->labeltype == LABEL_ITEMIZE) {
521 // At some point of time we should do something more
522 // clever here, like:
523 // par.params().labelString(
524 // buf.params().user_defined_bullet(par.itemdepth).getText());
525 // for now, use a simple hardcoded label
526 switch (par.itemdepth) {
528 itemlabel = char_type(0x2022);
531 itemlabel = char_type(0x2013);
534 itemlabel = char_type(0x2217);
537 itemlabel = char_type(0x2219); // or 0x00b7
540 par.params().labelString(itemlabel);
542 } else if (layout->labeltype == LABEL_ENUMERATE) {
544 // Yes I know this is a really, really! bad solution
546 docstring enumcounter = from_ascii("enum");
548 switch (par.itemdepth) {
560 // not a valid enumdepth...
564 // Maybe we have to reset the enumeration counter.
565 if (needEnumCounterReset(it))
566 counters.reset(enumcounter);
568 counters.step(enumcounter);
572 switch (par.itemdepth) {
574 format = N_("\\arabic{enumi}.");
577 format = N_("(\\alph{enumii})");
580 format = N_("\\roman{enumiii}.");
583 format = N_("\\Alph{enumiv}.");
586 // not a valid enumdepth...
590 par.params().labelString(counters.counterLabel(
591 par.translateIfPossible(from_ascii(format), buf.params())));
593 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
594 counters.step(from_ascii("bibitem"));
595 int number = counters.value(from_ascii("bibitem"));
597 par.bibitem()->setCounter(number);
599 par.params().labelString(
600 par.translateIfPossible(layout->labelstring(), buf.params()));
601 // In biblio shouldn't be following counters but...
602 } else if (layout->labeltype == LABEL_SENSITIVE) {
603 // Search for the first float or wrap inset in the iterator
604 size_t i = it.depth();
608 Inset::Code const code = it[i].inset().lyxCode();
609 if (code == Inset::FLOAT_CODE ||
610 code == Inset::WRAP_CODE) {
615 // FIXME Can Inset::name() return an empty name for wide or
616 // float insets? If not we can put the definition of type
617 // inside the if (in) clause and use that instead of
618 // if (!type.empty()).
624 Floating const & fl = textclass.floats().getType(to_ascii(type));
626 counters.step(from_ascii(fl.type()));
628 // Doesn't work... yet.
629 par.params().labelString(par.translateIfPossible(
630 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
633 // par->SetLayout(0);
634 par.params().labelString(par.translateIfPossible(
635 layout->labelstring(), buf.params()));
638 } else if (layout->labeltype == LABEL_NO_LABEL)
639 par.params().labelString(docstring());
641 par.params().labelString(
642 par.translateIfPossible(layout->labelstring(), buf.params()));
648 void updateLabels(Buffer const & buf, bool childonly)
650 Buffer const * const master = buf.getMasterBuffer();
651 // Use the master text class also for child documents
652 TextClass const & textclass = master->params().getTextClass();
655 // If this is a child document start with the master
656 if (master != &buf) {
657 updateLabels(*master);
661 // start over the counters
662 textclass.counters().reset();
665 ParIterator const end = par_iterator_end(buf.inset());
667 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
668 // reduce depth if necessary
670 Paragraph const & prevpar = it.plist()[it.pit() - 1];
671 it->params().depth(min(it->params().depth(),
672 prevpar.getMaxDepthAfter()));
674 it->params().depth(0);
676 // set the counter for this paragraph
677 setLabel(buf, it, textclass);
679 // It is better to set the captions after setLabel because
680 // the caption number might need the section number in the
682 setCaptions(*it, textclass);
685 InsetList::const_iterator iit = it->insetlist.begin();
686 InsetList::const_iterator end = it->insetlist.end();
687 for (; iit != end; ++iit) {
688 if (iit->inset->lyxCode() == Inset::INCLUDE_CODE)
689 static_cast<InsetInclude const *>(iit->inset)
694 Buffer & cbuf = const_cast<Buffer &>(buf);
695 cbuf.tocBackend().update();
697 cbuf.structureChanged();
701 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
703 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
704 Buffer * master = buffer.getMasterBuffer();
705 master->tocBackend().updateItem(par_it);
706 master->structureChanged();