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 Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "DispatchResult.h"
29 #include "DocIterator.h"
31 #include "ErrorList.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "IndicesList.h"
37 #include "InsetIterator.h"
38 #include "InsetList.h"
40 #include "LaTeXFeatures.h"
44 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
119 using namespace lyx::support;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
145 // A storehouse for the cloned buffers.
146 list<CloneList *> cloned_buffers;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
156 delete preview_loader_;
164 /// search for macro in local (buffer) table or in children
165 MacroData const * getBufferMacro(docstring const & name,
166 DocIterator const & pos) const;
168 /// Update macro table starting with position of it \param it in some
170 void updateMacros(DocIterator & it, DocIterator & scope);
172 void setLabel(ParIterator & it, UpdateType utype) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this an unnamed file (New...)?
198 /// is this an internal bufffer?
199 bool internal_buffer;
204 /// name of the file the buffer is associated with.
207 /** Set to true only when the file is fully loaded.
208 * Used to prevent the premature generation of previews
209 * and by the citation inset.
211 bool file_fully_loaded;
213 /// Ignore the parent (e.g. when exporting a child standalone)?
217 mutable TocBackend toc_backend;
220 typedef pair<DocIterator, MacroData> ScopeMacro;
221 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
222 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
223 /// map from the macro name to the position map,
224 /// which maps the macro definition position to the scope and the MacroData.
225 NamePositionScopeMacroMap macros;
226 /// This seem to change the way Buffer::getMacro() works
227 mutable bool macro_lock;
229 /// positions of child buffers in the buffer
230 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
231 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
232 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
233 /// position of children buffers in this buffer
234 BufferPositionMap children_positions;
235 /// map from children inclusion positions to their scope and their buffer
236 PositionScopeBufferMap position_to_children;
238 /// Container for all sort of Buffer dependant errors.
239 map<string, ErrorList> errorLists;
241 /// timestamp and checksum used to test if the file has been externally
242 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
244 unsigned long checksum_;
247 frontend::WorkAreaManager * wa_;
249 frontend::GuiBufferDelegate * gui_;
254 /// A cache for the bibfiles (including bibfiles of loaded child
255 /// documents), needed for appropriate update of natbib labels.
256 mutable support::FileNameList bibfiles_cache_;
258 // FIXME The caching mechanism could be improved. At present, we have a
259 // cache for each Buffer, that caches all the bibliography info for that
260 // Buffer. A more efficient solution would be to have a global cache per
261 // file, and then to construct the Buffer's bibinfo from that.
262 /// A cache for bibliography info
263 mutable BiblioInfo bibinfo_;
264 /// whether the bibinfo cache is valid
265 mutable bool bibinfo_cache_valid_;
266 /// whether the bibfile cache is valid
267 mutable bool bibfile_cache_valid_;
268 /// Cache of timestamps of .bib files
269 map<FileName, time_t> bibfile_status_;
270 /// Indicates whether the bibinfo has changed since the last time
271 /// we ran updateBuffer(), i.e., whether citation labels may need
273 mutable bool cite_labels_valid_;
275 mutable RefCache ref_cache_;
277 /// our Text that should be wrapped in an InsetText
281 PreviewLoader * preview_loader_;
283 /// This is here to force the test to be done whenever parent_buffer
285 Buffer const * parent() const
287 // ignore_parent temporarily "orphans" a buffer
288 // (e.g. if a child is compiled standalone)
291 // if parent_buffer is not loaded, then it has been unloaded,
292 // which means that parent_buffer is an invalid pointer. So we
293 // set it to null in that case.
294 // however, the BufferList doesn't know about cloned buffers, so
295 // they will always be regarded as unloaded. in that case, we hope
297 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
299 return parent_buffer;
303 void setParent(Buffer const * pb)
305 if (parent_buffer == pb)
308 if (!cloned_buffer_ && parent_buffer && pb)
309 LYXERR0("Warning: a buffer should not have two parents!");
311 if (!cloned_buffer_ && parent_buffer) {
312 parent_buffer->invalidateBibfileCache();
313 parent_buffer->invalidateBibinfoCache();
317 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
318 /// This one is useful for preview detached in a thread.
319 Buffer const * cloned_buffer_;
321 CloneList * clone_list_;
322 /// are we in the process of exporting this buffer?
323 mutable bool doing_export;
325 /// compute statistics
326 /// \p from initial position
327 /// \p to points to the end position
328 void updateStatistics(DocIterator & from, DocIterator & to,
329 bool skipNoOutput = true);
330 /// statistics accessor functions
331 int wordCount() const
335 int charCount(bool with_blanks) const
338 + (with_blanks ? blank_count_ : 0);
342 /// So we can force access via the accessors.
343 mutable Buffer const * parent_buffer;
352 /// Creates the per buffer temporary directory
353 static FileName createBufferTmpDir()
356 // We are in our own directory. Why bother to mangle name?
357 // In fact I wrote this code to circumvent a problematic behaviour
358 // (bug?) of EMX mkstemp().
359 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
360 convert<string>(count++));
362 if (!tmpfl.createDirectory(0777)) {
363 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
364 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
365 from_utf8(tmpfl.absFileName())));
371 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
372 Buffer const * cloned_buffer)
373 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
374 internal_buffer(false), read_only(readonly_), filename(file),
375 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
376 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
377 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
378 cite_labels_valid_(false), preview_loader_(0),
379 cloned_buffer_(cloned_buffer), clone_list_(0),
380 doing_export(false), parent_buffer(0)
382 if (!cloned_buffer_) {
383 temppath = createBufferTmpDir();
384 lyxvc.setBuffer(owner_);
386 wa_ = new frontend::WorkAreaManager;
389 temppath = cloned_buffer_->d->temppath;
390 file_fully_loaded = true;
391 params = cloned_buffer_->d->params;
392 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
393 bibinfo_ = cloned_buffer_->d->bibinfo_;
394 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
395 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
396 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
397 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
398 unnamed = cloned_buffer_->d->unnamed;
399 internal_buffer = cloned_buffer_->d->internal_buffer;
403 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
404 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
406 LYXERR(Debug::INFO, "Buffer::Buffer()");
408 d->inset = new InsetText(*cloned_buffer->d->inset);
409 d->inset->setBuffer(*this);
410 // FIXME: optimize this loop somewhat, maybe by creating a new
411 // general recursive Inset::setId().
412 DocIterator it = doc_iterator_begin(this);
413 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
414 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
415 it.paragraph().setId(cloned_it.paragraph().id());
417 d->inset = new InsetText(this);
418 d->inset->setAutoBreakRows(true);
419 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
425 LYXERR(Debug::INFO, "Buffer::~Buffer()");
426 // here the buffer should take care that it is
427 // saved properly, before it goes into the void.
429 // GuiView already destroyed
433 // No need to do additional cleanups for internal buffer.
439 // this is in case of recursive includes: we won't try to delete
440 // ourselves as a child.
441 d->clone_list_->erase(this);
442 // loop over children
443 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
444 Impl::BufferPositionMap::iterator end = d->children_positions.end();
445 for (; it != end; ++it) {
446 Buffer * child = const_cast<Buffer *>(it->first);
447 if (d->clone_list_->erase(child))
450 // if we're the master buffer, then we should get rid of the list
453 // if this is not empty, we have leaked something. worse, one of the
454 // children still has a reference to this list.
455 LASSERT(d->clone_list_->empty(), /* */);
456 list<CloneList *>::iterator it =
457 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
458 LASSERT(it != cloned_buffers.end(), /* */);
459 cloned_buffers.erase(it);
460 delete d->clone_list_;
462 // FIXME Do we really need to do this right before we delete d?
463 // clear references to children in macro tables
464 d->children_positions.clear();
465 d->position_to_children.clear();
467 // loop over children
468 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
469 Impl::BufferPositionMap::iterator end = d->children_positions.end();
470 for (; it != end; ++it) {
471 Buffer * child = const_cast<Buffer *>(it->first);
472 if (theBufferList().isLoaded(child))
473 theBufferList().releaseChild(this, child);
477 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
478 msg += emergencyWrite();
479 Alert::warning(_("Attempting to close changed document!"), msg);
482 // FIXME Do we really need to do this right before we delete d?
483 // clear references to children in macro tables
484 d->children_positions.clear();
485 d->position_to_children.clear();
487 if (!d->temppath.destroyDirectory()) {
488 Alert::warning(_("Could not remove temporary directory"),
489 bformat(_("Could not remove the temporary directory %1$s"),
490 from_utf8(d->temppath.absFileName())));
499 Buffer * Buffer::cloneFromMaster() const
502 cloned_buffers.push_back(new CloneList);
503 CloneList * clones = cloned_buffers.back();
505 masterBuffer()->cloneWithChildren(bufmap, clones);
507 // make sure we got cloned
508 BufferMap::const_iterator bit = bufmap.find(this);
509 LASSERT(bit != bufmap.end(), return 0);
510 Buffer * cloned_buffer = bit->second;
512 return cloned_buffer;
516 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
518 // have we already been cloned?
519 if (bufmap.find(this) != bufmap.end())
522 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
523 bufmap[this] = buffer_clone;
524 clones->insert(buffer_clone);
525 buffer_clone->d->clone_list_ = clones;
526 buffer_clone->d->macro_lock = true;
527 buffer_clone->d->children_positions.clear();
528 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
529 // math macro caches need to be rethought and simplified.
530 // I am not sure wether we should handle Buffer cloning here or in BufferList.
531 // Right now BufferList knows nothing about buffer clones.
532 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
533 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
534 for (; it != end; ++it) {
535 DocIterator dit = it->first.clone(buffer_clone);
536 dit.setBuffer(buffer_clone);
537 Buffer * child = const_cast<Buffer *>(it->second.second);
539 child->cloneWithChildren(bufmap, clones);
540 BufferMap::iterator const bit = bufmap.find(child);
541 LASSERT(bit != bufmap.end(), continue);
542 Buffer * child_clone = bit->second;
544 Inset * inset = dit.nextInset();
545 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
546 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
547 inset_inc->setChildBuffer(child_clone);
548 child_clone->d->setParent(buffer_clone);
549 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
550 buffer_clone->setChild(dit, child_clone);
552 buffer_clone->d->macro_lock = false;
557 Buffer * Buffer::cloneBufferOnly() const {
558 cloned_buffers.push_back(new CloneList);
559 CloneList * clones = cloned_buffers.back();
560 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
561 clones->insert(buffer_clone);
562 buffer_clone->d->clone_list_ = clones;
563 // we won't be cloning the children
564 buffer_clone->d->children_positions.clear();
569 bool Buffer::isClone() const
571 return d->cloned_buffer_;
575 void Buffer::changed(bool update_metrics) const
578 d->wa_->redrawAll(update_metrics);
582 frontend::WorkAreaManager & Buffer::workAreaManager() const
584 LASSERT(d->wa_, /**/);
589 Text & Buffer::text() const
591 return d->inset->text();
595 Inset & Buffer::inset() const
601 BufferParams & Buffer::params()
607 BufferParams const & Buffer::params() const
613 ParagraphList & Buffer::paragraphs()
615 return text().paragraphs();
619 ParagraphList const & Buffer::paragraphs() const
621 return text().paragraphs();
625 LyXVC & Buffer::lyxvc()
631 LyXVC const & Buffer::lyxvc() const
637 string const Buffer::temppath() const
639 return d->temppath.absFileName();
643 TexRow & Buffer::texrow()
649 TexRow const & Buffer::texrow() const
655 TocBackend & Buffer::tocBackend() const
657 return d->toc_backend;
661 Undo & Buffer::undo()
667 void Buffer::setChild(DocIterator const & dit, Buffer * child)
669 d->children_positions[child] = dit;
673 string Buffer::latexName(bool const no_path) const
675 FileName latex_name =
676 makeLatexName(d->exportFileName());
677 return no_path ? latex_name.onlyFileName()
678 : latex_name.absFileName();
682 FileName Buffer::Impl::exportFileName() const
684 docstring const branch_suffix =
685 params.branchlist().getFileNameSuffix();
686 if (branch_suffix.empty())
689 string const name = filename.onlyFileNameWithoutExt()
690 + to_utf8(branch_suffix);
691 FileName res(filename.onlyPath().absFileName() + "/" + name);
692 res.changeExtension(filename.extension());
698 string Buffer::logName(LogType * type) const
700 string const filename = latexName(false);
702 if (filename.empty()) {
708 string const path = temppath();
710 FileName const fname(addName(temppath(),
711 onlyFileName(changeExtension(filename,
714 // FIXME: how do we know this is the name of the build log?
715 FileName const bname(
716 addName(path, onlyFileName(
717 changeExtension(filename,
718 formats.extension(params().bufferFormat()) + ".out"))));
720 // Also consider the master buffer log file
721 FileName masterfname = fname;
723 if (masterBuffer() != this) {
724 string const mlogfile = masterBuffer()->logName(&mtype);
725 masterfname = FileName(mlogfile);
728 // If no Latex log or Build log is newer, show Build log
729 if (bname.exists() &&
730 ((!fname.exists() && !masterfname.exists())
731 || (fname.lastModified() < bname.lastModified()
732 && masterfname.lastModified() < bname.lastModified()))) {
733 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
736 return bname.absFileName();
737 // If we have a newer master file log or only a master log, show this
738 } else if (fname != masterfname
739 && (!fname.exists() && (masterfname.exists()
740 || fname.lastModified() < masterfname.lastModified()))) {
741 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
744 return masterfname.absFileName();
746 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
749 return fname.absFileName();
753 void Buffer::setReadonly(bool const flag)
755 if (d->read_only != flag) {
762 void Buffer::setFileName(FileName const & fname)
764 bool const changed = fname != d->filename;
767 lyxvc().file_found_hook(fname);
768 setReadonly(d->filename.isReadOnly());
774 int Buffer::readHeader(Lexer & lex)
776 int unknown_tokens = 0;
778 int begin_header_line = -1;
780 // Initialize parameters that may be/go lacking in header:
781 params().branchlist().clear();
782 params().preamble.erase();
783 params().options.erase();
784 params().master.erase();
785 params().float_placement.erase();
786 params().paperwidth.erase();
787 params().paperheight.erase();
788 params().leftmargin.erase();
789 params().rightmargin.erase();
790 params().topmargin.erase();
791 params().bottommargin.erase();
792 params().headheight.erase();
793 params().headsep.erase();
794 params().footskip.erase();
795 params().columnsep.erase();
796 params().fonts_cjk.erase();
797 params().listings_params.clear();
798 params().clearLayoutModules();
799 params().clearRemovedModules();
800 params().clearIncludedChildren();
801 params().pdfoptions().clear();
802 params().indiceslist().clear();
803 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
804 params().isbackgroundcolor = false;
805 params().fontcolor = RGBColor(0, 0, 0);
806 params().isfontcolor = false;
807 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
808 params().boxbgcolor = RGBColor(0xFF, 0, 0);
809 params().html_latex_start.clear();
810 params().html_latex_end.clear();
811 params().html_math_img_scale = 1.0;
812 params().output_sync_macro.erase();
813 params().local_layout.clear();
815 for (int i = 0; i < 4; ++i) {
816 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
817 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
820 ErrorList & errorList = d->errorLists["Parse"];
829 if (token == "\\end_header")
833 if (token == "\\begin_header") {
834 begin_header_line = line;
838 LYXERR(Debug::PARSER, "Handling document header token: `"
841 string unknown = params().readToken(lex, token, d->filename.onlyPath());
842 if (!unknown.empty()) {
843 if (unknown[0] != '\\' && token == "\\textclass") {
844 Alert::warning(_("Unknown document class"),
845 bformat(_("Using the default document class, because the "
846 "class %1$s is unknown."), from_utf8(unknown)));
849 docstring const s = bformat(_("Unknown token: "
853 errorList.push_back(ErrorItem(_("Document header error"),
858 if (begin_header_line) {
859 docstring const s = _("\\begin_header is missing");
860 errorList.push_back(ErrorItem(_("Document header error"),
864 params().makeDocumentClass();
866 return unknown_tokens;
871 // changed to be public and have one parameter
872 // Returns true if "\end_document" is not read (Asger)
873 bool Buffer::readDocument(Lexer & lex)
875 ErrorList & errorList = d->errorLists["Parse"];
878 // remove dummy empty par
879 paragraphs().clear();
881 if (!lex.checkFor("\\begin_document")) {
882 docstring const s = _("\\begin_document is missing");
883 errorList.push_back(ErrorItem(_("Document header error"),
889 if (params().outputChanges) {
890 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
891 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
892 LaTeXFeatures::isAvailable("xcolor");
894 if (!dvipost && !xcolorulem) {
895 Alert::warning(_("Changes not shown in LaTeX output"),
896 _("Changes will not be highlighted in LaTeX output, "
897 "because neither dvipost nor xcolor/ulem are installed.\n"
898 "Please install these packages or redefine "
899 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
900 } else if (!xcolorulem) {
901 Alert::warning(_("Changes not shown in LaTeX output"),
902 _("Changes will not be highlighted in LaTeX output "
903 "when using pdflatex, because xcolor and ulem are not installed.\n"
904 "Please install both packages or redefine "
905 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
909 if (!params().master.empty()) {
910 FileName const master_file = makeAbsPath(params().master,
911 onlyPath(absFileName()));
912 if (isLyXFileName(master_file.absFileName())) {
914 checkAndLoadLyXFile(master_file, true);
916 // necessary e.g. after a reload
917 // to re-register the child (bug 5873)
918 // FIXME: clean up updateMacros (here, only
919 // child registering is needed).
920 master->updateMacros();
921 // set master as master buffer, but only
922 // if we are a real child
923 if (master->isChild(this))
925 // if the master is not fully loaded
926 // it is probably just loading this
927 // child. No warning needed then.
928 else if (master->isFullyLoaded())
929 LYXERR0("The master '"
931 << "' assigned to this document ("
933 << ") does not include "
934 "this document. Ignoring the master assignment.");
939 // assure we have a default index
940 params().indiceslist().addDefault(B_("Index"));
943 bool const res = text().read(lex, errorList, d->inset);
945 // inform parent buffer about local macros
947 Buffer const * pbuf = parent();
948 UserMacroSet::const_iterator cit = usermacros.begin();
949 UserMacroSet::const_iterator end = usermacros.end();
950 for (; cit != end; ++cit)
951 pbuf->usermacros.insert(*cit);
955 updateMacroInstances(InternalUpdate);
960 bool Buffer::readString(string const & s)
962 params().compressed = false;
967 FileName const fn = FileName::tempName("Buffer_readString");
970 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
971 if (ret_plf != ReadSuccess)
974 if (file_format != LYX_FORMAT) {
975 // We need to call lyx2lyx, so write the input to a file
976 ofstream os(fn.toFilesystemEncoding().c_str());
980 return readFile(fn) == ReadSuccess;
983 if (readDocument(lex))
989 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
993 if (!lex.setFile(fname)) {
994 Alert::error(_("File Not Found"),
995 bformat(_("Unable to open file `%1$s'."),
996 from_utf8(fn.absFileName())));
997 return ReadFileNotFound;
1001 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1002 if (ret_plf != ReadSuccess)
1005 if (file_format != LYX_FORMAT) {
1007 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1008 if (ret_clf != ReadSuccess)
1010 return readFile(tmpFile);
1013 // FIXME: InsetInfo needs to know whether the file is under VCS
1014 // during the parse process, so this has to be done before.
1015 lyxvc().file_found_hook(d->filename);
1017 if (readDocument(lex)) {
1018 Alert::error(_("Document format failure"),
1019 bformat(_("%1$s ended unexpectedly, which means"
1020 " that it is probably corrupted."),
1021 from_utf8(fn.absFileName())));
1022 return ReadDocumentFailure;
1025 d->file_fully_loaded = true;
1026 d->read_only = !d->filename.isWritable();
1027 params().compressed = formats.isZippedFile(d->filename);
1033 bool Buffer::isFullyLoaded() const
1035 return d->file_fully_loaded;
1039 void Buffer::setFullyLoaded(bool value)
1041 d->file_fully_loaded = value;
1045 PreviewLoader * Buffer::loader() const
1047 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1049 if (!d->preview_loader_)
1050 d->preview_loader_ = new PreviewLoader(*this);
1051 return d->preview_loader_;
1055 void Buffer::removePreviews() const
1057 delete d->preview_loader_;
1058 d->preview_loader_ = 0;
1062 void Buffer::updatePreviews() const
1064 PreviewLoader * ploader = loader();
1068 InsetIterator it = inset_iterator_begin(*d->inset);
1069 InsetIterator const end = inset_iterator_end(*d->inset);
1070 for (; it != end; ++it)
1071 it->addPreview(it, *ploader);
1073 ploader->startLoading();
1077 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1078 FileName const & fn, int & file_format) const
1080 if(!lex.checkFor("\\lyxformat")) {
1081 Alert::error(_("Document format failure"),
1082 bformat(_("%1$s is not a readable LyX document."),
1083 from_utf8(fn.absFileName())));
1084 return ReadNoLyXFormat;
1090 // LyX formats 217 and earlier were written as 2.17. This corresponds
1091 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1092 // these cases. See also: www.lyx.org/trac/changeset/1313.
1093 size_t dot = tmp_format.find_first_of(".,");
1094 if (dot != string::npos)
1095 tmp_format.erase(dot, 1);
1097 file_format = convert<int>(tmp_format);
1102 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1103 FileName & tmpfile, int from_format)
1105 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1106 if(tmpfile.empty()) {
1107 Alert::error(_("Conversion failed"),
1108 bformat(_("%1$s is from a different"
1109 " version of LyX, but a temporary"
1110 " file for converting it could"
1111 " not be created."),
1112 from_utf8(fn.absFileName())));
1113 return LyX2LyXNoTempFile;
1116 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1117 if (lyx2lyx.empty()) {
1118 Alert::error(_("Conversion script not found"),
1119 bformat(_("%1$s is from a different"
1120 " version of LyX, but the"
1121 " conversion script lyx2lyx"
1122 " could not be found."),
1123 from_utf8(fn.absFileName())));
1124 return LyX2LyXNotFound;
1128 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1129 ostringstream command;
1130 command << os::python()
1131 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1132 << " -t " << convert<string>(LYX_FORMAT)
1133 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1134 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1135 string const command_str = command.str();
1137 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1139 cmd_ret const ret = runCommand(command_str);
1140 if (ret.first != 0) {
1141 if (from_format < LYX_FORMAT) {
1142 Alert::error(_("Conversion script failed"),
1143 bformat(_("%1$s is from an older version"
1144 " of LyX and the lyx2lyx script"
1145 " failed to convert it."),
1146 from_utf8(fn.absFileName())));
1147 return LyX2LyXOlderFormat;
1149 Alert::error(_("Conversion script failed"),
1150 bformat(_("%1$s is from a newer version"
1151 " of LyX and the lyx2lyx script"
1152 " failed to convert it."),
1153 from_utf8(fn.absFileName())));
1154 return LyX2LyXNewerFormat;
1161 // Should probably be moved to somewhere else: BufferView? GuiView?
1162 bool Buffer::save() const
1164 docstring const file = makeDisplayPath(absFileName(), 20);
1165 d->filename.refresh();
1167 // check the read-only status before moving the file as a backup
1168 if (d->filename.exists()) {
1169 bool const read_only = !d->filename.isWritable();
1171 Alert::warning(_("File is read-only"),
1172 bformat(_("The file %1$s cannot be written because it "
1173 "is marked as read-only."), file));
1178 // ask if the disk file has been externally modified (use checksum method)
1179 if (fileName().exists() && isExternallyModified(checksum_method)) {
1181 bformat(_("Document %1$s has been externally modified. "
1182 "Are you sure you want to overwrite this file?"), file);
1183 int const ret = Alert::prompt(_("Overwrite modified file?"),
1184 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1189 // We don't need autosaves in the immediate future. (Asger)
1190 resetAutosaveTimers();
1192 FileName backupName;
1193 bool madeBackup = false;
1195 // make a backup if the file already exists
1196 if (lyxrc.make_backup && fileName().exists()) {
1197 backupName = FileName(absFileName() + '~');
1198 if (!lyxrc.backupdir_path.empty()) {
1199 string const mangledName =
1200 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1201 backupName = FileName(addName(lyxrc.backupdir_path,
1205 // Except file is symlink do not copy because of #6587.
1206 // Hard links have bad luck.
1207 if (fileName().isSymLink())
1208 madeBackup = fileName().copyTo(backupName);
1210 madeBackup = fileName().moveTo(backupName);
1213 Alert::error(_("Backup failure"),
1214 bformat(_("Cannot create backup file %1$s.\n"
1215 "Please check whether the directory exists and is writable."),
1216 from_utf8(backupName.absFileName())));
1217 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1221 if (writeFile(d->filename)) {
1225 // Saving failed, so backup is not backup
1227 backupName.moveTo(d->filename);
1233 bool Buffer::writeFile(FileName const & fname) const
1235 // FIXME Do we need to do these here? I don't think writing
1236 // the LyX file depends upon it. (RGH)
1238 // updateMacroInstances();
1240 if (d->read_only && fname == d->filename)
1243 bool retval = false;
1245 docstring const str = bformat(_("Saving document %1$s..."),
1246 makeDisplayPath(fname.absFileName()));
1249 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1251 if (params().compressed) {
1252 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1253 retval = ofs && write(ofs);
1255 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1256 retval = ofs && write(ofs);
1260 message(str + _(" could not write file!"));
1265 // removeAutosaveFile();
1268 message(str + _(" done."));
1274 docstring Buffer::emergencyWrite()
1276 // No need to save if the buffer has not changed.
1280 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1282 docstring user_message = bformat(
1283 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1285 // We try to save three places:
1286 // 1) Same place as document. Unless it is an unnamed doc.
1288 string s = absFileName();
1291 if (writeFile(FileName(s))) {
1293 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1294 return user_message;
1296 user_message += " " + _("Save failed! Trying again...\n");
1300 // 2) In HOME directory.
1301 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1303 lyxerr << ' ' << s << endl;
1304 if (writeFile(FileName(s))) {
1306 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1307 return user_message;
1310 user_message += " " + _("Save failed! Trying yet again...\n");
1312 // 3) In "/tmp" directory.
1313 // MakeAbsPath to prepend the current
1314 // drive letter on OS/2
1315 s = addName(package().temp_dir().absFileName(), absFileName());
1317 lyxerr << ' ' << s << endl;
1318 if (writeFile(FileName(s))) {
1320 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1321 return user_message;
1324 user_message += " " + _("Save failed! Bummer. Document is lost.");
1327 return user_message;
1331 bool Buffer::write(ostream & ofs) const
1334 // Use the standard "C" locale for file output.
1335 ofs.imbue(locale::classic());
1338 // The top of the file should not be written by params().
1340 // write out a comment in the top of the file
1341 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1342 << " created this file. For more info see http://www.lyx.org/\n"
1343 << "\\lyxformat " << LYX_FORMAT << "\n"
1344 << "\\begin_document\n";
1346 /// For each author, set 'used' to true if there is a change
1347 /// by this author in the document; otherwise set it to 'false'.
1348 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1349 AuthorList::Authors::const_iterator a_end = params().authors().end();
1350 for (; a_it != a_end; ++a_it)
1351 a_it->setUsed(false);
1353 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1354 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1355 for ( ; it != end; ++it)
1356 it->checkAuthors(params().authors());
1358 // now write out the buffer parameters.
1359 ofs << "\\begin_header\n";
1360 params().writeFile(ofs);
1361 ofs << "\\end_header\n";
1364 ofs << "\n\\begin_body\n";
1366 ofs << "\n\\end_body\n";
1368 // Write marker that shows file is complete
1369 ofs << "\\end_document" << endl;
1371 // Shouldn't really be needed....
1374 // how to check if close went ok?
1375 // Following is an attempt... (BE 20001011)
1377 // good() returns false if any error occured, including some
1378 // formatting error.
1379 // bad() returns true if something bad happened in the buffer,
1380 // which should include file system full errors.
1385 lyxerr << "File was not closed properly." << endl;
1392 bool Buffer::makeLaTeXFile(FileName const & fname,
1393 string const & original_path,
1394 OutputParams const & runparams_in,
1395 OutputWhat output) const
1397 OutputParams runparams = runparams_in;
1399 // This is necessary for LuaTeX/XeTeX with tex fonts.
1400 // See FIXME in BufferParams::encoding()
1401 if (runparams.isFullUnicode())
1402 runparams.encoding = encodings.fromLyXName("utf8-plain");
1404 string const encoding = runparams.encoding->iconvName();
1405 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1408 try { ofs.reset(encoding); }
1409 catch (iconv_codecvt_facet_exception const & e) {
1410 lyxerr << "Caught iconv exception: " << e.what() << endl;
1411 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1412 "verify that the support software for your encoding (%1$s) is "
1413 "properly installed"), from_ascii(encoding)));
1416 if (!openFileWrite(ofs, fname))
1419 //TexStream ts(ofs.rdbuf(), &texrow());
1420 ErrorList & errorList = d->errorLists["Export"];
1422 bool failed_export = false;
1423 otexstream os(ofs, d->texrow);
1425 // make sure we are ready to export
1426 // this needs to be done before we validate
1427 // FIXME Do we need to do this all the time? I.e., in children
1428 // of a master we are exporting?
1430 updateMacroInstances(OutputUpdate);
1433 os.texrow().reset();
1434 writeLaTeXSource(os, original_path, runparams, output);
1436 catch (EncodingException const & e) {
1437 odocstringstream ods;
1438 ods.put(e.failed_char);
1440 oss << "0x" << hex << e.failed_char << dec;
1441 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1442 " (code point %2$s)"),
1443 ods.str(), from_utf8(oss.str()));
1444 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1445 "representable in the chosen encoding.\n"
1446 "Changing the document encoding to utf8 could help."),
1447 e.par_id, e.pos, e.pos + 1));
1448 failed_export = true;
1450 catch (iconv_codecvt_facet_exception const & e) {
1451 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1452 _(e.what()), -1, 0, 0));
1453 failed_export = true;
1455 catch (exception const & e) {
1456 errorList.push_back(ErrorItem(_("conversion failed"),
1457 _(e.what()), -1, 0, 0));
1458 failed_export = true;
1461 lyxerr << "Caught some really weird exception..." << endl;
1467 failed_export = true;
1468 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1472 return !failed_export;
1476 void Buffer::writeLaTeXSource(otexstream & os,
1477 string const & original_path,
1478 OutputParams const & runparams_in,
1479 OutputWhat output) const
1481 // The child documents, if any, shall be already loaded at this point.
1483 OutputParams runparams = runparams_in;
1485 // If we are compiling a file standalone, even if this is the
1486 // child of some other buffer, let's cut the link here, so the
1487 // file is really independent and no concurring settings from
1488 // the master (e.g. branch state) interfere (see #8100).
1489 if (!runparams.is_child)
1490 d->ignore_parent = true;
1492 // Classify the unicode characters appearing in math insets
1493 Encodings::initUnicodeMath(*this);
1495 // validate the buffer.
1496 LYXERR(Debug::LATEX, " Validating buffer...");
1497 LaTeXFeatures features(*this, params(), runparams);
1499 runparams.use_polyglossia = features.usePolyglossia();
1500 LYXERR(Debug::LATEX, " Buffer validation done.");
1502 bool const output_preamble =
1503 output == FullSource || output == OnlyPreamble;
1504 bool const output_body =
1505 output == FullSource || output == OnlyBody;
1507 // The starting paragraph of the coming rows is the
1508 // first paragraph of the document. (Asger)
1509 if (output_preamble && runparams.nice) {
1510 os << "%% LyX " << lyx_version << " created this file. "
1511 "For more info, see http://www.lyx.org/.\n"
1512 "%% Do not edit unless you really know what "
1515 LYXERR(Debug::INFO, "lyx document header finished");
1517 // There are a few differences between nice LaTeX and usual files:
1518 // usual files have \batchmode and special input@path to allow
1519 // inclusion of figures specified by an explicitly relative path
1520 // (i.e., a path starting with './' or '../') with either \input or
1521 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1522 // input@path is set when the actual parameter original_path is set.
1523 // This is done for usual tex-file, but not for nice-latex-file.
1524 // (Matthias 250696)
1525 // Note that input@path is only needed for something the user does
1526 // in the preamble, included .tex files or ERT, files included by
1527 // LyX work without it.
1528 if (output_preamble) {
1529 if (!runparams.nice) {
1530 // code for usual, NOT nice-latex-file
1531 os << "\\batchmode\n"; // changed from \nonstopmode
1533 if (!original_path.empty()) {
1535 // We don't know the encoding of inputpath
1536 docstring const inputpath = from_utf8(original_path);
1537 docstring uncodable_glyphs;
1538 Encoding const * const enc = runparams.encoding;
1540 for (size_t n = 0; n < inputpath.size(); ++n) {
1541 if (!enc->encodable(inputpath[n])) {
1542 docstring const glyph(1, inputpath[n]);
1543 LYXERR0("Uncodable character '"
1545 << "' in input path!");
1546 uncodable_glyphs += glyph;
1551 // warn user if we found uncodable glyphs.
1552 if (!uncodable_glyphs.empty()) {
1553 frontend::Alert::warning(
1554 _("Uncodable character in file path"),
1556 _("The path of your document\n"
1558 "contains glyphs that are unknown "
1559 "in the current document encoding "
1560 "(namely %2$s). This may result in "
1561 "incomplete output, unless "
1562 "TEXINPUTS contains the document "
1563 "directory and you don't use "
1564 "explicitly relative paths (i.e., "
1565 "paths starting with './' or "
1566 "'../') in the preamble or in ERT."
1567 "\n\nIn case of problems, choose "
1568 "an appropriate document encoding\n"
1569 "(such as utf8) or change the "
1571 inputpath, uncodable_glyphs));
1574 support::latex_path(original_path);
1575 if (contains(docdir, '#')) {
1576 docdir = subst(docdir, "#", "\\#");
1577 os << "\\catcode`\\#=11"
1578 "\\def\\#{#}\\catcode`\\#=6\n";
1580 if (contains(docdir, '%')) {
1581 docdir = subst(docdir, "%", "\\%");
1582 os << "\\catcode`\\%=11"
1583 "\\def\\%{%}\\catcode`\\%=14\n";
1585 os << "\\makeatletter\n"
1586 << "\\def\\input@path{{"
1587 << docdir << "/}}\n"
1588 << "\\makeatother\n";
1592 // get parent macros (if this buffer has a parent) which will be
1593 // written at the document begin further down.
1594 MacroSet parentMacros;
1595 listParentMacros(parentMacros, features);
1597 // Write the preamble
1598 runparams.use_babel = params().writeLaTeX(os, features,
1599 d->filename.onlyPath());
1601 runparams.use_japanese = features.isRequired("japanese");
1604 // Restore the parenthood if needed
1605 if (!runparams.is_child)
1606 d->ignore_parent = false;
1611 os << "\\begin{document}\n";
1613 // output the parent macros
1614 MacroSet::iterator it = parentMacros.begin();
1615 MacroSet::iterator end = parentMacros.end();
1616 for (; it != end; ++it) {
1617 int num_lines = (*it)->write(os.os(), true);
1618 os.texrow().newlines(num_lines);
1621 } // output_preamble
1623 os.texrow().start(paragraphs().begin()->id(), 0);
1625 LYXERR(Debug::INFO, "preamble finished, now the body.");
1628 latexParagraphs(*this, text(), os, runparams);
1630 // Restore the parenthood if needed
1631 if (!runparams.is_child)
1632 d->ignore_parent = false;
1634 // add this just in case after all the paragraphs
1637 if (output_preamble) {
1638 os << "\\end{document}\n";
1639 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1641 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1643 runparams_in.encoding = runparams.encoding;
1645 // Just to be sure. (Asger)
1646 os.texrow().newline();
1648 //for (int i = 0; i<d->texrow.rows(); i++) {
1650 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1651 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1654 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1655 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1659 void Buffer::makeDocBookFile(FileName const & fname,
1660 OutputParams const & runparams,
1661 OutputWhat output) const
1663 LYXERR(Debug::LATEX, "makeDocBookFile...");
1666 if (!openFileWrite(ofs, fname))
1669 // make sure we are ready to export
1670 // this needs to be done before we validate
1672 updateMacroInstances(OutputUpdate);
1674 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1678 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1682 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1683 OutputParams const & runparams,
1684 OutputWhat output) const
1686 LaTeXFeatures features(*this, params(), runparams);
1691 DocumentClass const & tclass = params().documentClass();
1692 string const top_element = tclass.latexname();
1694 bool const output_preamble =
1695 output == FullSource || output == OnlyPreamble;
1696 bool const output_body =
1697 output == FullSource || output == OnlyBody;
1699 if (output_preamble) {
1700 if (runparams.flavor == OutputParams::XML)
1701 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1704 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1707 if (! tclass.class_header().empty())
1708 os << from_ascii(tclass.class_header());
1709 else if (runparams.flavor == OutputParams::XML)
1710 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1711 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1713 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1715 docstring preamble = from_utf8(params().preamble);
1716 if (runparams.flavor != OutputParams::XML ) {
1717 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1718 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1719 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1720 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1723 string const name = runparams.nice
1724 ? changeExtension(absFileName(), ".sgml") : fname;
1725 preamble += features.getIncludedFiles(name);
1726 preamble += features.getLyXSGMLEntities();
1728 if (!preamble.empty()) {
1729 os << "\n [ " << preamble << " ]";
1735 string top = top_element;
1737 if (runparams.flavor == OutputParams::XML)
1738 top += params().language->code();
1740 top += params().language->code().substr(0, 2);
1743 if (!params().options.empty()) {
1745 top += params().options;
1748 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1749 << " file was created by LyX " << lyx_version
1750 << "\n See http://www.lyx.org/ for more information -->\n";
1752 params().documentClass().counters().reset();
1754 sgml::openTag(os, top);
1756 docbookParagraphs(text(), *this, os, runparams);
1757 sgml::closeTag(os, top_element);
1762 void Buffer::makeLyXHTMLFile(FileName const & fname,
1763 OutputParams const & runparams) const
1765 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1768 if (!openFileWrite(ofs, fname))
1771 // make sure we are ready to export
1772 // this has to be done before we validate
1773 updateBuffer(UpdateMaster, OutputUpdate);
1774 updateMacroInstances(OutputUpdate);
1776 writeLyXHTMLSource(ofs, runparams, FullSource);
1780 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1784 void Buffer::writeLyXHTMLSource(odocstream & os,
1785 OutputParams const & runparams,
1786 OutputWhat output) const
1788 LaTeXFeatures features(*this, params(), runparams);
1790 d->bibinfo_.makeCitationLabels(*this);
1792 bool const output_preamble =
1793 output == FullSource || output == OnlyPreamble;
1794 bool const output_body =
1795 output == FullSource || output == OnlyBody || output == IncludedFile;
1797 if (output_preamble) {
1798 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1799 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1800 // FIXME Language should be set properly.
1801 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1803 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1804 // FIXME Presumably need to set this right
1805 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1807 docstring const & doctitle = features.htmlTitle();
1809 << (doctitle.empty() ?
1810 from_ascii("LyX Document") :
1811 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1814 docstring styles = features.getTClassHTMLPreamble();
1815 if (!styles.empty())
1816 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1818 styles = from_utf8(features.getPreambleSnippets());
1819 if (!styles.empty())
1820 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1822 // we will collect CSS information in a stream, and then output it
1823 // either here, as part of the header, or else in a separate file.
1824 odocstringstream css;
1825 styles = from_utf8(features.getCSSSnippets());
1826 if (!styles.empty())
1827 css << "/* LyX Provided Styles */\n" << styles << '\n';
1829 styles = features.getTClassHTMLStyles();
1830 if (!styles.empty())
1831 css << "/* Layout-provided Styles */\n" << styles << '\n';
1833 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1834 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1835 if (needfg || needbg) {
1836 css << "\nbody {\n";
1839 << from_ascii(X11hexname(params().fontcolor))
1842 css << " background-color: "
1843 << from_ascii(X11hexname(params().backgroundcolor))
1848 docstring const dstyles = css.str();
1849 if (!dstyles.empty()) {
1850 bool written = false;
1851 if (params().html_css_as_file) {
1852 // open a file for CSS info
1854 string const fcssname = addName(temppath(), "docstyle.css");
1855 FileName const fcssfile = FileName(fcssname);
1856 if (openFileWrite(ocss, fcssfile)) {
1860 // write link to header
1861 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1863 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1866 // we are here if the CSS is supposed to be written to the header
1867 // or if we failed to write it to an external file.
1869 os << "<style type='text/css'>\n"
1878 bool const output_body_tag = (output != IncludedFile);
1879 if (output_body_tag)
1882 params().documentClass().counters().reset();
1883 xhtmlParagraphs(text(), *this, xs, runparams);
1884 if (output_body_tag)
1888 if (output_preamble)
1893 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1894 // Other flags: -wall -v0 -x
1895 int Buffer::runChktex()
1899 // get LaTeX-Filename
1900 FileName const path(temppath());
1901 string const name = addName(path.absFileName(), latexName());
1902 string const org_path = filePath();
1904 PathChanger p(path); // path to LaTeX file
1905 message(_("Running chktex..."));
1907 // Generate the LaTeX file if neccessary
1908 OutputParams runparams(¶ms().encoding());
1909 runparams.flavor = OutputParams::LATEX;
1910 runparams.nice = false;
1911 runparams.linelen = lyxrc.plaintext_linelen;
1912 makeLaTeXFile(FileName(name), org_path, runparams);
1915 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1916 int const res = chktex.run(terr); // run chktex
1919 Alert::error(_("chktex failure"),
1920 _("Could not run chktex successfully."));
1921 } else if (res > 0) {
1922 ErrorList & errlist = d->errorLists["ChkTeX"];
1924 bufferErrors(terr, errlist);
1935 void Buffer::validate(LaTeXFeatures & features) const
1937 // Validate the buffer params, but not for included
1938 // files, since they also use the parent buffer's
1940 if (!features.runparams().is_child)
1941 params().validate(features);
1943 for_each(paragraphs().begin(), paragraphs().end(),
1944 bind(&Paragraph::validate, _1, ref(features)));
1946 if (lyxerr.debugging(Debug::LATEX)) {
1947 features.showStruct();
1952 void Buffer::getLabelList(vector<docstring> & list) const
1954 // If this is a child document, use the master's list instead.
1956 masterBuffer()->getLabelList(list);
1961 Toc & toc = d->toc_backend.toc("label");
1962 TocIterator toc_it = toc.begin();
1963 TocIterator end = toc.end();
1964 for (; toc_it != end; ++toc_it) {
1965 if (toc_it->depth() == 0)
1966 list.push_back(toc_it->str());
1971 void Buffer::updateBibfilesCache(UpdateScope scope) const
1973 // FIXME This is probably unnecssary, given where we call this.
1974 // If this is a child document, use the parent's cache instead.
1975 if (parent() && scope != UpdateChildOnly) {
1976 masterBuffer()->updateBibfilesCache();
1980 d->bibfiles_cache_.clear();
1981 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1982 if (it->lyxCode() == BIBTEX_CODE) {
1983 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1984 support::FileNameList const bibfiles = inset.getBibFiles();
1985 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1988 } else if (it->lyxCode() == INCLUDE_CODE) {
1989 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1990 Buffer const * const incbuf = inset.getChildBuffer();
1993 support::FileNameList const & bibfiles =
1994 incbuf->getBibfilesCache(UpdateChildOnly);
1995 if (!bibfiles.empty()) {
1996 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2002 d->bibfile_cache_valid_ = true;
2003 d->bibinfo_cache_valid_ = false;
2004 d->cite_labels_valid_ = false;
2008 void Buffer::invalidateBibinfoCache() const
2010 d->bibinfo_cache_valid_ = false;
2011 d->cite_labels_valid_ = false;
2012 // also invalidate the cache for the parent buffer
2013 Buffer const * const pbuf = d->parent();
2015 pbuf->invalidateBibinfoCache();
2019 void Buffer::invalidateBibfileCache() const
2021 d->bibfile_cache_valid_ = false;
2022 d->bibinfo_cache_valid_ = false;
2023 d->cite_labels_valid_ = false;
2024 // also invalidate the cache for the parent buffer
2025 Buffer const * const pbuf = d->parent();
2027 pbuf->invalidateBibfileCache();
2031 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2033 // FIXME This is probably unnecessary, given where we call this.
2034 // If this is a child document, use the master's cache instead.
2035 Buffer const * const pbuf = masterBuffer();
2036 if (pbuf != this && scope != UpdateChildOnly)
2037 return pbuf->getBibfilesCache();
2039 if (!d->bibfile_cache_valid_)
2040 this->updateBibfilesCache(scope);
2042 return d->bibfiles_cache_;
2046 BiblioInfo const & Buffer::masterBibInfo() const
2048 Buffer const * const tmp = masterBuffer();
2050 return tmp->masterBibInfo();
2055 void Buffer::checkIfBibInfoCacheIsValid() const
2057 // use the master's cache
2058 Buffer const * const tmp = masterBuffer();
2060 tmp->checkIfBibInfoCacheIsValid();
2064 // compare the cached timestamps with the actual ones.
2065 FileNameList const & bibfiles_cache = getBibfilesCache();
2066 FileNameList::const_iterator ei = bibfiles_cache.begin();
2067 FileNameList::const_iterator en = bibfiles_cache.end();
2068 for (; ei != en; ++ ei) {
2069 time_t lastw = ei->lastModified();
2070 time_t prevw = d->bibfile_status_[*ei];
2071 if (lastw != prevw) {
2072 d->bibinfo_cache_valid_ = false;
2073 d->cite_labels_valid_ = false;
2074 d->bibfile_status_[*ei] = lastw;
2080 void Buffer::reloadBibInfoCache() const
2082 // use the master's cache
2083 Buffer const * const tmp = masterBuffer();
2085 tmp->reloadBibInfoCache();
2089 checkIfBibInfoCacheIsValid();
2090 if (d->bibinfo_cache_valid_)
2093 d->bibinfo_.clear();
2095 d->bibinfo_cache_valid_ = true;
2099 void Buffer::collectBibKeys() const
2101 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2102 it->collectBibKeys(it);
2106 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2108 Buffer const * tmp = masterBuffer();
2109 BiblioInfo & masterbi = (tmp == this) ?
2110 d->bibinfo_ : tmp->d->bibinfo_;
2111 masterbi.mergeBiblioInfo(bi);
2115 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2117 Buffer const * tmp = masterBuffer();
2118 BiblioInfo & masterbi = (tmp == this) ?
2119 d->bibinfo_ : tmp->d->bibinfo_;
2124 bool Buffer::citeLabelsValid() const
2126 return masterBuffer()->d->cite_labels_valid_;
2130 void Buffer::removeBiblioTempFiles() const
2132 // We remove files that contain LaTeX commands specific to the
2133 // particular bibliographic style being used, in order to avoid
2134 // LaTeX errors when we switch style.
2135 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2136 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2137 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2138 aux_file.removeFile();
2139 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2140 bbl_file.removeFile();
2141 // Also for the parent buffer
2142 Buffer const * const pbuf = parent();
2144 pbuf->removeBiblioTempFiles();
2148 bool Buffer::isDepClean(string const & name) const
2150 DepClean::const_iterator const it = d->dep_clean.find(name);
2151 if (it == d->dep_clean.end())
2157 void Buffer::markDepClean(string const & name)
2159 d->dep_clean[name] = true;
2163 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2166 // FIXME? if there is an Buffer LFUN that can be dispatched even
2167 // if internal, put a switch '(cmd.action)' here.
2173 switch (cmd.action()) {
2175 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2176 flag.setOnOff(isReadonly());
2179 // FIXME: There is need for a command-line import.
2180 //case LFUN_BUFFER_IMPORT:
2182 case LFUN_BUFFER_AUTO_SAVE:
2185 case LFUN_BUFFER_EXPORT_CUSTOM:
2186 // FIXME: Nothing to check here?
2189 case LFUN_BUFFER_EXPORT: {
2190 docstring const arg = cmd.argument();
2191 if (arg == "custom") {
2195 string format = to_utf8(arg);
2196 size_t pos = format.find(' ');
2197 if (pos != string::npos)
2198 format = format.substr(0, pos);
2199 enable = params().isExportable(format);
2201 flag.message(bformat(
2202 _("Don't know how to export to format: %1$s"), arg));
2206 case LFUN_BUFFER_CHKTEX:
2207 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2210 case LFUN_BUILD_PROGRAM:
2211 enable = params().isExportable("program");
2214 case LFUN_BRANCH_ADD:
2215 case LFUN_BRANCHES_RENAME:
2216 case LFUN_BUFFER_PRINT:
2217 // if no Buffer is present, then of course we won't be called!
2220 case LFUN_BUFFER_LANGUAGE:
2221 enable = !isReadonly();
2227 flag.setEnabled(enable);
2232 void Buffer::dispatch(string const & command, DispatchResult & result)
2234 return dispatch(lyxaction.lookupFunc(command), result);
2238 // NOTE We can end up here even if we have no GUI, because we are called
2239 // by LyX::exec to handled command-line requests. So we may need to check
2240 // whether we have a GUI or not. The boolean use_gui holds this information.
2241 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2244 // FIXME? if there is an Buffer LFUN that can be dispatched even
2245 // if internal, put a switch '(cmd.action())' here.
2246 dr.dispatched(false);
2249 string const argument = to_utf8(func.argument());
2250 // We'll set this back to false if need be.
2251 bool dispatched = true;
2252 undo().beginUndoGroup();
2254 switch (func.action()) {
2255 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2256 if (lyxvc().inUse()) {
2257 string log = lyxvc().toggleReadOnly();
2262 setReadonly(!isReadonly());
2265 case LFUN_BUFFER_EXPORT: {
2266 ExportStatus const status = doExport(argument, false);
2267 dr.setError(status != ExportSuccess);
2268 if (status != ExportSuccess)
2269 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2274 case LFUN_BUILD_PROGRAM:
2275 doExport("program", true);
2278 case LFUN_BUFFER_CHKTEX:
2282 case LFUN_BUFFER_EXPORT_CUSTOM: {
2284 string command = split(argument, format_name, ' ');
2285 Format const * format = formats.getFormat(format_name);
2287 lyxerr << "Format \"" << format_name
2288 << "\" not recognized!"
2293 // The name of the file created by the conversion process
2296 // Output to filename
2297 if (format->name() == "lyx") {
2298 string const latexname = latexName(false);
2299 filename = changeExtension(latexname,
2300 format->extension());
2301 filename = addName(temppath(), filename);
2303 if (!writeFile(FileName(filename)))
2307 doExport(format_name, true, filename);
2310 // Substitute $$FName for filename
2311 if (!contains(command, "$$FName"))
2312 command = "( " + command + " ) < $$FName";
2313 command = subst(command, "$$FName", filename);
2315 // Execute the command in the background
2317 call.startscript(Systemcall::DontWait, command, filePath());
2321 // FIXME: There is need for a command-line import.
2323 case LFUN_BUFFER_IMPORT:
2328 case LFUN_BUFFER_AUTO_SAVE:
2330 resetAutosaveTimers();
2333 case LFUN_BRANCH_ADD: {
2334 docstring branch_name = func.argument();
2335 if (branch_name.empty()) {
2339 BranchList & branch_list = params().branchlist();
2340 vector<docstring> const branches =
2341 getVectorFromString(branch_name, branch_list.separator());
2343 for (vector<docstring>::const_iterator it = branches.begin();
2344 it != branches.end(); ++it) {
2346 Branch * branch = branch_list.find(branch_name);
2348 LYXERR0("Branch " << branch_name << " already exists.");
2352 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2354 branch_list.add(branch_name);
2355 branch = branch_list.find(branch_name);
2356 string const x11hexname = X11hexname(branch->color());
2357 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2358 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2360 dr.screenUpdate(Update::Force);
2368 case LFUN_BRANCHES_RENAME: {
2369 if (func.argument().empty())
2372 docstring const oldname = from_utf8(func.getArg(0));
2373 docstring const newname = from_utf8(func.getArg(1));
2374 InsetIterator it = inset_iterator_begin(inset());
2375 InsetIterator const end = inset_iterator_end(inset());
2376 bool success = false;
2377 for (; it != end; ++it) {
2378 if (it->lyxCode() == BRANCH_CODE) {
2379 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2380 if (ins.branch() == oldname) {
2381 undo().recordUndo(CursorData(it));
2382 ins.rename(newname);
2387 if (it->lyxCode() == INCLUDE_CODE) {
2388 // get buffer of external file
2389 InsetInclude const & ins =
2390 static_cast<InsetInclude const &>(*it);
2391 Buffer * child = ins.getChildBuffer();
2394 child->dispatch(func, dr);
2399 dr.screenUpdate(Update::Force);
2400 dr.forceBufferUpdate();
2405 case LFUN_BUFFER_PRINT: {
2406 // we'll assume there's a problem until we succeed
2408 string target = func.getArg(0);
2409 string target_name = func.getArg(1);
2410 string command = func.getArg(2);
2413 || target_name.empty()
2414 || command.empty()) {
2415 LYXERR0("Unable to parse " << func.argument());
2416 docstring const msg =
2417 bformat(_("Unable to parse \"%1$s\""), func.argument());
2421 if (target != "printer" && target != "file") {
2422 LYXERR0("Unrecognized target \"" << target << '"');
2423 docstring const msg =
2424 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2429 if (!doExport("dvi", true)) {
2430 showPrintError(absFileName());
2431 dr.setMessage(_("Error exporting to DVI."));
2435 // Push directory path.
2436 string const path = temppath();
2437 // Prevent the compiler from optimizing away p
2441 // there are three cases here:
2442 // 1. we print to a file
2443 // 2. we print directly to a printer
2444 // 3. we print using a spool command (print to file first)
2447 string const dviname = changeExtension(latexName(true), "dvi");
2449 if (target == "printer") {
2450 if (!lyxrc.print_spool_command.empty()) {
2451 // case 3: print using a spool
2452 string const psname = changeExtension(dviname,".ps");
2453 command += ' ' + lyxrc.print_to_file
2456 + quoteName(dviname);
2458 string command2 = lyxrc.print_spool_command + ' ';
2459 if (target_name != "default") {
2460 command2 += lyxrc.print_spool_printerprefix
2464 command2 += quoteName(psname);
2466 // If successful, then spool command
2467 res = one.startscript(Systemcall::Wait, command,
2471 // If there's no GUI, we have to wait on this command. Otherwise,
2472 // LyX deletes the temporary directory, and with it the spooled
2473 // file, before it can be printed!!
2474 Systemcall::Starttype stype = use_gui ?
2475 Systemcall::DontWait : Systemcall::Wait;
2476 res = one.startscript(stype, command2,
2480 // case 2: print directly to a printer
2481 if (target_name != "default")
2482 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2484 Systemcall::Starttype stype = use_gui ?
2485 Systemcall::DontWait : Systemcall::Wait;
2486 res = one.startscript(stype, command +
2487 quoteName(dviname), filePath());
2491 // case 1: print to a file
2492 FileName const filename(makeAbsPath(target_name, filePath()));
2493 FileName const dvifile(makeAbsPath(dviname, path));
2494 if (filename.exists()) {
2495 docstring text = bformat(
2496 _("The file %1$s already exists.\n\n"
2497 "Do you want to overwrite that file?"),
2498 makeDisplayPath(filename.absFileName()));
2499 if (Alert::prompt(_("Overwrite file?"),
2500 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2503 command += ' ' + lyxrc.print_to_file
2504 + quoteName(filename.toFilesystemEncoding())
2506 + quoteName(dvifile.toFilesystemEncoding());
2508 Systemcall::Starttype stype = use_gui ?
2509 Systemcall::DontWait : Systemcall::Wait;
2510 res = one.startscript(stype, command, filePath());
2516 dr.setMessage(_("Error running external commands."));
2517 showPrintError(absFileName());
2526 dr.dispatched(dispatched);
2527 undo().endUndoGroup();
2531 void Buffer::changeLanguage(Language const * from, Language const * to)
2533 LASSERT(from, /**/);
2536 for_each(par_iterator_begin(),
2538 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2542 bool Buffer::isMultiLingual() const
2544 ParConstIterator end = par_iterator_end();
2545 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2546 if (it->isMultiLingual(params()))
2553 std::set<Language const *> Buffer::getLanguages() const
2555 std::set<Language const *> languages;
2556 getLanguages(languages);
2561 void Buffer::getLanguages(std::set<Language const *> & languages) const
2563 ParConstIterator end = par_iterator_end();
2564 // add the buffer language, even if it's not actively used
2565 languages.insert(language());
2566 // iterate over the paragraphs
2567 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2568 it->getLanguages(languages);
2570 ListOfBuffers clist = getDescendents();
2571 ListOfBuffers::const_iterator cit = clist.begin();
2572 ListOfBuffers::const_iterator const cen = clist.end();
2573 for (; cit != cen; ++cit)
2574 (*cit)->getLanguages(languages);
2578 DocIterator Buffer::getParFromID(int const id) const
2580 Buffer * buf = const_cast<Buffer *>(this);
2582 // John says this is called with id == -1 from undo
2583 lyxerr << "getParFromID(), id: " << id << endl;
2584 return doc_iterator_end(buf);
2587 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2588 if (it.paragraph().id() == id)
2591 return doc_iterator_end(buf);
2595 bool Buffer::hasParWithID(int const id) const
2597 return !getParFromID(id).atEnd();
2601 ParIterator Buffer::par_iterator_begin()
2603 return ParIterator(doc_iterator_begin(this));
2607 ParIterator Buffer::par_iterator_end()
2609 return ParIterator(doc_iterator_end(this));
2613 ParConstIterator Buffer::par_iterator_begin() const
2615 return ParConstIterator(doc_iterator_begin(this));
2619 ParConstIterator Buffer::par_iterator_end() const
2621 return ParConstIterator(doc_iterator_end(this));
2625 Language const * Buffer::language() const
2627 return params().language;
2631 docstring const Buffer::B_(string const & l10n) const
2633 return params().B_(l10n);
2637 bool Buffer::isClean() const
2639 return d->lyx_clean;
2643 bool Buffer::isExternallyModified(CheckMethod method) const
2645 LASSERT(d->filename.exists(), /**/);
2646 // if method == timestamp, check timestamp before checksum
2647 return (method == checksum_method
2648 || d->timestamp_ != d->filename.lastModified())
2649 && d->checksum_ != d->filename.checksum();
2653 void Buffer::saveCheckSum() const
2655 FileName const & file = d->filename;
2658 if (file.exists()) {
2659 d->timestamp_ = file.lastModified();
2660 d->checksum_ = file.checksum();
2662 // in the case of save to a new file.
2669 void Buffer::markClean() const
2671 if (!d->lyx_clean) {
2672 d->lyx_clean = true;
2675 // if the .lyx file has been saved, we don't need an
2677 d->bak_clean = true;
2678 d->undo_.markDirty();
2682 void Buffer::setUnnamed(bool flag)
2688 bool Buffer::isUnnamed() const
2695 /// Don't check unnamed, here: isInternal() is used in
2696 /// newBuffer(), where the unnamed flag has not been set by anyone
2697 /// yet. Also, for an internal buffer, there should be no need for
2698 /// retrieving fileName() nor for checking if it is unnamed or not.
2699 bool Buffer::isInternal() const
2701 return d->internal_buffer;
2705 void Buffer::setInternal(bool flag)
2707 d->internal_buffer = flag;
2711 void Buffer::markDirty()
2714 d->lyx_clean = false;
2717 d->bak_clean = false;
2719 DepClean::iterator it = d->dep_clean.begin();
2720 DepClean::const_iterator const end = d->dep_clean.end();
2722 for (; it != end; ++it)
2727 FileName Buffer::fileName() const
2733 string Buffer::absFileName() const
2735 return d->filename.absFileName();
2739 string Buffer::filePath() const
2741 int last = d->filename.onlyPath().absFileName().length() - 1;
2743 return d->filename.onlyPath().absFileName()[last] == '/'
2744 ? d->filename.onlyPath().absFileName()
2745 : d->filename.onlyPath().absFileName() + "/";
2749 bool Buffer::isReadonly() const
2751 return d->read_only;
2755 void Buffer::setParent(Buffer const * buffer)
2757 // Avoids recursive include.
2758 d->setParent(buffer == this ? 0 : buffer);
2763 Buffer const * Buffer::parent() const
2769 ListOfBuffers Buffer::allRelatives() const
2771 ListOfBuffers lb = masterBuffer()->getDescendents();
2772 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2777 Buffer const * Buffer::masterBuffer() const
2779 // FIXME Should be make sure we are not in some kind
2780 // of recursive include? A -> B -> A will crash this.
2781 Buffer const * const pbuf = d->parent();
2785 return pbuf->masterBuffer();
2789 bool Buffer::isChild(Buffer * child) const
2791 return d->children_positions.find(child) != d->children_positions.end();
2795 DocIterator Buffer::firstChildPosition(Buffer const * child)
2797 Impl::BufferPositionMap::iterator it;
2798 it = d->children_positions.find(child);
2799 if (it == d->children_positions.end())
2800 return DocIterator(this);
2805 bool Buffer::hasChildren() const
2807 return !d->children_positions.empty();
2811 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2813 // loop over children
2814 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2815 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2816 for (; it != end; ++it) {
2817 Buffer * child = const_cast<Buffer *>(it->first);
2819 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2820 if (bit != clist.end())
2822 clist.push_back(child);
2824 // there might be grandchildren
2825 child->collectChildren(clist, true);
2830 ListOfBuffers Buffer::getChildren() const
2833 collectChildren(v, false);
2834 // Make sure we have not included ourselves.
2835 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2836 if (bit != v.end()) {
2837 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2844 ListOfBuffers Buffer::getDescendents() const
2847 collectChildren(v, true);
2848 // Make sure we have not included ourselves.
2849 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2850 if (bit != v.end()) {
2851 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2858 template<typename M>
2859 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2864 typename M::const_iterator it = m.lower_bound(x);
2865 if (it == m.begin())
2873 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2874 DocIterator const & pos) const
2876 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2878 // if paragraphs have no macro context set, pos will be empty
2882 // we haven't found anything yet
2883 DocIterator bestPos = owner_->par_iterator_begin();
2884 MacroData const * bestData = 0;
2886 // find macro definitions for name
2887 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2888 if (nameIt != macros.end()) {
2889 // find last definition in front of pos or at pos itself
2890 PositionScopeMacroMap::const_iterator it
2891 = greatest_below(nameIt->second, pos);
2892 if (it != nameIt->second.end()) {
2894 // scope ends behind pos?
2895 if (pos < it->second.first) {
2896 // Looks good, remember this. If there
2897 // is no external macro behind this,
2898 // we found the right one already.
2899 bestPos = it->first;
2900 bestData = &it->second.second;
2904 // try previous macro if there is one
2905 if (it == nameIt->second.begin())
2912 // find macros in included files
2913 PositionScopeBufferMap::const_iterator it
2914 = greatest_below(position_to_children, pos);
2915 if (it == position_to_children.end())
2916 // no children before
2920 // do we know something better (i.e. later) already?
2921 if (it->first < bestPos )
2924 // scope ends behind pos?
2925 if (pos < it->second.first
2926 && (cloned_buffer_ ||
2927 theBufferList().isLoaded(it->second.second))) {
2928 // look for macro in external file
2930 MacroData const * data
2931 = it->second.second->getMacro(name, false);
2934 bestPos = it->first;
2940 // try previous file if there is one
2941 if (it == position_to_children.begin())
2946 // return the best macro we have found
2951 MacroData const * Buffer::getMacro(docstring const & name,
2952 DocIterator const & pos, bool global) const
2957 // query buffer macros
2958 MacroData const * data = d->getBufferMacro(name, pos);
2962 // If there is a master buffer, query that
2963 Buffer const * const pbuf = d->parent();
2965 d->macro_lock = true;
2966 MacroData const * macro = pbuf->getMacro(
2967 name, *this, false);
2968 d->macro_lock = false;
2974 data = MacroTable::globalMacros().get(name);
2983 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2985 // set scope end behind the last paragraph
2986 DocIterator scope = par_iterator_begin();
2987 scope.pit() = scope.lastpit() + 1;
2989 return getMacro(name, scope, global);
2993 MacroData const * Buffer::getMacro(docstring const & name,
2994 Buffer const & child, bool global) const
2996 // look where the child buffer is included first
2997 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2998 if (it == d->children_positions.end())
3001 // check for macros at the inclusion position
3002 return getMacro(name, it->second, global);
3006 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3008 pit_type const lastpit = it.lastpit();
3010 // look for macros in each paragraph
3011 while (it.pit() <= lastpit) {
3012 Paragraph & par = it.paragraph();
3014 // iterate over the insets of the current paragraph
3015 InsetList const & insets = par.insetList();
3016 InsetList::const_iterator iit = insets.begin();
3017 InsetList::const_iterator end = insets.end();
3018 for (; iit != end; ++iit) {
3019 it.pos() = iit->pos;
3021 // is it a nested text inset?
3022 if (iit->inset->asInsetText()) {
3023 // Inset needs its own scope?
3024 InsetText const * itext = iit->inset->asInsetText();
3025 bool newScope = itext->isMacroScope();
3027 // scope which ends just behind the inset
3028 DocIterator insetScope = it;
3031 // collect macros in inset
3032 it.push_back(CursorSlice(*iit->inset));
3033 updateMacros(it, newScope ? insetScope : scope);
3038 if (iit->inset->asInsetTabular()) {
3039 CursorSlice slice(*iit->inset);
3040 size_t const numcells = slice.nargs();
3041 for (; slice.idx() < numcells; slice.forwardIdx()) {
3042 it.push_back(slice);
3043 updateMacros(it, scope);
3049 // is it an external file?
3050 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3051 // get buffer of external file
3052 InsetInclude const & inset =
3053 static_cast<InsetInclude const &>(*iit->inset);
3055 Buffer * child = inset.getChildBuffer();
3060 // register its position, but only when it is
3061 // included first in the buffer
3062 if (children_positions.find(child) ==
3063 children_positions.end())
3064 children_positions[child] = it;
3066 // register child with its scope
3067 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3071 InsetMath * im = iit->inset->asInsetMath();
3072 if (doing_export && im) {
3073 InsetMathHull * hull = im->asHullInset();
3075 hull->recordLocation(it);
3078 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3082 MathMacroTemplate & macroTemplate =
3083 *iit->inset->asInsetMath()->asMacroTemplate();
3084 MacroContext mc(owner_, it);
3085 macroTemplate.updateToContext(mc);
3088 bool valid = macroTemplate.validMacro();
3089 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3090 // then the BufferView's cursor will be invalid in
3091 // some cases which leads to crashes.
3096 // FIXME (Abdel), I don't understandt why we pass 'it' here
3097 // instead of 'macroTemplate' defined above... is this correct?
3098 macros[macroTemplate.name()][it] =
3099 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3109 void Buffer::updateMacros() const
3114 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3116 // start with empty table
3118 d->children_positions.clear();
3119 d->position_to_children.clear();
3121 // Iterate over buffer, starting with first paragraph
3122 // The scope must be bigger than any lookup DocIterator
3123 // later. For the global lookup, lastpit+1 is used, hence
3124 // we use lastpit+2 here.
3125 DocIterator it = par_iterator_begin();
3126 DocIterator outerScope = it;
3127 outerScope.pit() = outerScope.lastpit() + 2;
3128 d->updateMacros(it, outerScope);
3132 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3134 InsetIterator it = inset_iterator_begin(inset());
3135 InsetIterator const end = inset_iterator_end(inset());
3136 for (; it != end; ++it) {
3137 if (it->lyxCode() == BRANCH_CODE) {
3138 InsetBranch & br = static_cast<InsetBranch &>(*it);
3139 docstring const name = br.branch();
3140 if (!from_master && !params().branchlist().find(name))
3141 result.push_back(name);
3142 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3143 result.push_back(name);
3146 if (it->lyxCode() == INCLUDE_CODE) {
3147 // get buffer of external file
3148 InsetInclude const & ins =
3149 static_cast<InsetInclude const &>(*it);
3150 Buffer * child = ins.getChildBuffer();
3153 child->getUsedBranches(result, true);
3156 // remove duplicates
3161 void Buffer::updateMacroInstances(UpdateType utype) const
3163 LYXERR(Debug::MACROS, "updateMacroInstances for "
3164 << d->filename.onlyFileName());
3165 DocIterator it = doc_iterator_begin(this);
3167 DocIterator const end = doc_iterator_end(this);
3168 for (; it != end; it.forwardInset()) {
3169 // look for MathData cells in InsetMathNest insets
3170 InsetMath * minset = it.nextInset()->asInsetMath();
3174 // update macro in all cells of the InsetMathNest
3175 DocIterator::idx_type n = minset->nargs();
3176 MacroContext mc = MacroContext(this, it);
3177 for (DocIterator::idx_type i = 0; i < n; ++i) {
3178 MathData & data = minset->cell(i);
3179 data.updateMacros(0, mc, utype);
3185 void Buffer::listMacroNames(MacroNameSet & macros) const
3190 d->macro_lock = true;
3192 // loop over macro names
3193 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3194 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3195 for (; nameIt != nameEnd; ++nameIt)
3196 macros.insert(nameIt->first);
3198 // loop over children
3199 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3200 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3201 for (; it != end; ++it)
3202 it->first->listMacroNames(macros);
3205 Buffer const * const pbuf = d->parent();
3207 pbuf->listMacroNames(macros);
3209 d->macro_lock = false;
3213 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3215 Buffer const * const pbuf = d->parent();
3220 pbuf->listMacroNames(names);
3223 MacroNameSet::iterator it = names.begin();
3224 MacroNameSet::iterator end = names.end();
3225 for (; it != end; ++it) {
3227 MacroData const * data =
3228 pbuf->getMacro(*it, *this, false);
3230 macros.insert(data);
3232 // we cannot access the original MathMacroTemplate anymore
3233 // here to calls validate method. So we do its work here manually.
3234 // FIXME: somehow make the template accessible here.
3235 if (data->optionals() > 0)
3236 features.require("xargs");
3242 Buffer::References & Buffer::references(docstring const & label)
3245 return const_cast<Buffer *>(masterBuffer())->references(label);
3247 RefCache::iterator it = d->ref_cache_.find(label);
3248 if (it != d->ref_cache_.end())
3249 return it->second.second;
3251 static InsetLabel const * dummy_il = 0;
3252 static References const dummy_refs;
3253 it = d->ref_cache_.insert(
3254 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3255 return it->second.second;
3259 Buffer::References const & Buffer::references(docstring const & label) const
3261 return const_cast<Buffer *>(this)->references(label);
3265 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3267 masterBuffer()->d->ref_cache_[label].first = il;
3271 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3273 return masterBuffer()->d->ref_cache_[label].first;
3277 void Buffer::clearReferenceCache() const
3280 d->ref_cache_.clear();
3284 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3287 //FIXME: This does not work for child documents yet.
3288 LASSERT(code == CITE_CODE, /**/);
3290 reloadBibInfoCache();
3292 // Check if the label 'from' appears more than once
3293 BiblioInfo const & keys = masterBibInfo();
3294 BiblioInfo::const_iterator bit = keys.begin();
3295 BiblioInfo::const_iterator bend = keys.end();
3296 vector<docstring> labels;
3298 for (; bit != bend; ++bit)
3300 labels.push_back(bit->first);
3302 if (count(labels.begin(), labels.end(), from) > 1)
3305 string const paramName = "key";
3306 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3307 if (it->lyxCode() == code) {
3308 InsetCommand * inset = it->asInsetCommand();
3311 docstring const oldValue = inset->getParam(paramName);
3312 if (oldValue == from)
3313 inset->setParam(paramName, to);
3319 void Buffer::getSourceCode(odocstream & os, string const format,
3320 pit_type par_begin, pit_type par_end,
3321 OutputWhat output, bool master) const
3323 OutputParams runparams(¶ms().encoding());
3324 runparams.nice = true;
3325 runparams.flavor = params().getOutputFlavor(format);
3326 runparams.linelen = lyxrc.plaintext_linelen;
3327 // No side effect of file copying and image conversion
3328 runparams.dryrun = true;
3330 if (output == CurrentParagraph) {
3331 runparams.par_begin = par_begin;
3332 runparams.par_end = par_end;
3333 if (par_begin + 1 == par_end) {
3335 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3339 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3340 convert<docstring>(par_begin),
3341 convert<docstring>(par_end - 1))
3344 // output paragraphs
3345 if (runparams.flavor == OutputParams::LYX) {
3346 Paragraph const & par = text().paragraphs()[par_begin];
3348 depth_type dt = par.getDepth();
3349 par.write(ods, params(), dt);
3350 os << from_utf8(ods.str());
3351 } else if (runparams.flavor == OutputParams::HTML) {
3353 setMathFlavor(runparams);
3354 xhtmlParagraphs(text(), *this, xs, runparams);
3355 } else if (runparams.flavor == OutputParams::TEXT) {
3357 // FIXME Handles only one paragraph, unlike the others.
3358 // Probably should have some routine with a signature like them.
3359 writePlaintextParagraph(*this,
3360 text().paragraphs()[par_begin], os, runparams, dummy);
3361 } else if (params().isDocBook()) {
3362 docbookParagraphs(text(), *this, os, runparams);
3364 // If we are previewing a paragraph, even if this is the
3365 // child of some other buffer, let's cut the link here,
3366 // so that no concurring settings from the master
3367 // (e.g. branch state) interfere (see #8101).
3369 d->ignore_parent = true;
3370 // We need to validate the Buffer params' features here
3371 // in order to know if we should output polyglossia
3372 // macros (instead of babel macros)
3373 LaTeXFeatures features(*this, params(), runparams);
3374 params().validate(features);
3375 runparams.use_polyglossia = features.usePolyglossia();
3380 // latex or literate
3381 otexstream ots(os, texrow);
3384 latexParagraphs(*this, text(), ots, runparams);
3386 // Restore the parenthood
3388 d->ignore_parent = false;
3392 if (output == FullSource)
3393 os << _("Preview source code");
3394 else if (output == OnlyPreamble)
3395 os << _("Preview preamble");
3396 else if (output == OnlyBody)
3397 os << _("Preview body");
3399 if (runparams.flavor == OutputParams::LYX) {
3401 if (output == FullSource)
3403 else if (output == OnlyPreamble)
3404 params().writeFile(ods);
3405 else if (output == OnlyBody)
3407 os << from_utf8(ods.str());
3408 } else if (runparams.flavor == OutputParams::HTML) {
3409 writeLyXHTMLSource(os, runparams, output);
3410 } else if (runparams.flavor == OutputParams::TEXT) {
3411 if (output == OnlyPreamble) {
3412 os << "% "<< _("Plain text does not have a preamble.");
3414 writePlaintextFile(*this, os, runparams);
3415 } else if (params().isDocBook()) {
3416 writeDocBookSource(os, absFileName(), runparams, output);
3418 // latex or literate
3420 d->texrow.newline();
3421 d->texrow.newline();
3422 otexstream ots(os, d->texrow);
3424 runparams.is_child = true;
3425 writeLaTeXSource(ots, string(), runparams, output);
3431 ErrorList & Buffer::errorList(string const & type) const
3433 return d->errorLists[type];
3437 void Buffer::updateTocItem(std::string const & type,
3438 DocIterator const & dit) const
3441 d->gui_->updateTocItem(type, dit);
3445 void Buffer::structureChanged() const
3448 d->gui_->structureChanged();
3452 void Buffer::errors(string const & err, bool from_master) const
3455 d->gui_->errors(err, from_master);
3459 void Buffer::message(docstring const & msg) const
3462 d->gui_->message(msg);
3466 void Buffer::setBusy(bool on) const
3469 d->gui_->setBusy(on);
3473 void Buffer::updateTitles() const
3476 d->wa_->updateTitles();
3480 void Buffer::resetAutosaveTimers() const
3483 d->gui_->resetAutosaveTimers();
3487 bool Buffer::hasGuiDelegate() const
3493 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3502 class AutoSaveBuffer : public ForkedProcess {
3505 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3506 : buffer_(buffer), fname_(fname) {}
3508 virtual shared_ptr<ForkedProcess> clone() const
3510 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3515 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3516 from_utf8(fname_.absFileName())));
3517 return run(DontWait);
3521 virtual int generateChild();
3523 Buffer const & buffer_;
3528 int AutoSaveBuffer::generateChild()
3530 #if defined(__APPLE__)
3531 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3532 * We should use something else like threads.
3534 * Since I do not know how to determine at run time what is the OS X
3535 * version, I just disable forking altogether for now (JMarc)
3537 pid_t const pid = -1;
3539 // tmp_ret will be located (usually) in /tmp
3540 // will that be a problem?
3541 // Note that this calls ForkedCalls::fork(), so it's
3542 // ok cross-platform.
3543 pid_t const pid = fork();
3544 // If you want to debug the autosave
3545 // you should set pid to -1, and comment out the fork.
3546 if (pid != 0 && pid != -1)
3550 // pid = -1 signifies that lyx was unable
3551 // to fork. But we will do the save
3553 bool failed = false;
3554 FileName const tmp_ret = FileName::tempName("lyxauto");
3555 if (!tmp_ret.empty()) {
3556 buffer_.writeFile(tmp_ret);
3557 // assume successful write of tmp_ret
3558 if (!tmp_ret.moveTo(fname_))
3564 // failed to write/rename tmp_ret so try writing direct
3565 if (!buffer_.writeFile(fname_)) {
3566 // It is dangerous to do this in the child,
3567 // but safe in the parent, so...
3568 if (pid == -1) // emit message signal.
3569 buffer_.message(_("Autosave failed!"));
3573 if (pid == 0) // we are the child so...
3582 FileName Buffer::getEmergencyFileName() const
3584 return FileName(d->filename.absFileName() + ".emergency");
3588 FileName Buffer::getAutosaveFileName() const
3590 // if the document is unnamed try to save in the backup dir, else
3591 // in the default document path, and as a last try in the filePath,
3592 // which will most often be the temporary directory
3595 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3596 : lyxrc.backupdir_path;
3597 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3600 string const fname = "#" + d->filename.onlyFileName() + "#";
3602 return makeAbsPath(fname, fpath);
3606 void Buffer::removeAutosaveFile() const
3608 FileName const f = getAutosaveFileName();
3614 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3616 FileName const newauto = getAutosaveFileName();
3618 if (newauto != oldauto && oldauto.exists())
3619 if (!oldauto.moveTo(newauto))
3620 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3624 bool Buffer::autoSave() const
3626 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3627 if (buf->d->bak_clean || isReadonly())
3630 message(_("Autosaving current document..."));
3631 buf->d->bak_clean = true;
3633 FileName const fname = getAutosaveFileName();
3634 LASSERT(d->cloned_buffer_, return false);
3636 // If this buffer is cloned, we assume that
3637 // we are running in a separate thread already.
3638 FileName const tmp_ret = FileName::tempName("lyxauto");
3639 if (!tmp_ret.empty()) {
3641 // assume successful write of tmp_ret
3642 if (tmp_ret.moveTo(fname))
3645 // failed to write/rename tmp_ret so try writing direct
3646 return writeFile(fname);
3650 // helper class, to guarantee this gets reset properly
3651 class Buffer::MarkAsExporting {
3653 MarkAsExporting(Buffer const * buf) : buf_(buf)
3655 LASSERT(buf_, /* */);
3656 buf_->setExportStatus(true);
3660 buf_->setExportStatus(false);
3663 Buffer const * const buf_;
3668 void Buffer::setExportStatus(bool e) const
3670 d->doing_export = e;
3671 ListOfBuffers clist = getDescendents();
3672 ListOfBuffers::const_iterator cit = clist.begin();
3673 ListOfBuffers::const_iterator const cen = clist.end();
3674 for (; cit != cen; ++cit)
3675 (*cit)->d->doing_export = e;
3679 bool Buffer::isExporting() const
3681 return d->doing_export;
3685 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3689 return doExport(target, put_in_tempdir, result_file);
3692 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3693 string & result_file) const
3695 bool const update_unincluded =
3696 params().maintain_unincluded_children
3697 && !params().getIncludedChildren().empty();
3699 // (1) export with all included children (omit \includeonly)
3700 if (update_unincluded) {
3701 ExportStatus const status =
3702 doExport(target, put_in_tempdir, true, result_file);
3703 if (status != ExportSuccess)
3706 // (2) export with included children only
3707 return doExport(target, put_in_tempdir, false, result_file);
3711 void Buffer::setMathFlavor(OutputParams & op) const
3713 switch (params().html_math_output) {
3714 case BufferParams::MathML:
3715 op.math_flavor = OutputParams::MathAsMathML;
3717 case BufferParams::HTML:
3718 op.math_flavor = OutputParams::MathAsHTML;
3720 case BufferParams::Images:
3721 op.math_flavor = OutputParams::MathAsImages;
3723 case BufferParams::LaTeX:
3724 op.math_flavor = OutputParams::MathAsLaTeX;
3730 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3731 bool includeall, string & result_file) const
3733 LYXERR(Debug::FILES, "target=" << target);
3734 OutputParams runparams(¶ms().encoding());
3735 string format = target;
3736 string dest_filename;
3737 size_t pos = target.find(' ');
3738 if (pos != string::npos) {
3739 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3740 format = target.substr(0, pos);
3741 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3742 FileName(dest_filename).onlyPath().createPath();
3743 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3745 MarkAsExporting exporting(this);
3746 string backend_format;
3747 runparams.flavor = OutputParams::LATEX;
3748 runparams.linelen = lyxrc.plaintext_linelen;
3749 runparams.includeall = includeall;
3750 vector<string> backs = params().backends();
3751 Converters converters = theConverters();
3752 bool need_nice_file = false;
3753 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3754 // Get shortest path to format
3755 converters.buildGraph();
3756 Graph::EdgePath path;
3757 for (vector<string>::const_iterator it = backs.begin();
3758 it != backs.end(); ++it) {
3759 Graph::EdgePath p = converters.getPath(*it, format);
3760 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3761 backend_format = *it;
3766 if (!put_in_tempdir) {
3767 // Only show this alert if this is an export to a non-temporary
3768 // file (not for previewing).
3769 Alert::error(_("Couldn't export file"), bformat(
3770 _("No information for exporting the format %1$s."),
3771 formats.prettyName(format)));
3773 return ExportNoPathToFormat;
3775 runparams.flavor = converters.getFlavor(path, this);
3776 Graph::EdgePath::const_iterator it = path.begin();
3777 Graph::EdgePath::const_iterator en = path.end();
3778 for (; it != en; ++it)
3779 if (theConverters().get(*it).nice) {
3780 need_nice_file = true;
3785 backend_format = format;
3786 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3787 // FIXME: Don't hardcode format names here, but use a flag
3788 if (backend_format == "pdflatex")
3789 runparams.flavor = OutputParams::PDFLATEX;
3790 else if (backend_format == "luatex")
3791 runparams.flavor = OutputParams::LUATEX;
3792 else if (backend_format == "dviluatex")
3793 runparams.flavor = OutputParams::DVILUATEX;
3794 else if (backend_format == "xetex")
3795 runparams.flavor = OutputParams::XETEX;
3798 string filename = latexName(false);
3799 filename = addName(temppath(), filename);
3800 filename = changeExtension(filename,
3801 formats.extension(backend_format));
3802 LYXERR(Debug::FILES, "filename=" << filename);
3804 // Plain text backend
3805 if (backend_format == "text") {
3806 runparams.flavor = OutputParams::TEXT;
3807 writePlaintextFile(*this, FileName(filename), runparams);
3810 else if (backend_format == "xhtml") {
3811 runparams.flavor = OutputParams::HTML;
3812 setMathFlavor(runparams);
3813 makeLyXHTMLFile(FileName(filename), runparams);
3814 } else if (backend_format == "lyx")
3815 writeFile(FileName(filename));
3817 else if (params().isDocBook()) {
3818 runparams.nice = !put_in_tempdir;
3819 makeDocBookFile(FileName(filename), runparams);
3822 else if (backend_format == format || need_nice_file) {
3823 runparams.nice = true;
3824 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3825 if (d->cloned_buffer_)
3826 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3829 } else if (!lyxrc.tex_allows_spaces
3830 && contains(filePath(), ' ')) {
3831 Alert::error(_("File name error"),
3832 _("The directory path to the document cannot contain spaces."));
3833 return ExportTexPathHasSpaces;
3835 runparams.nice = false;
3836 bool const success = makeLaTeXFile(
3837 FileName(filename), filePath(), runparams);
3838 if (d->cloned_buffer_)
3839 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3844 string const error_type = (format == "program")
3845 ? "Build" : params().bufferFormat();
3846 ErrorList & error_list = d->errorLists[error_type];
3847 string const ext = formats.extension(format);
3848 FileName const tmp_result_file(changeExtension(filename, ext));
3849 bool const success = converters.convert(this, FileName(filename),
3850 tmp_result_file, FileName(absFileName()), backend_format, format,
3853 // Emit the signal to show the error list or copy it back to the
3854 // cloned Buffer so that it can be emitted afterwards.
3855 if (format != backend_format) {
3856 if (d->cloned_buffer_) {
3857 d->cloned_buffer_->d->errorLists[error_type] =
3858 d->errorLists[error_type];
3861 // also to the children, in case of master-buffer-view
3862 ListOfBuffers clist = getDescendents();
3863 ListOfBuffers::const_iterator cit = clist.begin();
3864 ListOfBuffers::const_iterator const cen = clist.end();
3865 for (; cit != cen; ++cit) {
3866 if (d->cloned_buffer_) {
3867 // Enable reverse search by copying back the
3868 // texrow object to the cloned buffer.
3869 // FIXME: this is not thread safe.
3870 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3871 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3872 (*cit)->d->errorLists[error_type];
3874 (*cit)->errors(error_type, true);
3878 if (d->cloned_buffer_) {
3879 // Enable reverse dvi or pdf to work by copying back the texrow
3880 // object to the cloned buffer.
3881 // FIXME: There is a possibility of concurrent access to texrow
3882 // here from the main GUI thread that should be securized.
3883 d->cloned_buffer_->d->texrow = d->texrow;
3884 string const error_type = params().bufferFormat();
3885 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3889 return ExportConverterError;
3891 if (put_in_tempdir) {
3892 result_file = tmp_result_file.absFileName();
3893 return ExportSuccess;
3896 if (dest_filename.empty())
3897 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3899 result_file = dest_filename;
3900 // We need to copy referenced files (e. g. included graphics
3901 // if format == "dvi") to the result dir.
3902 vector<ExportedFile> const files =
3903 runparams.exportdata->externalFiles(format);
3904 string const dest = runparams.export_folder.empty() ?
3905 onlyPath(result_file) : runparams.export_folder;
3906 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3907 : force_overwrite == ALL_FILES;
3908 CopyStatus status = use_force ? FORCE : SUCCESS;
3910 vector<ExportedFile>::const_iterator it = files.begin();
3911 vector<ExportedFile>::const_iterator const en = files.end();
3912 for (; it != en && status != CANCEL; ++it) {
3913 string const fmt = formats.getFormatFromFile(it->sourceName);
3914 string fixedName = it->exportName;
3915 if (!runparams.export_folder.empty()) {
3916 // Relative pathnames starting with ../ will be sanitized
3917 // if exporting to a different folder
3918 while (fixedName.substr(0, 3) == "../")
3919 fixedName = fixedName.substr(3, fixedName.length() - 3);
3921 FileName fixedFileName = makeAbsPath(fixedName, dest);
3922 fixedFileName.onlyPath().createPath();
3923 status = copyFile(fmt, it->sourceName,
3925 it->exportName, status == FORCE,
3926 runparams.export_folder.empty());
3929 if (status == CANCEL) {
3930 message(_("Document export cancelled."));
3931 return ExportCancel;
3934 if (tmp_result_file.exists()) {
3935 // Finally copy the main file
3936 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3937 : force_overwrite != NO_FILES;
3938 if (status == SUCCESS && use_force)
3940 status = copyFile(format, tmp_result_file,
3941 FileName(result_file), result_file,
3943 if (status == CANCEL) {
3944 message(_("Document export cancelled."));
3945 return ExportCancel;
3947 message(bformat(_("Document exported as %1$s "
3949 formats.prettyName(format),
3950 makeDisplayPath(result_file)));
3953 // This must be a dummy converter like fax (bug 1888)
3954 message(bformat(_("Document exported as %1$s"),
3955 formats.prettyName(format)));
3958 return ExportSuccess;
3962 Buffer::ExportStatus Buffer::preview(string const & format) const
3964 bool const update_unincluded =
3965 params().maintain_unincluded_children
3966 && !params().getIncludedChildren().empty();
3967 return preview(format, update_unincluded);
3970 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3972 MarkAsExporting exporting(this);
3974 // (1) export with all included children (omit \includeonly)
3976 ExportStatus const status = doExport(format, true, true, result_file);
3977 if (status != ExportSuccess)
3980 // (2) export with included children only
3981 ExportStatus const status = doExport(format, true, false, result_file);
3982 if (status != ExportSuccess)
3984 if (!formats.view(*this, FileName(result_file), format))
3985 return PreviewError;
3986 return PreviewSuccess;
3990 Buffer::ReadStatus Buffer::extractFromVC()
3992 bool const found = LyXVC::file_not_found_hook(d->filename);
3994 return ReadFileNotFound;
3995 if (!d->filename.isReadableFile())
4001 Buffer::ReadStatus Buffer::loadEmergency()
4003 FileName const emergencyFile = getEmergencyFileName();
4004 if (!emergencyFile.exists()
4005 || emergencyFile.lastModified() <= d->filename.lastModified())
4006 return ReadFileNotFound;
4008 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4009 docstring const text = bformat(_("An emergency save of the document "
4010 "%1$s exists.\n\nRecover emergency save?"), file);
4012 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4013 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4019 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4020 bool const success = (ret_llf == ReadSuccess);
4023 Alert::warning(_("File is read-only"),
4024 bformat(_("An emergency file is successfully loaded, "
4025 "but the original file %1$s is marked read-only. "
4026 "Please make sure to save the document as a different "
4027 "file."), from_utf8(d->filename.absFileName())));
4030 lyxvc().file_found_hook(d->filename);
4031 str = _("Document was successfully recovered.");
4033 str = _("Document was NOT successfully recovered.");
4034 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4035 makeDisplayPath(emergencyFile.absFileName()));
4037 int const del_emerg =
4038 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4039 _("&Remove"), _("&Keep"));
4040 if (del_emerg == 0) {
4041 emergencyFile.removeFile();
4043 Alert::warning(_("Emergency file deleted"),
4044 _("Do not forget to save your file now!"), true);
4046 return success ? ReadSuccess : ReadEmergencyFailure;
4049 int const del_emerg =
4050 Alert::prompt(_("Delete emergency file?"),
4051 _("Remove emergency file now?"), 1, 1,
4052 _("&Remove"), _("&Keep"));
4054 emergencyFile.removeFile();
4055 return ReadOriginal;
4065 Buffer::ReadStatus Buffer::loadAutosave()
4067 // Now check if autosave file is newer.
4068 FileName const autosaveFile = getAutosaveFileName();
4069 if (!autosaveFile.exists()
4070 || autosaveFile.lastModified() <= d->filename.lastModified())
4071 return ReadFileNotFound;
4073 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4074 docstring const text = bformat(_("The backup of the document %1$s "
4075 "is newer.\n\nLoad the backup instead?"), file);
4076 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4077 _("&Load backup"), _("Load &original"), _("&Cancel"));
4082 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4083 // the file is not saved if we load the autosave file.
4084 if (ret_llf == ReadSuccess) {
4086 Alert::warning(_("File is read-only"),
4087 bformat(_("A backup file is successfully loaded, "
4088 "but the original file %1$s is marked read-only. "
4089 "Please make sure to save the document as a "
4091 from_utf8(d->filename.absFileName())));
4094 lyxvc().file_found_hook(d->filename);
4097 return ReadAutosaveFailure;
4100 // Here we delete the autosave
4101 autosaveFile.removeFile();
4102 return ReadOriginal;
4110 Buffer::ReadStatus Buffer::loadLyXFile()
4112 if (!d->filename.isReadableFile()) {
4113 ReadStatus const ret_rvc = extractFromVC();
4114 if (ret_rvc != ReadSuccess)
4118 ReadStatus const ret_re = loadEmergency();
4119 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4122 ReadStatus const ret_ra = loadAutosave();
4123 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4126 return loadThisLyXFile(d->filename);
4130 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4132 return readFile(fn);
4136 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4138 TeXErrors::Errors::const_iterator it = terr.begin();
4139 TeXErrors::Errors::const_iterator end = terr.end();
4140 ListOfBuffers clist = getDescendents();
4141 ListOfBuffers::const_iterator cen = clist.end();
4143 for (; it != end; ++it) {
4146 int errorRow = it->error_in_line;
4147 Buffer const * buf = 0;
4149 if (it->child_name.empty())
4150 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4152 // The error occurred in a child
4153 ListOfBuffers::const_iterator cit = clist.begin();
4154 for (; cit != cen; ++cit) {
4155 string const child_name =
4156 DocFileName(changeExtension(
4157 (*cit)->absFileName(), "tex")).
4159 if (it->child_name != child_name)
4161 (*cit)->d->texrow.getIdFromRow(errorRow,
4162 id_start, pos_start);
4163 if (id_start != -1) {
4164 buf = d->cloned_buffer_
4165 ? (*cit)->d->cloned_buffer_->d->owner_
4166 : (*cit)->d->owner_;
4177 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4178 } while (found && id_start == id_end && pos_start == pos_end);
4180 if (id_start != id_end) {
4181 // Next registered position is outside the inset where
4182 // the error occurred, so signal end-of-paragraph
4186 errorList.push_back(ErrorItem(it->error_desc,
4187 it->error_text, id_start, pos_start, pos_end, buf));
4192 void Buffer::setBuffersForInsets() const
4194 inset().setBuffer(const_cast<Buffer &>(*this));
4198 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4200 // Use the master text class also for child documents
4201 Buffer const * const master = masterBuffer();
4202 DocumentClass const & textclass = master->params().documentClass();
4204 // do this only if we are the top-level Buffer
4206 reloadBibInfoCache();
4208 // keep the buffers to be children in this set. If the call from the
4209 // master comes back we can see which of them were actually seen (i.e.
4210 // via an InsetInclude). The remaining ones in the set need still be updated.
4211 static std::set<Buffer const *> bufToUpdate;
4212 if (scope == UpdateMaster) {
4213 // If this is a child document start with the master
4214 if (master != this) {
4215 bufToUpdate.insert(this);
4216 master->updateBuffer(UpdateMaster, utype);
4217 // Do this here in case the master has no gui associated with it. Then,
4218 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4219 if (!master->d->gui_)
4222 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4223 if (bufToUpdate.find(this) == bufToUpdate.end())
4227 // start over the counters in the master
4228 textclass.counters().reset();
4231 // update will be done below for this buffer
4232 bufToUpdate.erase(this);
4234 // update all caches
4235 clearReferenceCache();
4238 Buffer & cbuf = const_cast<Buffer &>(*this);
4240 LASSERT(!text().paragraphs().empty(), /**/);
4243 ParIterator parit = cbuf.par_iterator_begin();
4244 updateBuffer(parit, utype);
4247 // TocBackend update will be done later.
4250 d->bibinfo_cache_valid_ = true;
4251 d->cite_labels_valid_ = true;
4252 cbuf.tocBackend().update();
4253 if (scope == UpdateMaster)
4254 cbuf.structureChanged();
4258 static depth_type getDepth(DocIterator const & it)
4260 depth_type depth = 0;
4261 for (size_t i = 0 ; i < it.depth() ; ++i)
4262 if (!it[i].inset().inMathed())
4263 depth += it[i].paragraph().getDepth() + 1;
4264 // remove 1 since the outer inset does not count
4268 static depth_type getItemDepth(ParIterator const & it)
4270 Paragraph const & par = *it;
4271 LabelType const labeltype = par.layout().labeltype;
4273 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4276 // this will hold the lowest depth encountered up to now.
4277 depth_type min_depth = getDepth(it);
4278 ParIterator prev_it = it;
4281 --prev_it.top().pit();
4283 // start of nested inset: go to outer par
4285 if (prev_it.empty()) {
4286 // start of document: nothing to do
4291 // We search for the first paragraph with same label
4292 // that is not more deeply nested.
4293 Paragraph & prev_par = *prev_it;
4294 depth_type const prev_depth = getDepth(prev_it);
4295 if (labeltype == prev_par.layout().labeltype) {
4296 if (prev_depth < min_depth)
4297 return prev_par.itemdepth + 1;
4298 if (prev_depth == min_depth)
4299 return prev_par.itemdepth;
4301 min_depth = min(min_depth, prev_depth);
4302 // small optimization: if we are at depth 0, we won't
4303 // find anything else
4304 if (prev_depth == 0)
4310 static bool needEnumCounterReset(ParIterator const & it)
4312 Paragraph const & par = *it;
4313 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4314 depth_type const cur_depth = par.getDepth();
4315 ParIterator prev_it = it;
4316 while (prev_it.pit()) {
4317 --prev_it.top().pit();
4318 Paragraph const & prev_par = *prev_it;
4319 if (prev_par.getDepth() <= cur_depth)
4320 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4322 // start of nested inset: reset
4327 // set the label of a paragraph. This includes the counters.
4328 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4330 BufferParams const & bp = owner_->masterBuffer()->params();
4331 DocumentClass const & textclass = bp.documentClass();
4332 Paragraph & par = it.paragraph();
4333 Layout const & layout = par.layout();
4334 Counters & counters = textclass.counters();
4336 if (par.params().startOfAppendix()) {
4337 // We want to reset the counter corresponding to toplevel sectioning
4338 Layout const & lay = textclass.getTOCLayout();
4339 docstring const cnt = lay.counter;
4341 counters.reset(cnt);
4342 counters.appendix(true);
4344 par.params().appendix(counters.appendix());
4346 // Compute the item depth of the paragraph
4347 par.itemdepth = getItemDepth(it);
4349 if (layout.margintype == MARGIN_MANUAL) {
4350 if (par.params().labelWidthString().empty())
4351 par.params().labelWidthString(par.expandLabel(layout, bp));
4352 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4353 // we do not need to do anything here, since the empty case is
4354 // handled during export.
4356 par.params().labelWidthString(docstring());
4359 switch(layout.labeltype) {
4361 if (layout.toclevel <= bp.secnumdepth
4362 && (layout.latextype != LATEX_ENVIRONMENT
4363 || it.text()->isFirstInSequence(it.pit()))) {
4364 if (counters.hasCounter(layout.counter))
4365 counters.step(layout.counter, utype);
4366 par.params().labelString(par.expandLabel(layout, bp));
4368 par.params().labelString(docstring());
4371 case LABEL_ITEMIZE: {
4372 // At some point of time we should do something more
4373 // clever here, like:
4374 // par.params().labelString(
4375 // bp.user_defined_bullet(par.itemdepth).getText());
4376 // for now, use a simple hardcoded label
4377 docstring itemlabel;
4378 switch (par.itemdepth) {
4380 itemlabel = char_type(0x2022);
4383 itemlabel = char_type(0x2013);
4386 itemlabel = char_type(0x2217);
4389 itemlabel = char_type(0x2219); // or 0x00b7
4392 par.params().labelString(itemlabel);
4396 case LABEL_ENUMERATE: {
4397 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4399 switch (par.itemdepth) {
4408 enumcounter += "iv";
4411 // not a valid enumdepth...
4415 // Maybe we have to reset the enumeration counter.
4416 if (needEnumCounterReset(it))
4417 counters.reset(enumcounter);
4418 counters.step(enumcounter, utype);
4420 string const & lang = par.getParLanguage(bp)->code();
4421 par.params().labelString(counters.theCounter(enumcounter, lang));
4426 case LABEL_SENSITIVE: {
4427 string const & type = counters.current_float();
4428 docstring full_label;
4430 full_label = owner_->B_("Senseless!!! ");
4432 docstring name = owner_->B_(textclass.floats().getType(type).name());
4433 if (counters.hasCounter(from_utf8(type))) {
4434 string const & lang = par.getParLanguage(bp)->code();
4435 counters.step(from_utf8(type), utype);
4436 full_label = bformat(from_ascii("%1$s %2$s:"),
4438 counters.theCounter(from_utf8(type), lang));
4440 full_label = bformat(from_ascii("%1$s #:"), name);
4442 par.params().labelString(full_label);
4446 case LABEL_NO_LABEL:
4447 par.params().labelString(docstring());
4451 case LABEL_TOP_ENVIRONMENT:
4452 case LABEL_CENTERED_TOP_ENVIRONMENT:
4455 par.params().labelString(par.expandLabel(layout, bp));
4461 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4463 LASSERT(parit.pit() == 0, /**/);
4465 // Set the position of the text in the buffer to be able
4466 // to resolve macros in it.
4467 parit.text()->setMacrocontextPosition(parit);
4469 depth_type maxdepth = 0;
4470 pit_type const lastpit = parit.lastpit();
4471 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4472 // reduce depth if necessary
4473 if (parit->params().depth() > maxdepth) {
4474 /** FIXME: this function is const, but
4475 * nevertheless it modifies the buffer. To be
4476 * cleaner, one should modify the buffer in
4477 * another function, which is actually
4478 * non-const. This would however be costly in
4479 * terms of code duplication.
4481 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4482 parit->params().depth(maxdepth);
4484 maxdepth = parit->getMaxDepthAfter();
4486 if (utype == OutputUpdate) {
4487 // track the active counters
4488 // we have to do this for the master buffer, since the local
4489 // buffer isn't tracking anything.
4490 masterBuffer()->params().documentClass().counters().
4491 setActiveLayout(parit->layout());
4494 // set the counter for this paragraph
4495 d->setLabel(parit, utype);
4498 InsetList::const_iterator iit = parit->insetList().begin();
4499 InsetList::const_iterator end = parit->insetList().end();
4500 for (; iit != end; ++iit) {
4501 parit.pos() = iit->pos;
4502 iit->inset->updateBuffer(parit, utype);
4508 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4509 WordLangTuple & word_lang, docstring_list & suggestions) const
4513 suggestions.clear();
4514 word_lang = WordLangTuple();
4515 bool const to_end = to.empty();
4516 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4517 // OK, we start from here.
4518 for (; from != end; from.forwardPos()) {
4519 // We are only interested in text so remove the math CursorSlice.
4520 while (from.inMathed()) {
4524 // If from is at the end of the document (which is possible
4525 // when leaving the mathed) LyX will crash later otherwise.
4526 if (from.atEnd() || (!to_end && from >= end))
4529 from.paragraph().spellCheck();
4530 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4531 if (SpellChecker::misspelled(res)) {
4536 // Do not increase progress when from == to, otherwise the word
4537 // count will be wrong.
4547 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4549 bool inword = false;
4554 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4555 if (!dit.inTexted()) {
4560 Paragraph const & par = dit.paragraph();
4561 pos_type const pos = dit.pos();
4563 // Copied and adapted from isWordSeparator() in Paragraph
4564 if (pos == dit.lastpos()) {
4567 Inset const * ins = par.getInset(pos);
4568 if (ins && skipNoOutput && !ins->producesOutput()) {
4571 // stop if end of range was skipped
4572 if (!to.atEnd() && dit >= to)
4575 } else if (!par.isDeleted(pos)) {
4576 if (par.isWordSeparator(pos))
4582 if (ins && ins->isLetter())
4584 else if (ins && ins->isSpace())
4587 char_type const c = par.getChar(pos);
4588 if (isPrintableNonspace(c))
4590 else if (isSpace(c))
4600 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4602 d->updateStatistics(from, to, skipNoOutput);
4606 int Buffer::wordCount() const
4608 return d->wordCount();
4612 int Buffer::charCount(bool with_blanks) const
4614 return d->charCount(with_blanks);
4618 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4621 // c.f. bug http://www.lyx.org/trac/ticket/6587
4622 removeAutosaveFile();
4623 // e.g., read-only status could have changed due to version control
4624 d->filename.refresh();
4625 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4627 // clear parent. this will get reset if need be.
4629 ReadStatus const status = loadLyXFile();
4630 if (status == ReadSuccess) {
4635 message(bformat(_("Document %1$s reloaded."), disp_fn));
4639 message(bformat(_("Could not reload document %1$s."), disp_fn));
4649 bool Buffer::saveAs(FileName const & fn)
4651 FileName const old_name = fileName();
4652 FileName const old_auto = getAutosaveFileName();
4653 bool const old_unnamed = isUnnamed();
4660 // bring the autosave file with us, just in case.
4661 moveAutosaveFile(old_auto);
4662 // validate version control data and
4663 // correct buffer title
4664 lyxvc().file_found_hook(fileName());
4666 // the file has now been saved to the new location.
4667 // we need to check that the locations of child buffers
4669 checkChildBuffers();
4670 checkMasterBuffer();
4674 // reset the old filename and unnamed state
4675 setFileName(old_name);
4676 setUnnamed(old_unnamed);
4682 // FIXME We could do better here, but it is complicated. What would be
4683 // nice is to offer either (a) to save the child buffer to an appropriate
4684 // location, so that it would "move with the master", or else (b) to update
4685 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4686 // complicated, because the code for this lives in GuiView.
4687 void Buffer::checkChildBuffers()
4689 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4690 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4691 for (; it != en; ++it) {
4692 DocIterator dit = it->second;
4693 Buffer * cbuf = const_cast<Buffer *>(it->first);
4694 if (!cbuf || !theBufferList().isLoaded(cbuf))
4696 Inset * inset = dit.nextInset();
4697 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4698 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4699 docstring const & incfile = inset_inc->getParam("filename");
4700 string oldloc = cbuf->absFileName();
4701 string newloc = makeAbsPath(to_utf8(incfile),
4702 onlyPath(absFileName())).absFileName();
4703 if (oldloc == newloc)
4705 // the location of the child file is incorrect.
4706 Alert::warning(_("Included File Invalid"),
4707 bformat(_("Saving this document to a new location has made the file:\n"
4709 "inaccessible. You will need to update the included filename."),
4710 from_utf8(oldloc)));
4712 inset_inc->setChildBuffer(0);
4714 // invalidate cache of children
4715 d->children_positions.clear();
4716 d->position_to_children.clear();
4720 // If a child has been saved under a different name/path, it might have been
4721 // orphaned. Therefore the master needs to be reset (bug 8161).
4722 void Buffer::checkMasterBuffer()
4724 Buffer const * const master = masterBuffer();
4728 // necessary to re-register the child (bug 5873)
4729 // FIXME: clean up updateMacros (here, only
4730 // child registering is needed).
4731 master->updateMacros();
4732 // (re)set master as master buffer, but only
4733 // if we are a real child
4734 if (master->isChild(this))