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"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
221 typedef pair<DocIterator, MacroData> ScopeMacro;
222 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224 /// map from the macro name to the position map,
225 /// which maps the macro definition position to the scope and the MacroData.
226 NamePositionScopeMacroMap macros;
227 /// This seem to change the way Buffer::getMacro() works
228 mutable bool macro_lock;
230 /// positions of child buffers in the buffer
231 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Container for all sort of Buffer dependant errors.
240 map<string, ErrorList> errorLists;
242 /// timestamp and checksum used to test if the file has been externally
243 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable support::FileNameList bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// whether the bibinfo cache is valid
266 mutable bool bibinfo_cache_valid_;
267 /// whether the bibfile cache is valid
268 mutable bool bibfile_cache_valid_;
269 /// Cache of timestamps of .bib files
270 map<FileName, time_t> bibfile_status_;
271 /// Indicates whether the bibinfo has changed since the last time
272 /// we ran updateBuffer(), i.e., whether citation labels may need
274 mutable bool cite_labels_valid_;
276 mutable RefCache ref_cache_;
278 /// our Text that should be wrapped in an InsetText
282 PreviewLoader * preview_loader_;
284 /// This is here to force the test to be done whenever parent_buffer
286 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) {
304 if (parent_buffer == pb)
307 if (!cloned_buffer_ && parent_buffer && pb)
308 LYXERR0("Warning: a buffer should not have two parents!");
310 if (!cloned_buffer_ && parent_buffer) {
311 parent_buffer->invalidateBibfileCache();
312 parent_buffer->invalidateBibinfoCache();
316 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
317 /// This one is useful for preview detached in a thread.
318 Buffer const * cloned_buffer_;
320 CloneList * clone_list_;
321 /// are we in the process of exporting this buffer?
322 mutable bool doing_export;
324 /// compute statistics
325 /// \p from initial position
326 /// \p to points to the end position
327 void updateStatistics(DocIterator & from, DocIterator & to,
328 bool skipNoOutput = true);
329 /// statistics accessor functions
330 int wordCount() const { return word_count_; }
331 int charCount(bool with_blanks) const {
333 + (with_blanks ? blank_count_ : 0);
337 /// So we can force access via the accessors.
338 mutable Buffer const * parent_buffer;
347 /// Creates the per buffer temporary directory
348 static FileName createBufferTmpDir()
351 // We are in our own directory. Why bother to mangle name?
352 // In fact I wrote this code to circumvent a problematic behaviour
353 // (bug?) of EMX mkstemp().
354 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
355 convert<string>(count++));
357 if (!tmpfl.createDirectory(0777)) {
358 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
359 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
360 from_utf8(tmpfl.absFileName())));
366 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
367 Buffer const * cloned_buffer)
368 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
369 internal_buffer(false), read_only(readonly_), filename(file),
370 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
371 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
372 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
373 cite_labels_valid_(false), preview_loader_(0),
374 cloned_buffer_(cloned_buffer), clone_list_(0),
375 doing_export(false), parent_buffer(0)
377 if (!cloned_buffer_) {
378 temppath = createBufferTmpDir();
379 lyxvc.setBuffer(owner_);
381 wa_ = new frontend::WorkAreaManager;
384 temppath = cloned_buffer_->d->temppath;
385 file_fully_loaded = true;
386 params = cloned_buffer_->d->params;
387 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
388 bibinfo_ = cloned_buffer_->d->bibinfo_;
389 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
390 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
391 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
392 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
393 unnamed = cloned_buffer_->d->unnamed;
394 internal_buffer = cloned_buffer_->d->internal_buffer;
398 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
399 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
401 LYXERR(Debug::INFO, "Buffer::Buffer()");
403 d->inset = new InsetText(*cloned_buffer->d->inset);
404 d->inset->setBuffer(*this);
405 // FIXME: optimize this loop somewhat, maybe by creating a new
406 // general recursive Inset::setId().
407 DocIterator it = doc_iterator_begin(this);
408 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
409 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
410 it.paragraph().setId(cloned_it.paragraph().id());
412 d->inset = new InsetText(this);
413 d->inset->setAutoBreakRows(true);
414 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
420 LYXERR(Debug::INFO, "Buffer::~Buffer()");
421 // here the buffer should take care that it is
422 // saved properly, before it goes into the void.
424 // GuiView already destroyed
428 // No need to do additional cleanups for internal buffer.
434 // this is in case of recursive includes: we won't try to delete
435 // ourselves as a child.
436 d->clone_list_->erase(this);
437 // loop over children
438 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
439 Impl::BufferPositionMap::iterator end = d->children_positions.end();
440 for (; it != end; ++it) {
441 Buffer * child = const_cast<Buffer *>(it->first);
442 if (d->clone_list_->erase(child))
445 // if we're the master buffer, then we should get rid of the list
448 // if this is not empty, we have leaked something. worse, one of the
449 // children still has a reference to this list.
450 LASSERT(d->clone_list_->empty(), /* */);
451 list<CloneList *>::iterator it =
452 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
453 LASSERT(it != cloned_buffers.end(), /* */);
454 cloned_buffers.erase(it);
455 delete d->clone_list_;
457 // FIXME Do we really need to do this right before we delete d?
458 // clear references to children in macro tables
459 d->children_positions.clear();
460 d->position_to_children.clear();
462 // loop over children
463 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
464 Impl::BufferPositionMap::iterator end = d->children_positions.end();
465 for (; it != end; ++it) {
466 Buffer * child = const_cast<Buffer *>(it->first);
467 if (theBufferList().isLoaded(child))
468 theBufferList().releaseChild(this, child);
472 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
473 msg += emergencyWrite();
474 Alert::warning(_("Attempting to close changed document!"), msg);
477 // FIXME Do we really need to do this right before we delete d?
478 // clear references to children in macro tables
479 d->children_positions.clear();
480 d->position_to_children.clear();
482 if (!d->temppath.destroyDirectory()) {
483 Alert::warning(_("Could not remove temporary directory"),
484 bformat(_("Could not remove the temporary directory %1$s"),
485 from_utf8(d->temppath.absFileName())));
494 Buffer * Buffer::cloneFromMaster() const
497 cloned_buffers.push_back(new CloneList());
498 CloneList * clones = cloned_buffers.back();
500 masterBuffer()->cloneWithChildren(bufmap, clones);
502 // make sure we got cloned
503 BufferMap::const_iterator bit = bufmap.find(this);
504 LASSERT(bit != bufmap.end(), return 0);
505 Buffer * cloned_buffer = bit->second;
507 return cloned_buffer;
511 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
513 // have we already been cloned?
514 if (bufmap.find(this) != bufmap.end())
517 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
518 bufmap[this] = buffer_clone;
519 clones->insert(buffer_clone);
520 buffer_clone->d->clone_list_ = clones;
521 buffer_clone->d->macro_lock = true;
522 buffer_clone->d->children_positions.clear();
523 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
524 // math macro caches need to be rethought and simplified.
525 // I am not sure wether we should handle Buffer cloning here or in BufferList.
526 // Right now BufferList knows nothing about buffer clones.
527 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
528 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
529 for (; it != end; ++it) {
530 DocIterator dit = it->first.clone(buffer_clone);
531 dit.setBuffer(buffer_clone);
532 Buffer * child = const_cast<Buffer *>(it->second.second);
534 child->cloneWithChildren(bufmap, clones);
535 BufferMap::iterator const bit = bufmap.find(child);
536 LASSERT(bit != bufmap.end(), continue);
537 Buffer * child_clone = bit->second;
539 Inset * inset = dit.nextInset();
540 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
541 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
542 inset_inc->setChildBuffer(child_clone);
543 child_clone->d->setParent(buffer_clone);
544 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
545 buffer_clone->setChild(dit, child_clone);
547 buffer_clone->d->macro_lock = false;
552 Buffer * Buffer::cloneBufferOnly() const {
553 cloned_buffers.push_back(new CloneList());
554 CloneList * clones = cloned_buffers.back();
555 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
556 clones->insert(buffer_clone);
557 buffer_clone->d->clone_list_ = clones;
558 // we won't be cloning the children
559 buffer_clone->d->children_positions.clear();
564 bool Buffer::isClone() const
566 return d->cloned_buffer_;
570 void Buffer::changed(bool update_metrics) const
573 d->wa_->redrawAll(update_metrics);
577 frontend::WorkAreaManager & Buffer::workAreaManager() const
579 LASSERT(d->wa_, /**/);
584 Text & Buffer::text() const
586 return d->inset->text();
590 Inset & Buffer::inset() const
596 BufferParams & Buffer::params()
602 BufferParams const & Buffer::params() const
608 ParagraphList & Buffer::paragraphs()
610 return text().paragraphs();
614 ParagraphList const & Buffer::paragraphs() const
616 return text().paragraphs();
620 LyXVC & Buffer::lyxvc()
626 LyXVC const & Buffer::lyxvc() const
632 string const Buffer::temppath() const
634 return d->temppath.absFileName();
638 TexRow & Buffer::texrow()
644 TexRow const & Buffer::texrow() const
650 TocBackend & Buffer::tocBackend() const
652 return d->toc_backend;
656 Undo & Buffer::undo()
662 void Buffer::setChild(DocIterator const & dit, Buffer * child)
664 d->children_positions[child] = dit;
668 string Buffer::latexName(bool const no_path) const
670 FileName latex_name =
671 makeLatexName(d->exportFileName());
672 return no_path ? latex_name.onlyFileName()
673 : latex_name.absFileName();
677 FileName Buffer::Impl::exportFileName() const
679 docstring const branch_suffix =
680 params.branchlist().getFileNameSuffix();
681 if (branch_suffix.empty())
684 string const name = filename.onlyFileNameWithoutExt()
685 + to_utf8(branch_suffix);
686 FileName res(filename.onlyPath().absFileName() + "/" + name);
687 res.changeExtension(filename.extension());
693 string Buffer::logName(LogType * type) const
695 string const filename = latexName(false);
697 if (filename.empty()) {
703 string const path = temppath();
705 FileName const fname(addName(temppath(),
706 onlyFileName(changeExtension(filename,
709 // FIXME: how do we know this is the name of the build log?
710 FileName const bname(
711 addName(path, onlyFileName(
712 changeExtension(filename,
713 formats.extension(params().bufferFormat()) + ".out"))));
715 // Also consider the master buffer log file
716 FileName masterfname = fname;
718 if (masterBuffer() != this) {
719 string const mlogfile = masterBuffer()->logName(&mtype);
720 masterfname = FileName(mlogfile);
723 // If no Latex log or Build log is newer, show Build log
724 if (bname.exists() &&
725 ((!fname.exists() && !masterfname.exists())
726 || (fname.lastModified() < bname.lastModified()
727 && masterfname.lastModified() < bname.lastModified()))) {
728 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
731 return bname.absFileName();
732 // If we have a newer master file log or only a master log, show this
733 } else if (fname != masterfname
734 && (!fname.exists() && (masterfname.exists()
735 || fname.lastModified() < masterfname.lastModified()))) {
736 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
739 return masterfname.absFileName();
741 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
744 return fname.absFileName();
748 void Buffer::setReadonly(bool const flag)
750 if (d->read_only != flag) {
757 void Buffer::setFileName(FileName const & fname)
760 setReadonly(d->filename.isReadOnly());
766 int Buffer::readHeader(Lexer & lex)
768 int unknown_tokens = 0;
770 int begin_header_line = -1;
772 // Initialize parameters that may be/go lacking in header:
773 params().branchlist().clear();
774 params().preamble.erase();
775 params().options.erase();
776 params().master.erase();
777 params().float_placement.erase();
778 params().paperwidth.erase();
779 params().paperheight.erase();
780 params().leftmargin.erase();
781 params().rightmargin.erase();
782 params().topmargin.erase();
783 params().bottommargin.erase();
784 params().headheight.erase();
785 params().headsep.erase();
786 params().footskip.erase();
787 params().columnsep.erase();
788 params().fonts_cjk.erase();
789 params().listings_params.clear();
790 params().clearLayoutModules();
791 params().clearRemovedModules();
792 params().clearIncludedChildren();
793 params().pdfoptions().clear();
794 params().indiceslist().clear();
795 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
796 params().isbackgroundcolor = false;
797 params().fontcolor = RGBColor(0, 0, 0);
798 params().isfontcolor = false;
799 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
800 params().boxbgcolor = RGBColor(0xFF, 0, 0);
801 params().html_latex_start.clear();
802 params().html_latex_end.clear();
803 params().html_math_img_scale = 1.0;
804 params().output_sync_macro.erase();
805 params().local_layout.clear();
807 for (int i = 0; i < 4; ++i) {
808 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
809 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
812 ErrorList & errorList = d->errorLists["Parse"];
821 if (token == "\\end_header")
825 if (token == "\\begin_header") {
826 begin_header_line = line;
830 LYXERR(Debug::PARSER, "Handling document header token: `"
833 string unknown = params().readToken(lex, token, d->filename.onlyPath());
834 if (!unknown.empty()) {
835 if (unknown[0] != '\\' && token == "\\textclass") {
836 Alert::warning(_("Unknown document class"),
837 bformat(_("Using the default document class, because the "
838 "class %1$s is unknown."), from_utf8(unknown)));
841 docstring const s = bformat(_("Unknown token: "
845 errorList.push_back(ErrorItem(_("Document header error"),
850 if (begin_header_line) {
851 docstring const s = _("\\begin_header is missing");
852 errorList.push_back(ErrorItem(_("Document header error"),
856 params().makeDocumentClass();
858 return unknown_tokens;
863 // changed to be public and have one parameter
864 // Returns true if "\end_document" is not read (Asger)
865 bool Buffer::readDocument(Lexer & lex)
867 ErrorList & errorList = d->errorLists["Parse"];
870 // remove dummy empty par
871 paragraphs().clear();
873 if (!lex.checkFor("\\begin_document")) {
874 docstring const s = _("\\begin_document is missing");
875 errorList.push_back(ErrorItem(_("Document header error"),
881 if (params().outputChanges) {
882 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
883 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
884 LaTeXFeatures::isAvailable("xcolor");
886 if (!dvipost && !xcolorulem) {
887 Alert::warning(_("Changes not shown in LaTeX output"),
888 _("Changes will not be highlighted in LaTeX output, "
889 "because neither dvipost nor xcolor/ulem are installed.\n"
890 "Please install these packages or redefine "
891 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
892 } else if (!xcolorulem) {
893 Alert::warning(_("Changes not shown in LaTeX output"),
894 _("Changes will not be highlighted in LaTeX output "
895 "when using pdflatex, because xcolor and ulem are not installed.\n"
896 "Please install both packages or redefine "
897 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
901 if (!params().master.empty()) {
902 FileName const master_file = makeAbsPath(params().master,
903 onlyPath(absFileName()));
904 if (isLyXFileName(master_file.absFileName())) {
906 checkAndLoadLyXFile(master_file, true);
908 // necessary e.g. after a reload
909 // to re-register the child (bug 5873)
910 // FIXME: clean up updateMacros (here, only
911 // child registering is needed).
912 master->updateMacros();
913 // set master as master buffer, but only
914 // if we are a real child
915 if (master->isChild(this))
917 // if the master is not fully loaded
918 // it is probably just loading this
919 // child. No warning needed then.
920 else if (master->isFullyLoaded())
921 LYXERR0("The master '"
923 << "' assigned to this document ("
925 << ") does not include "
926 "this document. Ignoring the master assignment.");
931 // assure we have a default index
932 params().indiceslist().addDefault(B_("Index"));
935 bool const res = text().read(lex, errorList, d->inset);
937 // inform parent buffer about local macros
939 Buffer const * pbuf = parent();
940 UserMacroSet::const_iterator cit = usermacros.begin();
941 UserMacroSet::const_iterator end = usermacros.end();
942 for (; cit != end; ++cit)
943 pbuf->usermacros.insert(*cit);
947 updateMacroInstances(InternalUpdate);
952 bool Buffer::readString(string const & s)
954 params().compressed = false;
959 FileName const fn = FileName::tempName("Buffer_readString");
962 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
963 if (ret_plf != ReadSuccess)
966 if (file_format != LYX_FORMAT) {
967 // We need to call lyx2lyx, so write the input to a file
968 ofstream os(fn.toFilesystemEncoding().c_str());
972 return readFile(fn) == ReadSuccess;
975 if (readDocument(lex))
981 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
985 if (!lex.setFile(fname)) {
986 Alert::error(_("File Not Found"),
987 bformat(_("Unable to open file `%1$s'."),
988 from_utf8(fn.absFileName())));
989 return ReadFileNotFound;
993 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
994 if (ret_plf != ReadSuccess)
997 if (file_format != LYX_FORMAT) {
999 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1000 if (ret_clf != ReadSuccess)
1002 return readFile(tmpFile);
1005 // FIXME: InsetInfo needs to know whether the file is under VCS
1006 // during the parse process, so this has to be done before.
1007 lyxvc().file_found_hook(d->filename);
1009 if (readDocument(lex)) {
1010 Alert::error(_("Document format failure"),
1011 bformat(_("%1$s ended unexpectedly, which means"
1012 " that it is probably corrupted."),
1013 from_utf8(fn.absFileName())));
1014 return ReadDocumentFailure;
1017 d->file_fully_loaded = true;
1018 d->read_only = !d->filename.isWritable();
1019 params().compressed = formats.isZippedFile(d->filename);
1025 bool Buffer::isFullyLoaded() const
1027 return d->file_fully_loaded;
1031 void Buffer::setFullyLoaded(bool value)
1033 d->file_fully_loaded = value;
1037 PreviewLoader * Buffer::loader() const
1039 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1041 if (!d->preview_loader_)
1042 d->preview_loader_ = new PreviewLoader(*this);
1043 return d->preview_loader_;
1047 void Buffer::removePreviews() const
1049 delete d->preview_loader_;
1050 d->preview_loader_ = 0;
1054 void Buffer::updatePreviews() const
1056 PreviewLoader * ploader = loader();
1060 InsetIterator it = inset_iterator_begin(*d->inset);
1061 InsetIterator const end = inset_iterator_end(*d->inset);
1062 for (; it != end; ++it)
1063 it->addPreview(it, *ploader);
1065 ploader->startLoading();
1069 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1070 FileName const & fn, int & file_format) const
1072 if(!lex.checkFor("\\lyxformat")) {
1073 Alert::error(_("Document format failure"),
1074 bformat(_("%1$s is not a readable LyX document."),
1075 from_utf8(fn.absFileName())));
1076 return ReadNoLyXFormat;
1082 // LyX formats 217 and earlier were written as 2.17. This corresponds
1083 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1084 // these cases. See also: www.lyx.org/trac/changeset/1313.
1085 size_t dot = tmp_format.find_first_of(".,");
1086 if (dot != string::npos)
1087 tmp_format.erase(dot, 1);
1089 file_format = convert<int>(tmp_format);
1094 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1095 FileName & tmpfile, int from_format)
1097 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1098 if(tmpfile.empty()) {
1099 Alert::error(_("Conversion failed"),
1100 bformat(_("%1$s is from a different"
1101 " version of LyX, but a temporary"
1102 " file for converting it could"
1103 " not be created."),
1104 from_utf8(fn.absFileName())));
1105 return LyX2LyXNoTempFile;
1108 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1109 if (lyx2lyx.empty()) {
1110 Alert::error(_("Conversion script not found"),
1111 bformat(_("%1$s is from a different"
1112 " version of LyX, but the"
1113 " conversion script lyx2lyx"
1114 " could not be found."),
1115 from_utf8(fn.absFileName())));
1116 return LyX2LyXNotFound;
1120 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1121 ostringstream command;
1122 command << os::python()
1123 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1124 << " -t " << convert<string>(LYX_FORMAT)
1125 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1126 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1127 string const command_str = command.str();
1129 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1131 cmd_ret const ret = runCommand(command_str);
1132 if (ret.first != 0) {
1133 if (from_format < LYX_FORMAT) {
1134 Alert::error(_("Conversion script failed"),
1135 bformat(_("%1$s is from an older version"
1136 " of LyX and the lyx2lyx script"
1137 " failed to convert it."),
1138 from_utf8(fn.absFileName())));
1139 return LyX2LyXOlderFormat;
1141 Alert::error(_("Conversion script failed"),
1142 bformat(_("%1$s is from a newer version"
1143 " of LyX and the lyx2lyx script"
1144 " failed to convert it."),
1145 from_utf8(fn.absFileName())));
1146 return LyX2LyXNewerFormat;
1153 // Should probably be moved to somewhere else: BufferView? GuiView?
1154 bool Buffer::save() const
1156 docstring const file = makeDisplayPath(absFileName(), 20);
1157 d->filename.refresh();
1159 // check the read-only status before moving the file as a backup
1160 if (d->filename.exists()) {
1161 bool const read_only = !d->filename.isWritable();
1163 Alert::warning(_("File is read-only"),
1164 bformat(_("The file %1$s cannot be written because it "
1165 "is marked as read-only."), file));
1170 // ask if the disk file has been externally modified (use checksum method)
1171 if (fileName().exists() && isExternallyModified(checksum_method)) {
1173 bformat(_("Document %1$s has been externally modified. "
1174 "Are you sure you want to overwrite this file?"), file);
1175 int const ret = Alert::prompt(_("Overwrite modified file?"),
1176 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1181 // We don't need autosaves in the immediate future. (Asger)
1182 resetAutosaveTimers();
1184 FileName backupName;
1185 bool madeBackup = false;
1187 // make a backup if the file already exists
1188 if (lyxrc.make_backup && fileName().exists()) {
1189 backupName = FileName(absFileName() + '~');
1190 if (!lyxrc.backupdir_path.empty()) {
1191 string const mangledName =
1192 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1193 backupName = FileName(addName(lyxrc.backupdir_path,
1197 // Except file is symlink do not copy because of #6587.
1198 // Hard links have bad luck.
1199 if (fileName().isSymLink())
1200 madeBackup = fileName().copyTo(backupName);
1202 madeBackup = fileName().moveTo(backupName);
1205 Alert::error(_("Backup failure"),
1206 bformat(_("Cannot create backup file %1$s.\n"
1207 "Please check whether the directory exists and is writable."),
1208 from_utf8(backupName.absFileName())));
1209 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1213 if (writeFile(d->filename)) {
1217 // Saving failed, so backup is not backup
1219 backupName.moveTo(d->filename);
1225 bool Buffer::writeFile(FileName const & fname) const
1227 // FIXME Do we need to do these here? I don't think writing
1228 // the LyX file depends upon it. (RGH)
1230 // updateMacroInstances();
1232 if (d->read_only && fname == d->filename)
1235 bool retval = false;
1237 docstring const str = bformat(_("Saving document %1$s..."),
1238 makeDisplayPath(fname.absFileName()));
1241 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1243 if (params().compressed) {
1244 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1245 retval = ofs && write(ofs);
1247 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1248 retval = ofs && write(ofs);
1252 message(str + _(" could not write file!"));
1257 // removeAutosaveFile();
1260 message(str + _(" done."));
1266 docstring Buffer::emergencyWrite()
1268 // No need to save if the buffer has not changed.
1272 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1274 docstring user_message = bformat(
1275 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1277 // We try to save three places:
1278 // 1) Same place as document. Unless it is an unnamed doc.
1280 string s = absFileName();
1283 if (writeFile(FileName(s))) {
1285 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1286 return user_message;
1288 user_message += " " + _("Save failed! Trying again...\n");
1292 // 2) In HOME directory.
1293 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1295 lyxerr << ' ' << s << endl;
1296 if (writeFile(FileName(s))) {
1298 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1299 return user_message;
1302 user_message += " " + _("Save failed! Trying yet again...\n");
1304 // 3) In "/tmp" directory.
1305 // MakeAbsPath to prepend the current
1306 // drive letter on OS/2
1307 s = addName(package().temp_dir().absFileName(), absFileName());
1309 lyxerr << ' ' << s << endl;
1310 if (writeFile(FileName(s))) {
1312 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1313 return user_message;
1316 user_message += " " + _("Save failed! Bummer. Document is lost.");
1319 return user_message;
1323 bool Buffer::write(ostream & ofs) const
1326 // Use the standard "C" locale for file output.
1327 ofs.imbue(locale::classic());
1330 // The top of the file should not be written by params().
1332 // write out a comment in the top of the file
1333 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1334 << " created this file. For more info see http://www.lyx.org/\n"
1335 << "\\lyxformat " << LYX_FORMAT << "\n"
1336 << "\\begin_document\n";
1338 /// For each author, set 'used' to true if there is a change
1339 /// by this author in the document; otherwise set it to 'false'.
1340 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1341 AuthorList::Authors::const_iterator a_end = params().authors().end();
1342 for (; a_it != a_end; ++a_it)
1343 a_it->setUsed(false);
1345 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1346 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1347 for ( ; it != end; ++it)
1348 it->checkAuthors(params().authors());
1350 // now write out the buffer parameters.
1351 ofs << "\\begin_header\n";
1352 params().writeFile(ofs);
1353 ofs << "\\end_header\n";
1356 ofs << "\n\\begin_body\n";
1358 ofs << "\n\\end_body\n";
1360 // Write marker that shows file is complete
1361 ofs << "\\end_document" << endl;
1363 // Shouldn't really be needed....
1366 // how to check if close went ok?
1367 // Following is an attempt... (BE 20001011)
1369 // good() returns false if any error occured, including some
1370 // formatting error.
1371 // bad() returns true if something bad happened in the buffer,
1372 // which should include file system full errors.
1377 lyxerr << "File was not closed properly." << endl;
1384 bool Buffer::makeLaTeXFile(FileName const & fname,
1385 string const & original_path,
1386 OutputParams const & runparams_in,
1387 OutputWhat output) const
1389 OutputParams runparams = runparams_in;
1391 // This is necessary for LuaTeX/XeTeX with tex fonts.
1392 // See FIXME in BufferParams::encoding()
1393 if (runparams.isFullUnicode())
1394 runparams.encoding = encodings.fromLyXName("utf8-plain");
1396 string const encoding = runparams.encoding->iconvName();
1397 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1400 try { ofs.reset(encoding); }
1401 catch (iconv_codecvt_facet_exception const & e) {
1402 lyxerr << "Caught iconv exception: " << e.what() << endl;
1403 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1404 "verify that the support software for your encoding (%1$s) is "
1405 "properly installed"), from_ascii(encoding)));
1408 if (!openFileWrite(ofs, fname))
1411 //TexStream ts(ofs.rdbuf(), &texrow());
1412 ErrorList & errorList = d->errorLists["Export"];
1414 bool failed_export = false;
1415 otexstream os(ofs, d->texrow);
1417 // make sure we are ready to export
1418 // this needs to be done before we validate
1419 // FIXME Do we need to do this all the time? I.e., in children
1420 // of a master we are exporting?
1422 updateMacroInstances(OutputUpdate);
1425 os.texrow().reset();
1426 writeLaTeXSource(os, original_path, runparams, output);
1428 catch (EncodingException const & e) {
1429 odocstringstream ods;
1430 ods.put(e.failed_char);
1432 oss << "0x" << hex << e.failed_char << dec;
1433 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1434 " (code point %2$s)"),
1435 ods.str(), from_utf8(oss.str()));
1436 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1437 "representable in the chosen encoding.\n"
1438 "Changing the document encoding to utf8 could help."),
1439 e.par_id, e.pos, e.pos + 1));
1440 failed_export = true;
1442 catch (iconv_codecvt_facet_exception const & e) {
1443 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1444 _(e.what()), -1, 0, 0));
1445 failed_export = true;
1447 catch (exception const & e) {
1448 errorList.push_back(ErrorItem(_("conversion failed"),
1449 _(e.what()), -1, 0, 0));
1450 failed_export = true;
1453 lyxerr << "Caught some really weird exception..." << endl;
1459 failed_export = true;
1460 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1464 return !failed_export;
1468 void Buffer::writeLaTeXSource(otexstream & os,
1469 string const & original_path,
1470 OutputParams const & runparams_in,
1471 OutputWhat output) const
1473 // The child documents, if any, shall be already loaded at this point.
1475 OutputParams runparams = runparams_in;
1477 // If we are compiling a file standalone, even if this is the
1478 // child of some other buffer, let's cut the link here, so the
1479 // file is really independent and no concurring settings from
1480 // the master (e.g. branch state) interfere (see #8100).
1481 if (!runparams.is_child)
1482 d->ignore_parent = true;
1484 // Classify the unicode characters appearing in math insets
1485 Encodings::initUnicodeMath(*this);
1487 // validate the buffer.
1488 LYXERR(Debug::LATEX, " Validating buffer...");
1489 LaTeXFeatures features(*this, params(), runparams);
1491 runparams.use_polyglossia = features.usePolyglossia();
1492 LYXERR(Debug::LATEX, " Buffer validation done.");
1494 bool const output_preamble =
1495 output == FullSource || output == OnlyPreamble;
1496 bool const output_body =
1497 output == FullSource || output == OnlyBody;
1499 // The starting paragraph of the coming rows is the
1500 // first paragraph of the document. (Asger)
1501 if (output_preamble && runparams.nice) {
1502 os << "%% LyX " << lyx_version << " created this file. "
1503 "For more info, see http://www.lyx.org/.\n"
1504 "%% Do not edit unless you really know what "
1507 LYXERR(Debug::INFO, "lyx document header finished");
1509 // There are a few differences between nice LaTeX and usual files:
1510 // usual files have \batchmode and special input@path to allow
1511 // inclusion of figures specified by an explicitly relative path
1512 // (i.e., a path starting with './' or '../') with either \input or
1513 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1514 // input@path is set when the actual parameter original_path is set.
1515 // This is done for usual tex-file, but not for nice-latex-file.
1516 // (Matthias 250696)
1517 // Note that input@path is only needed for something the user does
1518 // in the preamble, included .tex files or ERT, files included by
1519 // LyX work without it.
1520 if (output_preamble) {
1521 if (!runparams.nice) {
1522 // code for usual, NOT nice-latex-file
1523 os << "\\batchmode\n"; // changed from \nonstopmode
1525 if (!original_path.empty()) {
1527 // We don't know the encoding of inputpath
1528 docstring const inputpath = from_utf8(original_path);
1529 docstring uncodable_glyphs;
1530 Encoding const * const enc = runparams.encoding;
1532 for (size_t n = 0; n < inputpath.size(); ++n) {
1533 if (!enc->encodable(inputpath[n])) {
1534 docstring const glyph(1, inputpath[n]);
1535 LYXERR0("Uncodable character '"
1537 << "' in input path!");
1538 uncodable_glyphs += glyph;
1543 // warn user if we found uncodable glyphs.
1544 if (!uncodable_glyphs.empty()) {
1545 frontend::Alert::warning(
1546 _("Uncodable character in file path"),
1548 _("The path of your document\n"
1550 "contains glyphs that are unknown "
1551 "in the current document encoding "
1552 "(namely %2$s). This may result in "
1553 "incomplete output, unless "
1554 "TEXINPUTS contains the document "
1555 "directory and you don't use "
1556 "explicitly relative paths (i.e., "
1557 "paths starting with './' or "
1558 "'../') in the preamble or in ERT."
1559 "\n\nIn case of problems, choose "
1560 "an appropriate document encoding\n"
1561 "(such as utf8) or change the "
1563 inputpath, uncodable_glyphs));
1566 support::latex_path(original_path);
1567 if (contains(docdir, '#')) {
1568 docdir = subst(docdir, "#", "\\#");
1569 os << "\\catcode`\\#=11"
1570 "\\def\\#{#}\\catcode`\\#=6\n";
1572 if (contains(docdir, '%')) {
1573 docdir = subst(docdir, "%", "\\%");
1574 os << "\\catcode`\\%=11"
1575 "\\def\\%{%}\\catcode`\\%=14\n";
1577 os << "\\makeatletter\n"
1578 << "\\def\\input@path{{"
1579 << docdir << "/}}\n"
1580 << "\\makeatother\n";
1584 // get parent macros (if this buffer has a parent) which will be
1585 // written at the document begin further down.
1586 MacroSet parentMacros;
1587 listParentMacros(parentMacros, features);
1589 // Write the preamble
1590 runparams.use_babel = params().writeLaTeX(os, features,
1591 d->filename.onlyPath());
1593 runparams.use_japanese = features.isRequired("japanese");
1599 os << "\\begin{document}\n";
1601 // output the parent macros
1602 MacroSet::iterator it = parentMacros.begin();
1603 MacroSet::iterator end = parentMacros.end();
1604 for (; it != end; ++it) {
1605 int num_lines = (*it)->write(os.os(), true);
1606 os.texrow().newlines(num_lines);
1609 } // output_preamble
1611 os.texrow().start(paragraphs().begin()->id(), 0);
1613 LYXERR(Debug::INFO, "preamble finished, now the body.");
1616 latexParagraphs(*this, text(), os, runparams);
1618 // Restore the parenthood if needed
1619 if (!runparams.is_child)
1620 d->ignore_parent = false;
1622 // add this just in case after all the paragraphs
1625 if (output_preamble) {
1626 os << "\\end{document}\n";
1627 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1629 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1631 runparams_in.encoding = runparams.encoding;
1633 // Just to be sure. (Asger)
1634 os.texrow().newline();
1636 //for (int i = 0; i<d->texrow.rows(); i++) {
1638 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1639 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1642 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1643 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1647 void Buffer::makeDocBookFile(FileName const & fname,
1648 OutputParams const & runparams,
1649 OutputWhat output) const
1651 LYXERR(Debug::LATEX, "makeDocBookFile...");
1654 if (!openFileWrite(ofs, fname))
1657 // make sure we are ready to export
1658 // this needs to be done before we validate
1660 updateMacroInstances(OutputUpdate);
1662 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1666 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1670 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1671 OutputParams const & runparams,
1672 OutputWhat output) const
1674 LaTeXFeatures features(*this, params(), runparams);
1679 DocumentClass const & tclass = params().documentClass();
1680 string const top_element = tclass.latexname();
1682 bool const output_preamble =
1683 output == FullSource || output == OnlyPreamble;
1684 bool const output_body =
1685 output == FullSource || output == OnlyBody;
1687 if (output_preamble) {
1688 if (runparams.flavor == OutputParams::XML)
1689 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1692 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1695 if (! tclass.class_header().empty())
1696 os << from_ascii(tclass.class_header());
1697 else if (runparams.flavor == OutputParams::XML)
1698 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1699 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1701 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1703 docstring preamble = from_utf8(params().preamble);
1704 if (runparams.flavor != OutputParams::XML ) {
1705 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1706 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1707 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1708 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1711 string const name = runparams.nice
1712 ? changeExtension(absFileName(), ".sgml") : fname;
1713 preamble += features.getIncludedFiles(name);
1714 preamble += features.getLyXSGMLEntities();
1716 if (!preamble.empty()) {
1717 os << "\n [ " << preamble << " ]";
1723 string top = top_element;
1725 if (runparams.flavor == OutputParams::XML)
1726 top += params().language->code();
1728 top += params().language->code().substr(0, 2);
1731 if (!params().options.empty()) {
1733 top += params().options;
1736 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1737 << " file was created by LyX " << lyx_version
1738 << "\n See http://www.lyx.org/ for more information -->\n";
1740 params().documentClass().counters().reset();
1742 sgml::openTag(os, top);
1744 docbookParagraphs(text(), *this, os, runparams);
1745 sgml::closeTag(os, top_element);
1750 void Buffer::makeLyXHTMLFile(FileName const & fname,
1751 OutputParams const & runparams) const
1753 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1756 if (!openFileWrite(ofs, fname))
1759 // make sure we are ready to export
1760 // this has to be done before we validate
1761 updateBuffer(UpdateMaster, OutputUpdate);
1762 updateMacroInstances(OutputUpdate);
1764 writeLyXHTMLSource(ofs, runparams, FullSource);
1768 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1772 void Buffer::writeLyXHTMLSource(odocstream & os,
1773 OutputParams const & runparams,
1774 OutputWhat output) const
1776 LaTeXFeatures features(*this, params(), runparams);
1778 d->bibinfo_.makeCitationLabels(*this);
1780 bool const output_preamble =
1781 output == FullSource || output == OnlyPreamble;
1782 bool const output_body =
1783 output == FullSource || output == OnlyBody || output == IncludedFile;
1785 if (output_preamble) {
1786 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1787 << "<!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"
1788 // FIXME Language should be set properly.
1789 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1791 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1792 // FIXME Presumably need to set this right
1793 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1795 docstring const & doctitle = features.htmlTitle();
1797 << (doctitle.empty() ?
1798 from_ascii("LyX Document") :
1799 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1802 docstring styles = features.getTClassHTMLPreamble();
1803 if (!styles.empty())
1804 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1806 styles = from_utf8(features.getPreambleSnippets());
1807 if (!styles.empty())
1808 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1810 // we will collect CSS information in a stream, and then output it
1811 // either here, as part of the header, or else in a separate file.
1812 odocstringstream css;
1813 styles = from_utf8(features.getCSSSnippets());
1814 if (!styles.empty())
1815 css << "/* LyX Provided Styles */\n" << styles << '\n';
1817 styles = features.getTClassHTMLStyles();
1818 if (!styles.empty())
1819 css << "/* Layout-provided Styles */\n" << styles << '\n';
1821 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1822 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1823 if (needfg || needbg) {
1824 css << "\nbody {\n";
1827 << from_ascii(X11hexname(params().fontcolor))
1830 css << " background-color: "
1831 << from_ascii(X11hexname(params().backgroundcolor))
1836 docstring const dstyles = css.str();
1837 if (!dstyles.empty()) {
1838 bool written = false;
1839 if (params().html_css_as_file) {
1840 // open a file for CSS info
1842 string const fcssname = addName(temppath(), "docstyle.css");
1843 FileName const fcssfile = FileName(fcssname);
1844 if (openFileWrite(ocss, fcssfile)) {
1848 // write link to header
1849 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1851 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1854 // we are here if the CSS is supposed to be written to the header
1855 // or if we failed to write it to an external file.
1857 os << "<style type='text/css'>\n"
1866 bool const output_body_tag = (output != IncludedFile);
1867 if (output_body_tag)
1870 params().documentClass().counters().reset();
1871 xhtmlParagraphs(text(), *this, xs, runparams);
1872 if (output_body_tag)
1876 if (output_preamble)
1881 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1882 // Other flags: -wall -v0 -x
1883 int Buffer::runChktex()
1887 // get LaTeX-Filename
1888 FileName const path(temppath());
1889 string const name = addName(path.absFileName(), latexName());
1890 string const org_path = filePath();
1892 PathChanger p(path); // path to LaTeX file
1893 message(_("Running chktex..."));
1895 // Generate the LaTeX file if neccessary
1896 OutputParams runparams(¶ms().encoding());
1897 runparams.flavor = OutputParams::LATEX;
1898 runparams.nice = false;
1899 runparams.linelen = lyxrc.plaintext_linelen;
1900 makeLaTeXFile(FileName(name), org_path, runparams);
1903 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1904 int const res = chktex.run(terr); // run chktex
1907 Alert::error(_("chktex failure"),
1908 _("Could not run chktex successfully."));
1909 } else if (res > 0) {
1910 ErrorList & errlist = d->errorLists["ChkTeX"];
1912 bufferErrors(terr, errlist);
1923 void Buffer::validate(LaTeXFeatures & features) const
1925 // Validate the buffer params, but not for included
1926 // files, since they also use the parent buffer's
1928 if (!features.runparams().is_child)
1929 params().validate(features);
1931 for_each(paragraphs().begin(), paragraphs().end(),
1932 bind(&Paragraph::validate, _1, ref(features)));
1934 if (lyxerr.debugging(Debug::LATEX)) {
1935 features.showStruct();
1940 void Buffer::getLabelList(vector<docstring> & list) const
1942 // If this is a child document, use the master's list instead.
1944 masterBuffer()->getLabelList(list);
1949 Toc & toc = d->toc_backend.toc("label");
1950 TocIterator toc_it = toc.begin();
1951 TocIterator end = toc.end();
1952 for (; toc_it != end; ++toc_it) {
1953 if (toc_it->depth() == 0)
1954 list.push_back(toc_it->str());
1959 void Buffer::updateBibfilesCache(UpdateScope scope) const
1961 // FIXME This is probably unnecssary, given where we call this.
1962 // If this is a child document, use the parent's cache instead.
1963 if (parent() && scope != UpdateChildOnly) {
1964 masterBuffer()->updateBibfilesCache();
1968 d->bibfiles_cache_.clear();
1969 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1970 if (it->lyxCode() == BIBTEX_CODE) {
1971 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1972 support::FileNameList const bibfiles = inset.getBibFiles();
1973 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1976 } else if (it->lyxCode() == INCLUDE_CODE) {
1977 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1978 Buffer const * const incbuf = inset.getChildBuffer();
1981 support::FileNameList const & bibfiles =
1982 incbuf->getBibfilesCache(UpdateChildOnly);
1983 if (!bibfiles.empty()) {
1984 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1990 d->bibfile_cache_valid_ = true;
1991 d->bibinfo_cache_valid_ = false;
1992 d->cite_labels_valid_ = false;
1996 void Buffer::invalidateBibinfoCache() const
1998 d->bibinfo_cache_valid_ = false;
1999 d->cite_labels_valid_ = false;
2000 // also invalidate the cache for the parent buffer
2001 Buffer const * const pbuf = d->parent();
2003 pbuf->invalidateBibinfoCache();
2007 void Buffer::invalidateBibfileCache() const
2009 d->bibfile_cache_valid_ = false;
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->invalidateBibfileCache();
2019 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2021 // FIXME This is probably unnecessary, given where we call this.
2022 // If this is a child document, use the master's cache instead.
2023 Buffer const * const pbuf = masterBuffer();
2024 if (pbuf != this && scope != UpdateChildOnly)
2025 return pbuf->getBibfilesCache();
2027 if (!d->bibfile_cache_valid_)
2028 this->updateBibfilesCache(scope);
2030 return d->bibfiles_cache_;
2034 BiblioInfo const & Buffer::masterBibInfo() const
2036 Buffer const * const tmp = masterBuffer();
2038 return tmp->masterBibInfo();
2043 void Buffer::checkIfBibInfoCacheIsValid() const
2045 // use the master's cache
2046 Buffer const * const tmp = masterBuffer();
2048 tmp->checkIfBibInfoCacheIsValid();
2052 // compare the cached timestamps with the actual ones.
2053 FileNameList const & bibfiles_cache = getBibfilesCache();
2054 FileNameList::const_iterator ei = bibfiles_cache.begin();
2055 FileNameList::const_iterator en = bibfiles_cache.end();
2056 for (; ei != en; ++ ei) {
2057 time_t lastw = ei->lastModified();
2058 time_t prevw = d->bibfile_status_[*ei];
2059 if (lastw != prevw) {
2060 d->bibinfo_cache_valid_ = false;
2061 d->cite_labels_valid_ = false;
2062 d->bibfile_status_[*ei] = lastw;
2068 void Buffer::reloadBibInfoCache() const
2070 // use the master's cache
2071 Buffer const * const tmp = masterBuffer();
2073 tmp->reloadBibInfoCache();
2077 checkIfBibInfoCacheIsValid();
2078 if (d->bibinfo_cache_valid_)
2081 d->bibinfo_.clear();
2083 d->bibinfo_cache_valid_ = true;
2087 void Buffer::collectBibKeys() const
2089 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2090 it->collectBibKeys(it);
2094 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2096 Buffer const * tmp = masterBuffer();
2097 BiblioInfo & masterbi = (tmp == this) ?
2098 d->bibinfo_ : tmp->d->bibinfo_;
2099 masterbi.mergeBiblioInfo(bi);
2103 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2105 Buffer const * tmp = masterBuffer();
2106 BiblioInfo & masterbi = (tmp == this) ?
2107 d->bibinfo_ : tmp->d->bibinfo_;
2112 bool Buffer::citeLabelsValid() const
2114 return masterBuffer()->d->cite_labels_valid_;
2118 void Buffer::removeBiblioTempFiles() const
2120 // We remove files that contain LaTeX commands specific to the
2121 // particular bibliographic style being used, in order to avoid
2122 // LaTeX errors when we switch style.
2123 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2124 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2125 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2126 aux_file.removeFile();
2127 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2128 bbl_file.removeFile();
2129 // Also for the parent buffer
2130 Buffer const * const pbuf = parent();
2132 pbuf->removeBiblioTempFiles();
2136 bool Buffer::isDepClean(string const & name) const
2138 DepClean::const_iterator const it = d->dep_clean.find(name);
2139 if (it == d->dep_clean.end())
2145 void Buffer::markDepClean(string const & name)
2147 d->dep_clean[name] = true;
2151 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2154 // FIXME? if there is an Buffer LFUN that can be dispatched even
2155 // if internal, put a switch '(cmd.action)' here.
2161 switch (cmd.action()) {
2163 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2164 flag.setOnOff(isReadonly());
2167 // FIXME: There is need for a command-line import.
2168 //case LFUN_BUFFER_IMPORT:
2170 case LFUN_BUFFER_AUTO_SAVE:
2173 case LFUN_BUFFER_EXPORT_CUSTOM:
2174 // FIXME: Nothing to check here?
2177 case LFUN_BUFFER_EXPORT: {
2178 docstring const arg = cmd.argument();
2179 if (arg == "custom") {
2183 string format = to_utf8(arg);
2184 size_t pos = format.find(' ');
2185 if (pos != string::npos)
2186 format = format.substr(0, pos);
2187 enable = params().isExportable(format);
2189 flag.message(bformat(
2190 _("Don't know how to export to format: %1$s"), arg));
2194 case LFUN_BUFFER_CHKTEX:
2195 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2198 case LFUN_BUILD_PROGRAM:
2199 enable = params().isExportable("program");
2202 case LFUN_BRANCH_ADD:
2203 case LFUN_BRANCHES_RENAME:
2204 case LFUN_BUFFER_PRINT:
2205 // if no Buffer is present, then of course we won't be called!
2208 case LFUN_BUFFER_LANGUAGE:
2209 enable = !isReadonly();
2215 flag.setEnabled(enable);
2220 void Buffer::dispatch(string const & command, DispatchResult & result)
2222 return dispatch(lyxaction.lookupFunc(command), result);
2226 // NOTE We can end up here even if we have no GUI, because we are called
2227 // by LyX::exec to handled command-line requests. So we may need to check
2228 // whether we have a GUI or not. The boolean use_gui holds this information.
2229 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2232 // FIXME? if there is an Buffer LFUN that can be dispatched even
2233 // if internal, put a switch '(cmd.action())' here.
2234 dr.dispatched(false);
2237 string const argument = to_utf8(func.argument());
2238 // We'll set this back to false if need be.
2239 bool dispatched = true;
2240 undo().beginUndoGroup();
2242 switch (func.action()) {
2243 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2244 if (lyxvc().inUse())
2245 lyxvc().toggleReadOnly();
2247 setReadonly(!isReadonly());
2250 case LFUN_BUFFER_EXPORT: {
2251 ExportStatus const status = doExport(argument, false);
2252 dr.setError(status != ExportSuccess);
2253 if (status != ExportSuccess)
2254 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2259 case LFUN_BUILD_PROGRAM:
2260 doExport("program", true);
2263 case LFUN_BUFFER_CHKTEX:
2267 case LFUN_BUFFER_EXPORT_CUSTOM: {
2269 string command = split(argument, format_name, ' ');
2270 Format const * format = formats.getFormat(format_name);
2272 lyxerr << "Format \"" << format_name
2273 << "\" not recognized!"
2278 // The name of the file created by the conversion process
2281 // Output to filename
2282 if (format->name() == "lyx") {
2283 string const latexname = latexName(false);
2284 filename = changeExtension(latexname,
2285 format->extension());
2286 filename = addName(temppath(), filename);
2288 if (!writeFile(FileName(filename)))
2292 doExport(format_name, true, filename);
2295 // Substitute $$FName for filename
2296 if (!contains(command, "$$FName"))
2297 command = "( " + command + " ) < $$FName";
2298 command = subst(command, "$$FName", filename);
2300 // Execute the command in the background
2302 call.startscript(Systemcall::DontWait, command, filePath());
2306 // FIXME: There is need for a command-line import.
2308 case LFUN_BUFFER_IMPORT:
2313 case LFUN_BUFFER_AUTO_SAVE:
2315 resetAutosaveTimers();
2318 case LFUN_BRANCH_ADD: {
2319 docstring branch_name = func.argument();
2320 if (branch_name.empty()) {
2324 BranchList & branch_list = params().branchlist();
2325 vector<docstring> const branches =
2326 getVectorFromString(branch_name, branch_list.separator());
2328 for (vector<docstring>::const_iterator it = branches.begin();
2329 it != branches.end(); ++it) {
2331 Branch * branch = branch_list.find(branch_name);
2333 LYXERR0("Branch " << branch_name << " already exists.");
2337 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2339 branch_list.add(branch_name);
2340 branch = branch_list.find(branch_name);
2341 string const x11hexname = X11hexname(branch->color());
2342 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2343 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2345 dr.screenUpdate(Update::Force);
2353 case LFUN_BRANCHES_RENAME: {
2354 if (func.argument().empty())
2357 docstring const oldname = from_utf8(func.getArg(0));
2358 docstring const newname = from_utf8(func.getArg(1));
2359 InsetIterator it = inset_iterator_begin(inset());
2360 InsetIterator const end = inset_iterator_end(inset());
2361 bool success = false;
2362 for (; it != end; ++it) {
2363 if (it->lyxCode() == BRANCH_CODE) {
2364 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2365 if (ins.branch() == oldname) {
2366 undo().recordUndo(CursorData(it));
2367 ins.rename(newname);
2372 if (it->lyxCode() == INCLUDE_CODE) {
2373 // get buffer of external file
2374 InsetInclude const & ins =
2375 static_cast<InsetInclude const &>(*it);
2376 Buffer * child = ins.getChildBuffer();
2379 child->dispatch(func, dr);
2384 dr.screenUpdate(Update::Force);
2385 dr.forceBufferUpdate();
2390 case LFUN_BUFFER_PRINT: {
2391 // we'll assume there's a problem until we succeed
2393 string target = func.getArg(0);
2394 string target_name = func.getArg(1);
2395 string command = func.getArg(2);
2398 || target_name.empty()
2399 || command.empty()) {
2400 LYXERR0("Unable to parse " << func.argument());
2401 docstring const msg =
2402 bformat(_("Unable to parse \"%1$s\""), func.argument());
2406 if (target != "printer" && target != "file") {
2407 LYXERR0("Unrecognized target \"" << target << '"');
2408 docstring const msg =
2409 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2414 if (!doExport("dvi", true)) {
2415 showPrintError(absFileName());
2416 dr.setMessage(_("Error exporting to DVI."));
2420 // Push directory path.
2421 string const path = temppath();
2422 // Prevent the compiler from optimizing away p
2426 // there are three cases here:
2427 // 1. we print to a file
2428 // 2. we print directly to a printer
2429 // 3. we print using a spool command (print to file first)
2432 string const dviname = changeExtension(latexName(true), "dvi");
2434 if (target == "printer") {
2435 if (!lyxrc.print_spool_command.empty()) {
2436 // case 3: print using a spool
2437 string const psname = changeExtension(dviname,".ps");
2438 command += ' ' + lyxrc.print_to_file
2441 + quoteName(dviname);
2443 string command2 = lyxrc.print_spool_command + ' ';
2444 if (target_name != "default") {
2445 command2 += lyxrc.print_spool_printerprefix
2449 command2 += quoteName(psname);
2451 // If successful, then spool command
2452 res = one.startscript(Systemcall::Wait, command,
2456 // If there's no GUI, we have to wait on this command. Otherwise,
2457 // LyX deletes the temporary directory, and with it the spooled
2458 // file, before it can be printed!!
2459 Systemcall::Starttype stype = use_gui ?
2460 Systemcall::DontWait : Systemcall::Wait;
2461 res = one.startscript(stype, command2,
2465 // case 2: print directly to a printer
2466 if (target_name != "default")
2467 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2469 Systemcall::Starttype stype = use_gui ?
2470 Systemcall::DontWait : Systemcall::Wait;
2471 res = one.startscript(stype, command +
2472 quoteName(dviname), filePath());
2476 // case 1: print to a file
2477 FileName const filename(makeAbsPath(target_name, filePath()));
2478 FileName const dvifile(makeAbsPath(dviname, path));
2479 if (filename.exists()) {
2480 docstring text = bformat(
2481 _("The file %1$s already exists.\n\n"
2482 "Do you want to overwrite that file?"),
2483 makeDisplayPath(filename.absFileName()));
2484 if (Alert::prompt(_("Overwrite file?"),
2485 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2488 command += ' ' + lyxrc.print_to_file
2489 + quoteName(filename.toFilesystemEncoding())
2491 + quoteName(dvifile.toFilesystemEncoding());
2493 Systemcall::Starttype stype = use_gui ?
2494 Systemcall::DontWait : Systemcall::Wait;
2495 res = one.startscript(stype, command, filePath());
2501 dr.setMessage(_("Error running external commands."));
2502 showPrintError(absFileName());
2511 dr.dispatched(dispatched);
2512 undo().endUndoGroup();
2516 void Buffer::changeLanguage(Language const * from, Language const * to)
2518 LASSERT(from, /**/);
2521 for_each(par_iterator_begin(),
2523 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2527 bool Buffer::isMultiLingual() const
2529 ParConstIterator end = par_iterator_end();
2530 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2531 if (it->isMultiLingual(params()))
2538 std::set<Language const *> Buffer::getLanguages() const
2540 std::set<Language const *> languages;
2541 getLanguages(languages);
2546 void Buffer::getLanguages(std::set<Language const *> & languages) const
2548 ParConstIterator end = par_iterator_end();
2549 // add the buffer language, even if it's not actively used
2550 languages.insert(language());
2551 // iterate over the paragraphs
2552 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2553 it->getLanguages(languages);
2555 ListOfBuffers clist = getDescendents();
2556 ListOfBuffers::const_iterator cit = clist.begin();
2557 ListOfBuffers::const_iterator const cen = clist.end();
2558 for (; cit != cen; ++cit)
2559 (*cit)->getLanguages(languages);
2563 DocIterator Buffer::getParFromID(int const id) const
2565 Buffer * buf = const_cast<Buffer *>(this);
2567 // John says this is called with id == -1 from undo
2568 lyxerr << "getParFromID(), id: " << id << endl;
2569 return doc_iterator_end(buf);
2572 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2573 if (it.paragraph().id() == id)
2576 return doc_iterator_end(buf);
2580 bool Buffer::hasParWithID(int const id) const
2582 return !getParFromID(id).atEnd();
2586 ParIterator Buffer::par_iterator_begin()
2588 return ParIterator(doc_iterator_begin(this));
2592 ParIterator Buffer::par_iterator_end()
2594 return ParIterator(doc_iterator_end(this));
2598 ParConstIterator Buffer::par_iterator_begin() const
2600 return ParConstIterator(doc_iterator_begin(this));
2604 ParConstIterator Buffer::par_iterator_end() const
2606 return ParConstIterator(doc_iterator_end(this));
2610 Language const * Buffer::language() const
2612 return params().language;
2616 docstring const Buffer::B_(string const & l10n) const
2618 return params().B_(l10n);
2622 bool Buffer::isClean() const
2624 return d->lyx_clean;
2628 bool Buffer::isExternallyModified(CheckMethod method) const
2630 LASSERT(d->filename.exists(), /**/);
2631 // if method == timestamp, check timestamp before checksum
2632 return (method == checksum_method
2633 || d->timestamp_ != d->filename.lastModified())
2634 && d->checksum_ != d->filename.checksum();
2638 void Buffer::saveCheckSum() const
2640 FileName const & file = d->filename;
2643 if (file.exists()) {
2644 d->timestamp_ = file.lastModified();
2645 d->checksum_ = file.checksum();
2647 // in the case of save to a new file.
2654 void Buffer::markClean() const
2656 if (!d->lyx_clean) {
2657 d->lyx_clean = true;
2660 // if the .lyx file has been saved, we don't need an
2662 d->bak_clean = true;
2663 d->undo_.markDirty();
2667 void Buffer::setUnnamed(bool flag)
2673 bool Buffer::isUnnamed() const
2680 /// Don't check unnamed, here: isInternal() is used in
2681 /// newBuffer(), where the unnamed flag has not been set by anyone
2682 /// yet. Also, for an internal buffer, there should be no need for
2683 /// retrieving fileName() nor for checking if it is unnamed or not.
2684 bool Buffer::isInternal() const
2686 return d->internal_buffer;
2690 void Buffer::setInternal(bool flag)
2692 d->internal_buffer = flag;
2696 void Buffer::markDirty()
2699 d->lyx_clean = false;
2702 d->bak_clean = false;
2704 DepClean::iterator it = d->dep_clean.begin();
2705 DepClean::const_iterator const end = d->dep_clean.end();
2707 for (; it != end; ++it)
2712 FileName Buffer::fileName() const
2718 string Buffer::absFileName() const
2720 return d->filename.absFileName();
2724 string Buffer::filePath() const
2726 int last = d->filename.onlyPath().absFileName().length() - 1;
2728 return d->filename.onlyPath().absFileName()[last] == '/'
2729 ? d->filename.onlyPath().absFileName()
2730 : d->filename.onlyPath().absFileName() + "/";
2734 bool Buffer::isReadonly() const
2736 return d->read_only;
2740 void Buffer::setParent(Buffer const * buffer)
2742 // Avoids recursive include.
2743 d->setParent(buffer == this ? 0 : buffer);
2748 Buffer const * Buffer::parent() const
2754 ListOfBuffers Buffer::allRelatives() const
2756 ListOfBuffers lb = masterBuffer()->getDescendents();
2757 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2762 Buffer const * Buffer::masterBuffer() const
2764 // FIXME Should be make sure we are not in some kind
2765 // of recursive include? A -> B -> A will crash this.
2766 Buffer const * const pbuf = d->parent();
2770 return pbuf->masterBuffer();
2774 bool Buffer::isChild(Buffer * child) const
2776 return d->children_positions.find(child) != d->children_positions.end();
2780 DocIterator Buffer::firstChildPosition(Buffer const * child)
2782 Impl::BufferPositionMap::iterator it;
2783 it = d->children_positions.find(child);
2784 if (it == d->children_positions.end())
2785 return DocIterator(this);
2790 bool Buffer::hasChildren() const
2792 return !d->children_positions.empty();
2796 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2798 // loop over children
2799 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2800 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2801 for (; it != end; ++it) {
2802 Buffer * child = const_cast<Buffer *>(it->first);
2804 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2805 if (bit != clist.end())
2807 clist.push_back(child);
2809 // there might be grandchildren
2810 child->collectChildren(clist, true);
2815 ListOfBuffers Buffer::getChildren() const
2818 collectChildren(v, false);
2819 // Make sure we have not included ourselves.
2820 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2821 if (bit != v.end()) {
2822 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2829 ListOfBuffers Buffer::getDescendents() const
2832 collectChildren(v, true);
2833 // Make sure we have not included ourselves.
2834 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2835 if (bit != v.end()) {
2836 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2843 template<typename M>
2844 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2849 typename M::const_iterator it = m.lower_bound(x);
2850 if (it == m.begin())
2858 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2859 DocIterator const & pos) const
2861 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2863 // if paragraphs have no macro context set, pos will be empty
2867 // we haven't found anything yet
2868 DocIterator bestPos = owner_->par_iterator_begin();
2869 MacroData const * bestData = 0;
2871 // find macro definitions for name
2872 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2873 if (nameIt != macros.end()) {
2874 // find last definition in front of pos or at pos itself
2875 PositionScopeMacroMap::const_iterator it
2876 = greatest_below(nameIt->second, pos);
2877 if (it != nameIt->second.end()) {
2879 // scope ends behind pos?
2880 if (pos < it->second.first) {
2881 // Looks good, remember this. If there
2882 // is no external macro behind this,
2883 // we found the right one already.
2884 bestPos = it->first;
2885 bestData = &it->second.second;
2889 // try previous macro if there is one
2890 if (it == nameIt->second.begin())
2897 // find macros in included files
2898 PositionScopeBufferMap::const_iterator it
2899 = greatest_below(position_to_children, pos);
2900 if (it == position_to_children.end())
2901 // no children before
2905 // do we know something better (i.e. later) already?
2906 if (it->first < bestPos )
2909 // scope ends behind pos?
2910 if (pos < it->second.first
2911 && (cloned_buffer_ ||
2912 theBufferList().isLoaded(it->second.second))) {
2913 // look for macro in external file
2915 MacroData const * data
2916 = it->second.second->getMacro(name, false);
2919 bestPos = it->first;
2925 // try previous file if there is one
2926 if (it == position_to_children.begin())
2931 // return the best macro we have found
2936 MacroData const * Buffer::getMacro(docstring const & name,
2937 DocIterator const & pos, bool global) const
2942 // query buffer macros
2943 MacroData const * data = d->getBufferMacro(name, pos);
2947 // If there is a master buffer, query that
2948 Buffer const * const pbuf = d->parent();
2950 d->macro_lock = true;
2951 MacroData const * macro = pbuf->getMacro(
2952 name, *this, false);
2953 d->macro_lock = false;
2959 data = MacroTable::globalMacros().get(name);
2968 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2970 // set scope end behind the last paragraph
2971 DocIterator scope = par_iterator_begin();
2972 scope.pit() = scope.lastpit() + 1;
2974 return getMacro(name, scope, global);
2978 MacroData const * Buffer::getMacro(docstring const & name,
2979 Buffer const & child, bool global) const
2981 // look where the child buffer is included first
2982 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2983 if (it == d->children_positions.end())
2986 // check for macros at the inclusion position
2987 return getMacro(name, it->second, global);
2991 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2993 pit_type const lastpit = it.lastpit();
2995 // look for macros in each paragraph
2996 while (it.pit() <= lastpit) {
2997 Paragraph & par = it.paragraph();
2999 // iterate over the insets of the current paragraph
3000 InsetList const & insets = par.insetList();
3001 InsetList::const_iterator iit = insets.begin();
3002 InsetList::const_iterator end = insets.end();
3003 for (; iit != end; ++iit) {
3004 it.pos() = iit->pos;
3006 // is it a nested text inset?
3007 if (iit->inset->asInsetText()) {
3008 // Inset needs its own scope?
3009 InsetText const * itext = iit->inset->asInsetText();
3010 bool newScope = itext->isMacroScope();
3012 // scope which ends just behind the inset
3013 DocIterator insetScope = it;
3016 // collect macros in inset
3017 it.push_back(CursorSlice(*iit->inset));
3018 updateMacros(it, newScope ? insetScope : scope);
3023 if (iit->inset->asInsetTabular()) {
3024 CursorSlice slice(*iit->inset);
3025 size_t const numcells = slice.nargs();
3026 for (; slice.idx() < numcells; slice.forwardIdx()) {
3027 it.push_back(slice);
3028 updateMacros(it, scope);
3034 // is it an external file?
3035 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3036 // get buffer of external file
3037 InsetInclude const & inset =
3038 static_cast<InsetInclude const &>(*iit->inset);
3040 Buffer * child = inset.getChildBuffer();
3045 // register its position, but only when it is
3046 // included first in the buffer
3047 if (children_positions.find(child) ==
3048 children_positions.end())
3049 children_positions[child] = it;
3051 // register child with its scope
3052 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3056 InsetMath * im = iit->inset->asInsetMath();
3057 if (doing_export && im) {
3058 InsetMathHull * hull = im->asHullInset();
3060 hull->recordLocation(it);
3063 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3067 MathMacroTemplate & macroTemplate =
3068 *iit->inset->asInsetMath()->asMacroTemplate();
3069 MacroContext mc(owner_, it);
3070 macroTemplate.updateToContext(mc);
3073 bool valid = macroTemplate.validMacro();
3074 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3075 // then the BufferView's cursor will be invalid in
3076 // some cases which leads to crashes.
3081 // FIXME (Abdel), I don't understandt why we pass 'it' here
3082 // instead of 'macroTemplate' defined above... is this correct?
3083 macros[macroTemplate.name()][it] =
3084 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3094 void Buffer::updateMacros() const
3099 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3101 // start with empty table
3103 d->children_positions.clear();
3104 d->position_to_children.clear();
3106 // Iterate over buffer, starting with first paragraph
3107 // The scope must be bigger than any lookup DocIterator
3108 // later. For the global lookup, lastpit+1 is used, hence
3109 // we use lastpit+2 here.
3110 DocIterator it = par_iterator_begin();
3111 DocIterator outerScope = it;
3112 outerScope.pit() = outerScope.lastpit() + 2;
3113 d->updateMacros(it, outerScope);
3117 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3119 InsetIterator it = inset_iterator_begin(inset());
3120 InsetIterator const end = inset_iterator_end(inset());
3121 for (; it != end; ++it) {
3122 if (it->lyxCode() == BRANCH_CODE) {
3123 InsetBranch & br = static_cast<InsetBranch &>(*it);
3124 docstring const name = br.branch();
3125 if (!from_master && !params().branchlist().find(name))
3126 result.push_back(name);
3127 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3128 result.push_back(name);
3131 if (it->lyxCode() == INCLUDE_CODE) {
3132 // get buffer of external file
3133 InsetInclude const & ins =
3134 static_cast<InsetInclude const &>(*it);
3135 Buffer * child = ins.getChildBuffer();
3138 child->getUsedBranches(result, true);
3141 // remove duplicates
3146 void Buffer::updateMacroInstances(UpdateType utype) const
3148 LYXERR(Debug::MACROS, "updateMacroInstances for "
3149 << d->filename.onlyFileName());
3150 DocIterator it = doc_iterator_begin(this);
3152 DocIterator const end = doc_iterator_end(this);
3153 for (; it != end; it.forwardInset()) {
3154 // look for MathData cells in InsetMathNest insets
3155 InsetMath * minset = it.nextInset()->asInsetMath();
3159 // update macro in all cells of the InsetMathNest
3160 DocIterator::idx_type n = minset->nargs();
3161 MacroContext mc = MacroContext(this, it);
3162 for (DocIterator::idx_type i = 0; i < n; ++i) {
3163 MathData & data = minset->cell(i);
3164 data.updateMacros(0, mc, utype);
3170 void Buffer::listMacroNames(MacroNameSet & macros) const
3175 d->macro_lock = true;
3177 // loop over macro names
3178 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3179 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3180 for (; nameIt != nameEnd; ++nameIt)
3181 macros.insert(nameIt->first);
3183 // loop over children
3184 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3185 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3186 for (; it != end; ++it)
3187 it->first->listMacroNames(macros);
3190 Buffer const * const pbuf = d->parent();
3192 pbuf->listMacroNames(macros);
3194 d->macro_lock = false;
3198 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3200 Buffer const * const pbuf = d->parent();
3205 pbuf->listMacroNames(names);
3208 MacroNameSet::iterator it = names.begin();
3209 MacroNameSet::iterator end = names.end();
3210 for (; it != end; ++it) {
3212 MacroData const * data =
3213 pbuf->getMacro(*it, *this, false);
3215 macros.insert(data);
3217 // we cannot access the original MathMacroTemplate anymore
3218 // here to calls validate method. So we do its work here manually.
3219 // FIXME: somehow make the template accessible here.
3220 if (data->optionals() > 0)
3221 features.require("xargs");
3227 Buffer::References & Buffer::references(docstring const & label)
3230 return const_cast<Buffer *>(masterBuffer())->references(label);
3232 RefCache::iterator it = d->ref_cache_.find(label);
3233 if (it != d->ref_cache_.end())
3234 return it->second.second;
3236 static InsetLabel const * dummy_il = 0;
3237 static References const dummy_refs;
3238 it = d->ref_cache_.insert(
3239 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3240 return it->second.second;
3244 Buffer::References const & Buffer::references(docstring const & label) const
3246 return const_cast<Buffer *>(this)->references(label);
3250 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3252 masterBuffer()->d->ref_cache_[label].first = il;
3256 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3258 return masterBuffer()->d->ref_cache_[label].first;
3262 void Buffer::clearReferenceCache() const
3265 d->ref_cache_.clear();
3269 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3272 //FIXME: This does not work for child documents yet.
3273 LASSERT(code == CITE_CODE, /**/);
3275 reloadBibInfoCache();
3277 // Check if the label 'from' appears more than once
3278 BiblioInfo const & keys = masterBibInfo();
3279 BiblioInfo::const_iterator bit = keys.begin();
3280 BiblioInfo::const_iterator bend = keys.end();
3281 vector<docstring> labels;
3283 for (; bit != bend; ++bit)
3285 labels.push_back(bit->first);
3287 if (count(labels.begin(), labels.end(), from) > 1)
3290 string const paramName = "key";
3291 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3292 if (it->lyxCode() == code) {
3293 InsetCommand * inset = it->asInsetCommand();
3296 docstring const oldValue = inset->getParam(paramName);
3297 if (oldValue == from)
3298 inset->setParam(paramName, to);
3304 void Buffer::getSourceCode(odocstream & os, string const format,
3305 pit_type par_begin, pit_type par_end,
3306 OutputWhat output) const
3308 OutputParams runparams(¶ms().encoding());
3309 runparams.nice = true;
3310 runparams.flavor = params().getOutputFlavor(format);
3311 runparams.linelen = lyxrc.plaintext_linelen;
3312 // No side effect of file copying and image conversion
3313 runparams.dryrun = true;
3315 if (output == CurrentParagraph) {
3316 runparams.par_begin = par_begin;
3317 runparams.par_end = par_end;
3318 if (par_begin + 1 == par_end) {
3320 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3324 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3325 convert<docstring>(par_begin),
3326 convert<docstring>(par_end - 1))
3329 // output paragraphs
3330 if (runparams.flavor == OutputParams::LYX) {
3331 Paragraph const & par = text().paragraphs()[par_begin];
3333 depth_type dt = par.getDepth();
3334 par.write(ods, params(), dt);
3335 os << from_utf8(ods.str());
3336 } else if (runparams.flavor == OutputParams::HTML) {
3338 setMathFlavor(runparams);
3339 xhtmlParagraphs(text(), *this, xs, runparams);
3340 } else if (runparams.flavor == OutputParams::TEXT) {
3342 // FIXME Handles only one paragraph, unlike the others.
3343 // Probably should have some routine with a signature like them.
3344 writePlaintextParagraph(*this,
3345 text().paragraphs()[par_begin], os, runparams, dummy);
3346 } else if (params().isDocBook()) {
3347 docbookParagraphs(text(), *this, os, runparams);
3349 // If we are previewing a paragraph, even if this is the
3350 // child of some other buffer, let's cut the link here,
3351 // so that no concurring settings from the master
3352 // (e.g. branch state) interfere (see #8101).
3353 // FIXME: Add an optional "from master" perspective.
3354 d->ignore_parent = true;
3355 // We need to validate the Buffer params' features here
3356 // in order to know if we should output polyglossia
3357 // macros (instead of babel macros)
3358 LaTeXFeatures features(*this, params(), runparams);
3359 params().validate(features);
3360 runparams.use_polyglossia = features.usePolyglossia();
3365 // latex or literate
3366 otexstream ots(os, texrow);
3369 latexParagraphs(*this, text(), ots, runparams);
3371 // Restore the parenthood
3372 d->ignore_parent = false;
3376 if (output == FullSource)
3377 os << _("Preview source code");
3378 else if (output == OnlyPreamble)
3379 os << _("Preview preamble");
3380 else if (output == OnlyBody)
3381 os << _("Preview body");
3383 if (runparams.flavor == OutputParams::LYX) {
3385 if (output == FullSource)
3387 else if (output == OnlyPreamble)
3388 params().writeFile(ods);
3389 else if (output == OnlyBody)
3391 os << from_utf8(ods.str());
3392 } else if (runparams.flavor == OutputParams::HTML) {
3393 writeLyXHTMLSource(os, runparams, output);
3394 } else if (runparams.flavor == OutputParams::TEXT) {
3395 if (output == OnlyPreamble) {
3396 os << "% "<< _("Plain text does not have a preamble.");
3398 writePlaintextFile(*this, os, runparams);
3399 } else if (params().isDocBook()) {
3400 writeDocBookSource(os, absFileName(), runparams, output);
3402 // latex or literate
3404 d->texrow.newline();
3405 d->texrow.newline();
3406 otexstream ots(os, d->texrow);
3407 writeLaTeXSource(ots, string(), runparams, output);
3413 ErrorList & Buffer::errorList(string const & type) const
3415 return d->errorLists[type];
3419 void Buffer::updateTocItem(std::string const & type,
3420 DocIterator const & dit) const
3423 d->gui_->updateTocItem(type, dit);
3427 void Buffer::structureChanged() const
3430 d->gui_->structureChanged();
3434 void Buffer::errors(string const & err, bool from_master) const
3437 d->gui_->errors(err, from_master);
3441 void Buffer::message(docstring const & msg) const
3444 d->gui_->message(msg);
3448 void Buffer::setBusy(bool on) const
3451 d->gui_->setBusy(on);
3455 void Buffer::updateTitles() const
3458 d->wa_->updateTitles();
3462 void Buffer::resetAutosaveTimers() const
3465 d->gui_->resetAutosaveTimers();
3469 bool Buffer::hasGuiDelegate() const
3475 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3484 class AutoSaveBuffer : public ForkedProcess {
3487 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3488 : buffer_(buffer), fname_(fname) {}
3490 virtual shared_ptr<ForkedProcess> clone() const
3492 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3497 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3498 from_utf8(fname_.absFileName())));
3499 return run(DontWait);
3503 virtual int generateChild();
3505 Buffer const & buffer_;
3510 int AutoSaveBuffer::generateChild()
3512 #if defined(__APPLE__)
3513 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3514 * We should use something else like threads.
3516 * Since I do not know how to determine at run time what is the OS X
3517 * version, I just disable forking altogether for now (JMarc)
3519 pid_t const pid = -1;
3521 // tmp_ret will be located (usually) in /tmp
3522 // will that be a problem?
3523 // Note that this calls ForkedCalls::fork(), so it's
3524 // ok cross-platform.
3525 pid_t const pid = fork();
3526 // If you want to debug the autosave
3527 // you should set pid to -1, and comment out the fork.
3528 if (pid != 0 && pid != -1)
3532 // pid = -1 signifies that lyx was unable
3533 // to fork. But we will do the save
3535 bool failed = false;
3536 FileName const tmp_ret = FileName::tempName("lyxauto");
3537 if (!tmp_ret.empty()) {
3538 buffer_.writeFile(tmp_ret);
3539 // assume successful write of tmp_ret
3540 if (!tmp_ret.moveTo(fname_))
3546 // failed to write/rename tmp_ret so try writing direct
3547 if (!buffer_.writeFile(fname_)) {
3548 // It is dangerous to do this in the child,
3549 // but safe in the parent, so...
3550 if (pid == -1) // emit message signal.
3551 buffer_.message(_("Autosave failed!"));
3555 if (pid == 0) // we are the child so...
3564 FileName Buffer::getEmergencyFileName() const
3566 return FileName(d->filename.absFileName() + ".emergency");
3570 FileName Buffer::getAutosaveFileName() const
3572 // if the document is unnamed try to save in the backup dir, else
3573 // in the default document path, and as a last try in the filePath,
3574 // which will most often be the temporary directory
3577 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3578 : lyxrc.backupdir_path;
3579 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3582 string const fname = "#" + d->filename.onlyFileName() + "#";
3584 return makeAbsPath(fname, fpath);
3588 void Buffer::removeAutosaveFile() const
3590 FileName const f = getAutosaveFileName();
3596 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3598 FileName const newauto = getAutosaveFileName();
3600 if (newauto != oldauto && oldauto.exists())
3601 if (!oldauto.moveTo(newauto))
3602 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3606 bool Buffer::autoSave() const
3608 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3609 if (buf->d->bak_clean || isReadonly())
3612 message(_("Autosaving current document..."));
3613 buf->d->bak_clean = true;
3615 FileName const fname = getAutosaveFileName();
3616 if (d->cloned_buffer_) {
3617 // If this buffer is cloned, we assume that
3618 // we are running in a separate thread already.
3619 FileName const tmp_ret = FileName::tempName("lyxauto");
3620 if (!tmp_ret.empty()) {
3622 // assume successful write of tmp_ret
3623 if (tmp_ret.moveTo(fname))
3626 // failed to write/rename tmp_ret so try writing direct
3627 return writeFile(fname);
3629 /// This function is deprecated as the frontend needs to take care
3630 /// of cloning the buffer and autosaving it in another thread. It
3631 /// is still here to allow (QT_VERSION < 0x040400).
3632 AutoSaveBuffer autosave(*this, fname);
3639 // helper class, to guarantee this gets reset properly
3640 class Buffer::MarkAsExporting {
3642 MarkAsExporting(Buffer const * buf) : buf_(buf)
3644 LASSERT(buf_, /* */);
3645 buf_->setExportStatus(true);
3649 buf_->setExportStatus(false);
3652 Buffer const * const buf_;
3657 void Buffer::setExportStatus(bool e) const
3659 d->doing_export = e;
3660 ListOfBuffers clist = getDescendents();
3661 ListOfBuffers::const_iterator cit = clist.begin();
3662 ListOfBuffers::const_iterator const cen = clist.end();
3663 for (; cit != cen; ++cit)
3664 (*cit)->d->doing_export = e;
3668 bool Buffer::isExporting() const
3670 return d->doing_export;
3674 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3678 return doExport(target, put_in_tempdir, result_file);
3681 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3682 string & result_file) const
3684 bool const update_unincluded =
3685 params().maintain_unincluded_children
3686 && !params().getIncludedChildren().empty();
3688 // (1) export with all included children (omit \includeonly)
3689 if (update_unincluded) {
3690 ExportStatus const status =
3691 doExport(target, put_in_tempdir, true, result_file);
3692 if (status != ExportSuccess)
3695 // (2) export with included children only
3696 return doExport(target, put_in_tempdir, false, result_file);
3700 void Buffer::setMathFlavor(OutputParams & op) const
3702 switch (params().html_math_output) {
3703 case BufferParams::MathML:
3704 op.math_flavor = OutputParams::MathAsMathML;
3706 case BufferParams::HTML:
3707 op.math_flavor = OutputParams::MathAsHTML;
3709 case BufferParams::Images:
3710 op.math_flavor = OutputParams::MathAsImages;
3712 case BufferParams::LaTeX:
3713 op.math_flavor = OutputParams::MathAsLaTeX;
3719 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3720 bool includeall, string & result_file) const
3722 LYXERR(Debug::FILES, "target=" << target);
3723 OutputParams runparams(¶ms().encoding());
3724 string format = target;
3725 string dest_filename;
3726 size_t pos = target.find(' ');
3727 if (pos != string::npos) {
3728 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3729 format = target.substr(0, pos);
3730 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3731 FileName(dest_filename).onlyPath().createPath();
3732 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3734 MarkAsExporting exporting(this);
3735 string backend_format;
3736 runparams.flavor = OutputParams::LATEX;
3737 runparams.linelen = lyxrc.plaintext_linelen;
3738 runparams.includeall = includeall;
3739 vector<string> backs = params().backends();
3740 Converters converters = theConverters();
3741 bool need_nice_file = false;
3742 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3743 // Get shortest path to format
3744 converters.buildGraph();
3745 Graph::EdgePath path;
3746 for (vector<string>::const_iterator it = backs.begin();
3747 it != backs.end(); ++it) {
3748 Graph::EdgePath p = converters.getPath(*it, format);
3749 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3750 backend_format = *it;
3755 if (!put_in_tempdir) {
3756 // Only show this alert if this is an export to a non-temporary
3757 // file (not for previewing).
3758 Alert::error(_("Couldn't export file"), bformat(
3759 _("No information for exporting the format %1$s."),
3760 formats.prettyName(format)));
3762 return ExportNoPathToFormat;
3764 runparams.flavor = converters.getFlavor(path, this);
3765 Graph::EdgePath::const_iterator it = path.begin();
3766 Graph::EdgePath::const_iterator en = path.end();
3767 for (; it != en; ++it)
3768 if (theConverters().get(*it).nice) {
3769 need_nice_file = true;
3774 backend_format = format;
3775 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3776 // FIXME: Don't hardcode format names here, but use a flag
3777 if (backend_format == "pdflatex")
3778 runparams.flavor = OutputParams::PDFLATEX;
3779 else if (backend_format == "luatex")
3780 runparams.flavor = OutputParams::LUATEX;
3781 else if (backend_format == "dviluatex")
3782 runparams.flavor = OutputParams::DVILUATEX;
3783 else if (backend_format == "xetex")
3784 runparams.flavor = OutputParams::XETEX;
3787 string filename = latexName(false);
3788 filename = addName(temppath(), filename);
3789 filename = changeExtension(filename,
3790 formats.extension(backend_format));
3791 LYXERR(Debug::FILES, "filename=" << filename);
3793 // Plain text backend
3794 if (backend_format == "text") {
3795 runparams.flavor = OutputParams::TEXT;
3796 writePlaintextFile(*this, FileName(filename), runparams);
3799 else if (backend_format == "xhtml") {
3800 runparams.flavor = OutputParams::HTML;
3801 setMathFlavor(runparams);
3802 makeLyXHTMLFile(FileName(filename), runparams);
3803 } else if (backend_format == "lyx")
3804 writeFile(FileName(filename));
3806 else if (params().isDocBook()) {
3807 runparams.nice = !put_in_tempdir;
3808 makeDocBookFile(FileName(filename), runparams);
3811 else if (backend_format == format || need_nice_file) {
3812 runparams.nice = true;
3813 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3814 if (d->cloned_buffer_)
3815 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3818 } else if (!lyxrc.tex_allows_spaces
3819 && contains(filePath(), ' ')) {
3820 Alert::error(_("File name error"),
3821 _("The directory path to the document cannot contain spaces."));
3822 return ExportTexPathHasSpaces;
3824 runparams.nice = false;
3825 bool const success = makeLaTeXFile(
3826 FileName(filename), filePath(), runparams);
3827 if (d->cloned_buffer_)
3828 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3833 string const error_type = (format == "program")
3834 ? "Build" : params().bufferFormat();
3835 ErrorList & error_list = d->errorLists[error_type];
3836 string const ext = formats.extension(format);
3837 FileName const tmp_result_file(changeExtension(filename, ext));
3838 bool const success = converters.convert(this, FileName(filename),
3839 tmp_result_file, FileName(absFileName()), backend_format, format,
3842 // Emit the signal to show the error list or copy it back to the
3843 // cloned Buffer so that it can be emitted afterwards.
3844 if (format != backend_format) {
3845 if (d->cloned_buffer_) {
3846 d->cloned_buffer_->d->errorLists[error_type] =
3847 d->errorLists[error_type];
3850 // also to the children, in case of master-buffer-view
3851 ListOfBuffers clist = getDescendents();
3852 ListOfBuffers::const_iterator cit = clist.begin();
3853 ListOfBuffers::const_iterator const cen = clist.end();
3854 for (; cit != cen; ++cit) {
3855 if (d->cloned_buffer_) {
3856 // Enable reverse search by copying back the
3857 // texrow object to the cloned buffer.
3858 // FIXME: this is not thread safe.
3859 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3860 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3861 (*cit)->d->errorLists[error_type];
3863 (*cit)->errors(error_type, true);
3867 if (d->cloned_buffer_) {
3868 // Enable reverse dvi or pdf to work by copying back the texrow
3869 // object to the cloned buffer.
3870 // FIXME: There is a possibility of concurrent access to texrow
3871 // here from the main GUI thread that should be securized.
3872 d->cloned_buffer_->d->texrow = d->texrow;
3873 string const error_type = params().bufferFormat();
3874 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3878 return ExportConverterError;
3880 if (put_in_tempdir) {
3881 result_file = tmp_result_file.absFileName();
3882 return ExportSuccess;
3885 if (dest_filename.empty())
3886 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3888 result_file = dest_filename;
3889 // We need to copy referenced files (e. g. included graphics
3890 // if format == "dvi") to the result dir.
3891 vector<ExportedFile> const files =
3892 runparams.exportdata->externalFiles(format);
3893 string const dest = runparams.export_folder.empty() ?
3894 onlyPath(result_file) : runparams.export_folder;
3895 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3896 : force_overwrite == ALL_FILES;
3897 CopyStatus status = use_force ? FORCE : SUCCESS;
3899 vector<ExportedFile>::const_iterator it = files.begin();
3900 vector<ExportedFile>::const_iterator const en = files.end();
3901 for (; it != en && status != CANCEL; ++it) {
3902 string const fmt = formats.getFormatFromFile(it->sourceName);
3903 string fixedName = it->exportName;
3904 if (!runparams.export_folder.empty()) {
3905 // Relative pathnames starting with ../ will be sanitized
3906 // if exporting to a different folder
3907 while (fixedName.substr(0, 3) == "../")
3908 fixedName = fixedName.substr(3, fixedName.length() - 3);
3910 FileName fixedFileName = makeAbsPath(fixedName, dest);
3911 fixedFileName.onlyPath().createPath();
3912 status = copyFile(fmt, it->sourceName,
3914 it->exportName, status == FORCE,
3915 runparams.export_folder.empty());
3918 if (status == CANCEL) {
3919 message(_("Document export cancelled."));
3920 return ExportCancel;
3923 if (tmp_result_file.exists()) {
3924 // Finally copy the main file
3925 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3926 : force_overwrite != NO_FILES;
3927 if (status == SUCCESS && use_force)
3929 status = copyFile(format, tmp_result_file,
3930 FileName(result_file), result_file,
3932 if (status == CANCEL) {
3933 message(_("Document export cancelled."));
3934 return ExportCancel;
3936 message(bformat(_("Document exported as %1$s "
3938 formats.prettyName(format),
3939 makeDisplayPath(result_file)));
3942 // This must be a dummy converter like fax (bug 1888)
3943 message(bformat(_("Document exported as %1$s"),
3944 formats.prettyName(format)));
3947 return ExportSuccess;
3951 Buffer::ExportStatus Buffer::preview(string const & format) const
3953 bool const update_unincluded =
3954 params().maintain_unincluded_children
3955 && !params().getIncludedChildren().empty();
3956 return preview(format, update_unincluded);
3959 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3961 MarkAsExporting exporting(this);
3963 // (1) export with all included children (omit \includeonly)
3965 ExportStatus const status = doExport(format, true, true, result_file);
3966 if (status != ExportSuccess)
3969 // (2) export with included children only
3970 ExportStatus const status = doExport(format, true, false, result_file);
3971 if (status != ExportSuccess)
3973 if (!formats.view(*this, FileName(result_file), format))
3974 return PreviewError;
3975 return PreviewSuccess;
3979 Buffer::ReadStatus Buffer::extractFromVC()
3981 bool const found = LyXVC::file_not_found_hook(d->filename);
3983 return ReadFileNotFound;
3984 if (!d->filename.isReadableFile())
3990 Buffer::ReadStatus Buffer::loadEmergency()
3992 FileName const emergencyFile = getEmergencyFileName();
3993 if (!emergencyFile.exists()
3994 || emergencyFile.lastModified() <= d->filename.lastModified())
3995 return ReadFileNotFound;
3997 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3998 docstring const text = bformat(_("An emergency save of the document "
3999 "%1$s exists.\n\nRecover emergency save?"), file);
4001 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4002 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4008 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4009 bool const success = (ret_llf == ReadSuccess);
4012 Alert::warning(_("File is read-only"),
4013 bformat(_("An emergency file is successfully loaded, "
4014 "but the original file %1$s is marked read-only. "
4015 "Please make sure to save the document as a different "
4016 "file."), from_utf8(d->filename.absFileName())));
4019 str = _("Document was successfully recovered.");
4021 str = _("Document was NOT successfully recovered.");
4022 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4023 makeDisplayPath(emergencyFile.absFileName()));
4025 int const del_emerg =
4026 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4027 _("&Remove"), _("&Keep"));
4028 if (del_emerg == 0) {
4029 emergencyFile.removeFile();
4031 Alert::warning(_("Emergency file deleted"),
4032 _("Do not forget to save your file now!"), true);
4034 return success ? ReadSuccess : ReadEmergencyFailure;
4037 int const del_emerg =
4038 Alert::prompt(_("Delete emergency file?"),
4039 _("Remove emergency file now?"), 1, 1,
4040 _("&Remove"), _("&Keep"));
4042 emergencyFile.removeFile();
4043 return ReadOriginal;
4053 Buffer::ReadStatus Buffer::loadAutosave()
4055 // Now check if autosave file is newer.
4056 FileName const autosaveFile = getAutosaveFileName();
4057 if (!autosaveFile.exists()
4058 || autosaveFile.lastModified() <= d->filename.lastModified())
4059 return ReadFileNotFound;
4061 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4062 docstring const text = bformat(_("The backup of the document %1$s "
4063 "is newer.\n\nLoad the backup instead?"), file);
4064 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4065 _("&Load backup"), _("Load &original"), _("&Cancel"));
4070 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4071 // the file is not saved if we load the autosave file.
4072 if (ret_llf == ReadSuccess) {
4074 Alert::warning(_("File is read-only"),
4075 bformat(_("A backup file is successfully loaded, "
4076 "but the original file %1$s is marked read-only. "
4077 "Please make sure to save the document as a "
4079 from_utf8(d->filename.absFileName())));
4084 return ReadAutosaveFailure;
4087 // Here we delete the autosave
4088 autosaveFile.removeFile();
4089 return ReadOriginal;
4097 Buffer::ReadStatus Buffer::loadLyXFile()
4099 if (!d->filename.isReadableFile()) {
4100 ReadStatus const ret_rvc = extractFromVC();
4101 if (ret_rvc != ReadSuccess)
4105 ReadStatus const ret_re = loadEmergency();
4106 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4109 ReadStatus const ret_ra = loadAutosave();
4110 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4113 return loadThisLyXFile(d->filename);
4117 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4119 return readFile(fn);
4123 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4125 TeXErrors::Errors::const_iterator it = terr.begin();
4126 TeXErrors::Errors::const_iterator end = terr.end();
4127 ListOfBuffers clist = getDescendents();
4128 ListOfBuffers::const_iterator cen = clist.end();
4130 for (; it != end; ++it) {
4133 int errorRow = it->error_in_line;
4134 Buffer const * buf = 0;
4136 if (it->child_name.empty())
4137 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4139 // The error occurred in a child
4140 ListOfBuffers::const_iterator cit = clist.begin();
4141 for (; cit != cen; ++cit) {
4142 string const child_name =
4143 DocFileName(changeExtension(
4144 (*cit)->absFileName(), "tex")).
4146 if (it->child_name != child_name)
4148 (*cit)->d->texrow.getIdFromRow(errorRow,
4149 id_start, pos_start);
4150 if (id_start != -1) {
4151 buf = d->cloned_buffer_
4152 ? (*cit)->d->cloned_buffer_->d->owner_
4153 : (*cit)->d->owner_;
4164 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4165 } while (found && id_start == id_end && pos_start == pos_end);
4167 if (id_start != id_end) {
4168 // Next registered position is outside the inset where
4169 // the error occurred, so signal end-of-paragraph
4173 errorList.push_back(ErrorItem(it->error_desc,
4174 it->error_text, id_start, pos_start, pos_end, buf));
4179 void Buffer::setBuffersForInsets() const
4181 inset().setBuffer(const_cast<Buffer &>(*this));
4185 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4187 // Use the master text class also for child documents
4188 Buffer const * const master = masterBuffer();
4189 DocumentClass const & textclass = master->params().documentClass();
4191 // do this only if we are the top-level Buffer
4193 reloadBibInfoCache();
4195 // keep the buffers to be children in this set. If the call from the
4196 // master comes back we can see which of them were actually seen (i.e.
4197 // via an InsetInclude). The remaining ones in the set need still be updated.
4198 static std::set<Buffer const *> bufToUpdate;
4199 if (scope == UpdateMaster) {
4200 // If this is a child document start with the master
4201 if (master != this) {
4202 bufToUpdate.insert(this);
4203 master->updateBuffer(UpdateMaster, utype);
4204 // Do this here in case the master has no gui associated with it. Then,
4205 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4206 if (!master->d->gui_)
4209 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4210 if (bufToUpdate.find(this) == bufToUpdate.end())
4214 // start over the counters in the master
4215 textclass.counters().reset();
4218 // update will be done below for this buffer
4219 bufToUpdate.erase(this);
4221 // update all caches
4222 clearReferenceCache();
4225 Buffer & cbuf = const_cast<Buffer &>(*this);
4227 LASSERT(!text().paragraphs().empty(), /**/);
4230 ParIterator parit = cbuf.par_iterator_begin();
4231 updateBuffer(parit, utype);
4234 // TocBackend update will be done later.
4237 d->bibinfo_cache_valid_ = true;
4238 d->cite_labels_valid_ = true;
4239 cbuf.tocBackend().update();
4240 if (scope == UpdateMaster)
4241 cbuf.structureChanged();
4245 static depth_type getDepth(DocIterator const & it)
4247 depth_type depth = 0;
4248 for (size_t i = 0 ; i < it.depth() ; ++i)
4249 if (!it[i].inset().inMathed())
4250 depth += it[i].paragraph().getDepth() + 1;
4251 // remove 1 since the outer inset does not count
4255 static depth_type getItemDepth(ParIterator const & it)
4257 Paragraph const & par = *it;
4258 LabelType const labeltype = par.layout().labeltype;
4260 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4263 // this will hold the lowest depth encountered up to now.
4264 depth_type min_depth = getDepth(it);
4265 ParIterator prev_it = it;
4268 --prev_it.top().pit();
4270 // start of nested inset: go to outer par
4272 if (prev_it.empty()) {
4273 // start of document: nothing to do
4278 // We search for the first paragraph with same label
4279 // that is not more deeply nested.
4280 Paragraph & prev_par = *prev_it;
4281 depth_type const prev_depth = getDepth(prev_it);
4282 if (labeltype == prev_par.layout().labeltype) {
4283 if (prev_depth < min_depth)
4284 return prev_par.itemdepth + 1;
4285 if (prev_depth == min_depth)
4286 return prev_par.itemdepth;
4288 min_depth = min(min_depth, prev_depth);
4289 // small optimization: if we are at depth 0, we won't
4290 // find anything else
4291 if (prev_depth == 0)
4297 static bool needEnumCounterReset(ParIterator const & it)
4299 Paragraph const & par = *it;
4300 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4301 depth_type const cur_depth = par.getDepth();
4302 ParIterator prev_it = it;
4303 while (prev_it.pit()) {
4304 --prev_it.top().pit();
4305 Paragraph const & prev_par = *prev_it;
4306 if (prev_par.getDepth() <= cur_depth)
4307 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4309 // start of nested inset: reset
4314 // set the label of a paragraph. This includes the counters.
4315 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4317 BufferParams const & bp = owner_->masterBuffer()->params();
4318 DocumentClass const & textclass = bp.documentClass();
4319 Paragraph & par = it.paragraph();
4320 Layout const & layout = par.layout();
4321 Counters & counters = textclass.counters();
4323 if (par.params().startOfAppendix()) {
4324 // We want to reset the counter corresponding to toplevel sectioning
4325 Layout const & lay = textclass.getTOCLayout();
4326 docstring const cnt = lay.counter;
4328 counters.reset(cnt);
4329 counters.appendix(true);
4331 par.params().appendix(counters.appendix());
4333 // Compute the item depth of the paragraph
4334 par.itemdepth = getItemDepth(it);
4336 if (layout.margintype == MARGIN_MANUAL) {
4337 if (par.params().labelWidthString().empty())
4338 par.params().labelWidthString(par.expandLabel(layout, bp));
4339 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4340 // we do not need to do anything here, since the empty case is
4341 // handled during export.
4343 par.params().labelWidthString(docstring());
4346 switch(layout.labeltype) {
4348 if (layout.toclevel <= bp.secnumdepth
4349 && (layout.latextype != LATEX_ENVIRONMENT
4350 || it.text()->isFirstInSequence(it.pit()))) {
4351 if (counters.hasCounter(layout.counter))
4352 counters.step(layout.counter, utype);
4353 par.params().labelString(par.expandLabel(layout, bp));
4355 par.params().labelString(docstring());
4358 case LABEL_ITEMIZE: {
4359 // At some point of time we should do something more
4360 // clever here, like:
4361 // par.params().labelString(
4362 // bp.user_defined_bullet(par.itemdepth).getText());
4363 // for now, use a simple hardcoded label
4364 docstring itemlabel;
4365 switch (par.itemdepth) {
4367 itemlabel = char_type(0x2022);
4370 itemlabel = char_type(0x2013);
4373 itemlabel = char_type(0x2217);
4376 itemlabel = char_type(0x2219); // or 0x00b7
4379 par.params().labelString(itemlabel);
4383 case LABEL_ENUMERATE: {
4384 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4386 switch (par.itemdepth) {
4395 enumcounter += "iv";
4398 // not a valid enumdepth...
4402 // Maybe we have to reset the enumeration counter.
4403 if (needEnumCounterReset(it))
4404 counters.reset(enumcounter);
4405 counters.step(enumcounter, utype);
4407 string const & lang = par.getParLanguage(bp)->code();
4408 par.params().labelString(counters.theCounter(enumcounter, lang));
4413 case LABEL_SENSITIVE: {
4414 string const & type = counters.current_float();
4415 docstring full_label;
4417 full_label = owner_->B_("Senseless!!! ");
4419 docstring name = owner_->B_(textclass.floats().getType(type).name());
4420 if (counters.hasCounter(from_utf8(type))) {
4421 string const & lang = par.getParLanguage(bp)->code();
4422 counters.step(from_utf8(type), utype);
4423 full_label = bformat(from_ascii("%1$s %2$s:"),
4425 counters.theCounter(from_utf8(type), lang));
4427 full_label = bformat(from_ascii("%1$s #:"), name);
4429 par.params().labelString(full_label);
4433 case LABEL_NO_LABEL:
4434 par.params().labelString(docstring());
4438 case LABEL_TOP_ENVIRONMENT:
4439 case LABEL_CENTERED_TOP_ENVIRONMENT:
4442 par.params().labelString(par.expandLabel(layout, bp));
4448 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4450 LASSERT(parit.pit() == 0, /**/);
4452 // Set the position of the text in the buffer to be able
4453 // to resolve macros in it.
4454 parit.text()->setMacrocontextPosition(parit);
4456 depth_type maxdepth = 0;
4457 pit_type const lastpit = parit.lastpit();
4458 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4459 // reduce depth if necessary
4460 if (parit->params().depth() > maxdepth) {
4461 /** FIXME: this function is const, but
4462 * nevertheless it modifies the buffer. To be
4463 * cleaner, one should modify the buffer in
4464 * another function, which is actually
4465 * non-const. This would however be costly in
4466 * terms of code duplication.
4468 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4469 parit->params().depth(maxdepth);
4471 maxdepth = parit->getMaxDepthAfter();
4473 if (utype == OutputUpdate) {
4474 // track the active counters
4475 // we have to do this for the master buffer, since the local
4476 // buffer isn't tracking anything.
4477 masterBuffer()->params().documentClass().counters().
4478 setActiveLayout(parit->layout());
4481 // set the counter for this paragraph
4482 d->setLabel(parit, utype);
4485 InsetList::const_iterator iit = parit->insetList().begin();
4486 InsetList::const_iterator end = parit->insetList().end();
4487 for (; iit != end; ++iit) {
4488 parit.pos() = iit->pos;
4489 iit->inset->updateBuffer(parit, utype);
4495 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4496 WordLangTuple & word_lang, docstring_list & suggestions) const
4500 suggestions.clear();
4501 word_lang = WordLangTuple();
4502 bool const to_end = to.empty();
4503 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4504 // OK, we start from here.
4505 for (; from != end; from.forwardPos()) {
4506 // We are only interested in text so remove the math CursorSlice.
4507 while (from.inMathed()) {
4511 // If from is at the end of the document (which is possible
4512 // when leaving the mathed) LyX will crash later otherwise.
4513 if (from.atEnd() || (!to_end && from >= end))
4516 from.paragraph().spellCheck();
4517 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4518 if (SpellChecker::misspelled(res)) {
4523 // Do not increase progress when from == to, otherwise the word
4524 // count will be wrong.
4534 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4536 bool inword = false;
4541 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4542 if (!dit.inTexted()) {
4547 Paragraph const & par = dit.paragraph();
4548 pos_type const pos = dit.pos();
4550 // Copied and adapted from isWordSeparator() in Paragraph
4551 if (pos == dit.lastpos()) {
4554 Inset const * ins = par.getInset(pos);
4555 if (ins && skipNoOutput && !ins->producesOutput()) {
4558 // stop if end of range was skipped
4559 if (!to.atEnd() && dit >= to)
4562 } else if (!par.isDeleted(pos)) {
4563 if (par.isWordSeparator(pos))
4569 if (ins && ins->isLetter())
4571 else if (ins && ins->isSpace())
4574 char_type const c = par.getChar(pos);
4575 if (isPrintableNonspace(c))
4577 else if (isSpace(c))
4587 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4589 d->updateStatistics(from, to, skipNoOutput);
4593 int Buffer::wordCount() const
4595 return d->wordCount();
4599 int Buffer::charCount(bool with_blanks) const
4601 return d->charCount(with_blanks);
4605 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4608 // c.f. bug http://www.lyx.org/trac/ticket/6587
4609 removeAutosaveFile();
4610 // e.g., read-only status could have changed due to version control
4611 d->filename.refresh();
4612 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4614 // clear parent. this will get reset if need be.
4616 ReadStatus const status = loadLyXFile();
4617 if (status == ReadSuccess) {
4622 message(bformat(_("Document %1$s reloaded."), disp_fn));
4626 message(bformat(_("Could not reload document %1$s."), disp_fn));
4636 bool Buffer::saveAs(FileName const & fn)
4638 FileName const old_name = fileName();
4639 FileName const old_auto = getAutosaveFileName();
4640 bool const old_unnamed = isUnnamed();
4647 // bring the autosave file with us, just in case.
4648 moveAutosaveFile(old_auto);
4649 // validate version control data and
4650 // correct buffer title
4651 lyxvc().file_found_hook(fileName());
4653 // the file has now been saved to the new location.
4654 // we need to check that the locations of child buffers
4656 checkChildBuffers();
4657 checkMasterBuffer();
4661 // reset the old filename and unnamed state
4662 setFileName(old_name);
4663 setUnnamed(old_unnamed);
4669 // FIXME We could do better here, but it is complicated. What would be
4670 // nice is to offer either (a) to save the child buffer to an appropriate
4671 // location, so that it would "move with the master", or else (b) to update
4672 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4673 // complicated, because the code for this lives in GuiView.
4674 void Buffer::checkChildBuffers()
4676 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4677 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4678 for (; it != en; ++it) {
4679 DocIterator dit = it->second;
4680 Buffer * cbuf = const_cast<Buffer *>(it->first);
4681 if (!cbuf || !theBufferList().isLoaded(cbuf))
4683 Inset * inset = dit.nextInset();
4684 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4685 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4686 docstring const & incfile = inset_inc->getParam("filename");
4687 string oldloc = cbuf->absFileName();
4688 string newloc = makeAbsPath(to_utf8(incfile),
4689 onlyPath(absFileName())).absFileName();
4690 if (oldloc == newloc)
4692 // the location of the child file is incorrect.
4693 Alert::warning(_("Included File Invalid"),
4694 bformat(_("Saving this document to a new location has made the file:\n"
4696 "inaccessible. You will need to update the included filename."),
4697 from_utf8(oldloc)));
4699 inset_inc->setChildBuffer(0);
4701 // invalidate cache of children
4702 d->children_positions.clear();
4703 d->position_to_children.clear();
4707 // If a child has been saved under a different name/path, it might have been
4708 // orphaned. Therefore the master needs to be reset (bug 8161).
4709 void Buffer::checkMasterBuffer()
4711 Buffer const * const master = masterBuffer();
4715 // necessary to re-register the child (bug 5873)
4716 // FIXME: clean up updateMacros (here, only
4717 // child registering is needed).
4718 master->updateMacros();
4719 // (re)set master as master buffer, but only
4720 // if we are a real child
4721 if (master->isChild(this))