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"
20 #include "DocIterator.h"
22 #include "ErrorList.h"
24 #include "FloatList.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
32 #include "lyxlayout_ptr_fwd.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
43 #include "TocBackend.h"
44 #include "VCBackend.h"
46 #include "frontends/alert.h"
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetInclude.h"
51 #include "support/filetools.h"
52 #include "support/fs_extras.h"
53 #include "support/lyxlib.h"
55 #include <boost/bind.hpp>
56 #include <boost/filesystem/operations.hpp>
66 using support::bformat;
67 using support::FileName;
68 using support::libFileSearch;
69 using support::makeAbsPath;
70 using support::makeDisplayPath;
71 using support::onlyFilename;
72 using support::onlyPath;
73 using support::unlink;
75 namespace Alert = frontend::Alert;
76 namespace fs = boost::filesystem;
80 bool readFile(Buffer * const b, FileName const & s)
84 // File information about normal file
85 if (!fs::exists(s.toFilesystemEncoding())) {
86 docstring const file = makeDisplayPath(s.absFilename(), 50);
87 docstring text = bformat(_("The specified document\n%1$s"
88 "\ncould not be read."), file);
89 Alert::error(_("Could not read document"), text);
93 // Check if emergency save file exists and is newer.
94 FileName const e(s.absFilename() + ".emergency");
96 if (fs::exists(e.toFilesystemEncoding()) &&
97 fs::exists(s.toFilesystemEncoding()) &&
98 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
100 docstring const file = makeDisplayPath(s.absFilename(), 20);
101 docstring const text =
102 bformat(_("An emergency save of the document "
104 "Recover emergency save?"), file);
105 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
106 _("&Recover"), _("&Load Original"),
110 // the file is not saved if we load the emergency file.
112 return b->readFile(e);
120 // Now check if autosave file is newer.
121 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
123 if (fs::exists(a.toFilesystemEncoding()) &&
124 fs::exists(s.toFilesystemEncoding()) &&
125 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
127 docstring const file = makeDisplayPath(s.absFilename(), 20);
128 docstring const text =
129 bformat(_("The backup of the document "
130 "%1$s is newer.\n\nLoad the "
131 "backup instead?"), file);
132 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
133 _("&Load backup"), _("Load &original"),
137 // the file is not saved if we load the autosave file.
139 return b->readFile(a);
141 // Here we delete the autosave
148 return b->readFile(s);
156 bool loadLyXFile(Buffer * b, FileName const & s)
160 if (fs::is_readable(s.toFilesystemEncoding())) {
161 if (readFile(b, s)) {
162 b->lyxvc().file_found_hook(s);
163 if (!fs::is_writable(s.toFilesystemEncoding()))
164 b->setReadonly(true);
168 docstring const file = makeDisplayPath(s.absFilename(), 20);
169 // Here we probably should run
170 if (LyXVC::file_not_found_hook(s)) {
171 docstring const text =
172 bformat(_("Do you want to retrieve the document"
173 " %1$s from version control?"), file);
174 int const ret = Alert::prompt(_("Retrieve from version control?"),
175 text, 0, 1, _("&Retrieve"), _("&Cancel"));
178 // How can we know _how_ to do the checkout?
179 // With the current VC support it has to be,
180 // a RCS file since CVS do not have special ,v files.
182 return loadLyXFile(b, s);
190 bool checkIfLoaded(FileName const & fn)
192 return theBufferList().getBuffer(fn.absFilename());
196 Buffer * checkAndLoadLyXFile(FileName const & filename)
198 // File already open?
199 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
201 if (checkBuffer->isClean())
203 docstring const file = makeDisplayPath(filename.absFilename(), 20);
204 docstring text = bformat(_(
205 "The document %1$s is already loaded and has unsaved changes.\n"
206 "Do you want to abandon your changes and reload the version on disk?"), file);
207 if (Alert::prompt(_("Reload saved document?"),
208 text, 0, 1, _("&Reload"), _("&Keep Changes")))
211 // FIXME: should be LFUN_REVERT
212 if (theBufferList().close(checkBuffer, false))
214 return checkAndLoadLyXFile(filename);
216 // The file could not be closed.
220 if (isFileReadable(filename)) {
221 Buffer * b = theBufferList().newBuffer(filename.absFilename());
222 if (!lyx::loadLyXFile(b, filename)) {
223 theBufferList().release(b);
229 docstring text = bformat(_("The document %1$s does not yet "
230 "exist.\n\nDo you want to create a new document?"),
231 from_utf8(filename.absFilename()));
232 if (!Alert::prompt(_("Create new document?"),
233 text, 0, 1, _("&Create"), _("Cancel")))
234 return newFile(filename.absFilename(), string(), true);
239 // FIXME newFile() should probably be a member method of Application...
240 Buffer * newFile(string const & filename, string const & templatename,
244 Buffer * b = theBufferList().newBuffer(filename);
248 // use defaults.lyx as a default template if it exists.
249 if (templatename.empty())
250 tname = libFileSearch("templates", "defaults.lyx");
252 tname = makeAbsPath(templatename);
254 if (!tname.empty()) {
255 if (!b->readFile(tname)) {
256 docstring const file = makeDisplayPath(tname.absFilename(), 50);
257 docstring const text = bformat(
258 _("The specified document template\n%1$s\ncould not be read."),
260 Alert::error(_("Could not read template"), text);
261 theBufferList().release(b);
268 b->setFileName(filename);
271 b->setReadonly(false);
272 b->fully_loaded(true);
278 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
279 ErrorList & errorList)
281 TeXErrors::Errors::const_iterator cit = terr.begin();
282 TeXErrors::Errors::const_iterator end = terr.end();
284 for (; cit != end; ++cit) {
287 int errorrow = cit->error_in_line;
288 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
294 found = buf.texrow().getIdFromRow(errorrow, id_end,
296 } while (found && id_start == id_end && pos_start == pos_end);
298 errorList.push_back(ErrorItem(cit->error_desc,
299 cit->error_text, id_start, pos_start, pos_end));
304 string const bufferFormat(Buffer const & buffer)
306 if (buffer.isDocBook())
308 else if (buffer.isLiterate())
315 int countWords(DocIterator const & from, DocIterator const & to)
319 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
320 // Copied and adapted from isLetter() in ControlSpellChecker
322 && dit.pos() != dit.lastpos()
323 && dit.paragraph().isLetter(dit.pos())
324 && !dit.paragraph().isDeleted(dit.pos())) {
339 depth_type getDepth(DocIterator const & it)
341 depth_type depth = 0;
342 for (size_t i = 0 ; i < it.depth() ; ++i)
343 if (!it[i].inset().inMathed())
344 depth += it[i].paragraph().getDepth() + 1;
345 // remove 1 since the outer inset does not count
349 depth_type getItemDepth(ParIterator const & it)
351 Paragraph const & par = *it;
352 LabelType const labeltype = par.layout()->labeltype;
354 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
357 // this will hold the lowest depth encountered up to now.
358 depth_type min_depth = getDepth(it);
359 ParIterator prev_it = it;
362 --prev_it.top().pit();
364 // start of nested inset: go to outer par
366 if (prev_it.empty()) {
367 // start of document: nothing to do
372 // We search for the first paragraph with same label
373 // that is not more deeply nested.
374 Paragraph & prev_par = *prev_it;
375 depth_type const prev_depth = getDepth(prev_it);
376 if (labeltype == prev_par.layout()->labeltype) {
377 if (prev_depth < min_depth) {
378 return prev_par.itemdepth + 1;
380 else if (prev_depth == min_depth) {
381 return prev_par.itemdepth;
384 min_depth = std::min(min_depth, prev_depth);
385 // small optimization: if we are at depth 0, we won't
386 // find anything else
387 if (prev_depth == 0) {
394 bool needEnumCounterReset(ParIterator const & it)
396 Paragraph const & par = *it;
397 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
398 depth_type const cur_depth = par.getDepth();
399 ParIterator prev_it = it;
400 while (prev_it.pit()) {
401 --prev_it.top().pit();
402 Paragraph const & prev_par = *prev_it;
403 if (prev_par.getDepth() <= cur_depth)
404 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
406 // start of nested inset: reset
411 // set the label of a paragraph. This includes the counters.
412 void setLabel(Buffer const & buf, ParIterator & it)
414 TextClass const & textclass = buf.params().getTextClass();
415 Paragraph & par = it.paragraph();
416 LayoutPtr const & layout = par.layout();
417 Counters & counters = textclass.counters();
419 if (par.params().startOfAppendix()) {
420 // FIXME: only the counter corresponding to toplevel
421 // sectionning should be reset
423 counters.appendix(true);
425 par.params().appendix(counters.appendix());
427 // Compute the item depth of the paragraph
428 par.itemdepth = getItemDepth(it);
430 if (layout->margintype == MARGIN_MANUAL) {
431 if (par.params().labelWidthString().empty())
432 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
434 par.params().labelWidthString(docstring());
437 switch(layout->labeltype) {
439 if (layout->toclevel <= buf.params().secnumdepth
440 && (layout->latextype != LATEX_ENVIRONMENT
441 || isFirstInSequence(it.pit(), it.plist()))) {
442 counters.step(layout->counter);
443 par.params().labelString(
444 par.expandLabel(layout, buf.params()));
446 par.params().labelString(docstring());
449 case LABEL_ITEMIZE: {
450 // At some point of time we should do something more
451 // clever here, like:
452 // par.params().labelString(
453 // buf.params().user_defined_bullet(par.itemdepth).getText());
454 // for now, use a simple hardcoded label
456 switch (par.itemdepth) {
458 itemlabel = char_type(0x2022);
461 itemlabel = char_type(0x2013);
464 itemlabel = char_type(0x2217);
467 itemlabel = char_type(0x2219); // or 0x00b7
470 par.params().labelString(itemlabel);
474 case LABEL_ENUMERATE: {
475 // FIXME: Yes I know this is a really, really! bad solution
477 docstring enumcounter = from_ascii("enum");
479 switch (par.itemdepth) {
491 // not a valid enumdepth...
495 // Maybe we have to reset the enumeration counter.
496 if (needEnumCounterReset(it))
497 counters.reset(enumcounter);
499 counters.step(enumcounter);
503 switch (par.itemdepth) {
505 format = N_("\\arabic{enumi}.");
508 format = N_("(\\alph{enumii})");
511 format = N_("\\roman{enumiii}.");
514 format = N_("\\Alph{enumiv}.");
517 // not a valid enumdepth...
521 par.params().labelString(counters.counterLabel(
522 par.translateIfPossible(from_ascii(format), buf.params())));
527 case LABEL_SENSITIVE: {
528 string const & type = counters.current_float();
529 docstring full_label;
531 full_label = buf.B_("Senseless!!! ");
533 docstring name = buf.B_(textclass.floats().getType(type).name());
534 if (counters.hasCounter(from_utf8(type))) {
535 counters.step(from_utf8(type));
536 full_label = bformat(from_ascii("%1$s %2$s:"),
538 counters.theCounter(from_utf8(type)));
540 full_label = bformat(from_ascii("%1$s #:"), name);
542 par.params().labelString(full_label);
547 par.params().labelString(docstring());
551 case LABEL_TOP_ENVIRONMENT:
552 case LABEL_CENTERED_TOP_ENVIRONMENT:
555 par.params().labelString(
556 par.translateIfPossible(layout->labelstring(),
564 void updateLabels(Buffer const & buf, ParIterator & parit)
566 BOOST_ASSERT(parit.pit() == 0);
568 depth_type maxdepth = 0;
569 pit_type const lastpit = parit.lastpit();
570 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
571 // reduce depth if necessary
572 parit->params().depth(min(parit->params().depth(), maxdepth));
573 maxdepth = parit->getMaxDepthAfter();
575 // set the counter for this paragraph
576 setLabel(buf, parit);
579 InsetList::const_iterator iit = parit->insetList().begin();
580 InsetList::const_iterator end = parit->insetList().end();
581 for (; iit != end; ++iit) {
582 parit.pos() = iit->pos;
583 iit->inset->updateLabels(buf, parit);
590 // FIXME: buf should should be const because updateLabels() modifies
591 // the contents of the paragraphs.
592 void updateLabels(Buffer const & buf, bool childonly)
594 Buffer const * const master = buf.getMasterBuffer();
595 // Use the master text class also for child documents
596 TextClass const & textclass = master->params().getTextClass();
599 // If this is a child document start with the master
600 if (master != &buf) {
601 updateLabels(*master);
605 // start over the counters
606 textclass.counters().reset();
609 Buffer & cbuf = const_cast<Buffer &>(buf);
611 if (buf.text().empty()) {
612 // FIXME: we don't call continue with updateLabels()
613 // here because it crashes on newly created documents.
614 // But the TocBackend needs to be initialised
615 // nonetheless so we update the tocBackend manually.
616 cbuf.tocBackend().update();
621 ParIterator parit = par_iterator_begin(buf.inset());
622 updateLabels(buf, parit);
624 cbuf.tocBackend().update();
626 cbuf.structureChanged();
628 // the embedding signal is emitted with structureChanged signal
629 // this is inaccurate so these two will be separated later.
630 //cbuf.embeddedFiles().update();
631 //cbuf.embeddingChanged();
635 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
637 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
638 Buffer * master = buffer.getMasterBuffer();
639 master->tocBackend().updateItem(par_it);
640 master->structureChanged();
644 textclass_type defaultTextclass()
646 // We want to return the article class. if `first' is
647 // true in the returned pair, then `second' is the textclass
648 // number; if it is false, second is 0. In both cases, second
650 return textclasslist.numberOfClass("article").second;
654 void loadChildDocuments(Buffer const & buf)
656 bool parse_error = false;
658 for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
659 if (it->lyxCode() != INCLUDE_CODE)
661 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
662 InsetCommandParams const & ip = inset.params();
663 Buffer * child = loadIfNeeded(buf, ip);
666 parse_error |= !child->errorList("Parse").empty();
667 loadChildDocuments(*child);
670 if (use_gui && buf.getMasterBuffer() == &buf)