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"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 401; // Ronen: support for \Diagram
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);
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 /** If we have branches that use the file suffix
171 feature, return the file name with suffix appended.
173 support::FileName exportFileName() const;
180 mutable TexRow texrow;
182 /// need to regenerate .tex?
186 mutable bool lyx_clean;
188 /// is autosave needed?
189 mutable bool bak_clean;
191 /// is this a unnamed file (New...)?
197 /// name of the file the buffer is associated with.
200 /** Set to true only when the file is fully loaded.
201 * Used to prevent the premature generation of previews
202 * and by the citation inset.
204 bool file_fully_loaded;
207 mutable TocBackend toc_backend;
210 typedef pair<DocIterator, MacroData> ScopeMacro;
211 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
212 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
213 /// map from the macro name to the position map,
214 /// which maps the macro definition position to the scope and the MacroData.
215 NamePositionScopeMacroMap macros;
216 /// This seem to change the way Buffer::getMacro() works
217 mutable bool macro_lock;
219 /// positions of child buffers in the buffer
220 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
221 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
222 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
223 /// position of children buffers in this buffer
224 BufferPositionMap children_positions;
225 /// map from children inclusion positions to their scope and their buffer
226 PositionScopeBufferMap position_to_children;
228 /// Container for all sort of Buffer dependant errors.
229 map<string, ErrorList> errorLists;
231 /// timestamp and checksum used to test if the file has been externally
232 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
234 unsigned long checksum_;
237 frontend::WorkAreaManager * wa_;
239 frontend::GuiBufferDelegate * gui_;
244 /// A cache for the bibfiles (including bibfiles of loaded child
245 /// documents), needed for appropriate update of natbib labels.
246 mutable support::FileNameList bibfiles_cache_;
248 // FIXME The caching mechanism could be improved. At present, we have a
249 // cache for each Buffer, that caches all the bibliography info for that
250 // Buffer. A more efficient solution would be to have a global cache per
251 // file, and then to construct the Buffer's bibinfo from that.
252 /// A cache for bibliography info
253 mutable BiblioInfo bibinfo_;
254 /// whether the bibinfo cache is valid
255 mutable bool bibinfo_cache_valid_;
256 /// whether the bibfile cache is valid
257 mutable bool bibfile_cache_valid_;
258 /// Cache of timestamps of .bib files
259 map<FileName, time_t> bibfile_status_;
261 mutable RefCache ref_cache_;
263 /// our Text that should be wrapped in an InsetText
266 /// This is here to force the test to be done whenever parent_buffer
268 Buffer const * parent() const {
269 // if parent_buffer is not loaded, then it has been unloaded,
270 // which means that parent_buffer is an invalid pointer. So we
271 // set it to null in that case.
272 // however, the BufferList doesn't know about cloned buffers, so
273 // they will always be regarded as unloaded. in that case, we hope
275 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
277 return parent_buffer;
281 void setParent(Buffer const * pb) {
282 if (parent_buffer == pb)
285 if (!cloned_buffer_ && parent_buffer && pb)
286 LYXERR0("Warning: a buffer should not have two parents!");
288 if (!cloned_buffer_ && parent_buffer) {
289 parent_buffer->invalidateBibfileCache();
290 parent_buffer->invalidateBibinfoCache();
294 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
295 /// This one is useful for preview detached in a thread.
296 Buffer const * cloned_buffer_;
297 /// are we in the process of exporting this buffer?
298 mutable bool doing_export;
301 /// So we can force access via the accessors.
302 mutable Buffer const * parent_buffer;
307 /// Creates the per buffer temporary directory
308 static FileName createBufferTmpDir()
311 // We are in our own directory. Why bother to mangle name?
312 // In fact I wrote this code to circumvent a problematic behaviour
313 // (bug?) of EMX mkstemp().
314 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
315 convert<string>(count++));
317 if (!tmpfl.createDirectory(0777)) {
318 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
319 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
320 from_utf8(tmpfl.absFileName())));
326 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
327 Buffer const * cloned_buffer)
328 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
329 read_only(readonly_), filename(file), file_fully_loaded(false),
330 toc_backend(owner), macro_lock(false), timestamp_(0),
331 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
332 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
333 doing_export(false), parent_buffer(0)
335 if (!cloned_buffer_) {
336 temppath = createBufferTmpDir();
337 lyxvc.setBuffer(owner_);
339 wa_ = new frontend::WorkAreaManager;
342 temppath = cloned_buffer_->d->temppath;
343 file_fully_loaded = true;
344 params = cloned_buffer_->d->params;
345 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
346 bibinfo_ = cloned_buffer_->d->bibinfo_;
347 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
348 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
349 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
353 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
354 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
356 LYXERR(Debug::INFO, "Buffer::Buffer()");
358 d->inset = new InsetText(*cloned_buffer->d->inset);
359 d->inset->setBuffer(*this);
360 // FIXME: optimize this loop somewhat, maybe by creating a new
361 // general recursive Inset::setId().
362 DocIterator it = doc_iterator_begin(this);
363 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
364 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
365 it.paragraph().setId(cloned_it.paragraph().id());
367 d->inset = new InsetText(this);
368 d->inset->setAutoBreakRows(true);
369 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
375 LYXERR(Debug::INFO, "Buffer::~Buffer()");
376 // here the buffer should take care that it is
377 // saved properly, before it goes into the void.
379 // GuiView already destroyed
383 // No need to do additional cleanups for internal buffer.
388 // loop over children
389 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
390 Impl::BufferPositionMap::iterator end = d->children_positions.end();
391 for (; it != end; ++it) {
392 Buffer * child = const_cast<Buffer *>(it->first);
393 if (d->cloned_buffer_)
395 // The child buffer might have been closed already.
396 else if (theBufferList().isLoaded(child))
397 theBufferList().releaseChild(this, child);
401 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
402 msg += emergencyWrite();
403 Alert::warning(_("Attempting to close changed document!"), msg);
406 // clear references to children in macro tables
407 d->children_positions.clear();
408 d->position_to_children.clear();
410 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
411 Alert::warning(_("Could not remove temporary directory"),
412 bformat(_("Could not remove the temporary directory %1$s"),
413 from_utf8(d->temppath.absFileName())));
416 // Remove any previewed LaTeX snippets associated with this buffer.
418 thePreviews().removeLoader(*this);
424 Buffer * Buffer::clone() const
426 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
427 buffer_clone->d->macro_lock = true;
428 buffer_clone->d->children_positions.clear();
429 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
430 // math macro caches need to be rethought and simplified.
431 // I am not sure wether we should handle Buffer cloning here or in BufferList.
432 // Right now BufferList knows nothing about buffer clones.
433 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
434 Impl::BufferPositionMap::iterator end = d->children_positions.end();
435 for (; it != end; ++it) {
436 DocIterator dit = it->second.clone(buffer_clone);
437 dit.setBuffer(buffer_clone);
438 Buffer * child = const_cast<Buffer *>(it->first);
439 Buffer * child_clone = child->clone();
440 Inset * inset = dit.nextInset();
441 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
442 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
443 inset_inc->setChildBuffer(child_clone);
444 child_clone->d->setParent(buffer_clone);
445 buffer_clone->setChild(dit, child_clone);
447 buffer_clone->d->macro_lock = false;
452 bool Buffer::isClone() const
454 return d->cloned_buffer_;
458 void Buffer::changed(bool update_metrics) const
461 d->wa_->redrawAll(update_metrics);
465 frontend::WorkAreaManager & Buffer::workAreaManager() const
467 LASSERT(d->wa_, /**/);
472 Text & Buffer::text() const
474 return d->inset->text();
478 Inset & Buffer::inset() const
484 BufferParams & Buffer::params()
490 BufferParams const & Buffer::params() const
496 ParagraphList & Buffer::paragraphs()
498 return text().paragraphs();
502 ParagraphList const & Buffer::paragraphs() const
504 return text().paragraphs();
508 LyXVC & Buffer::lyxvc()
514 LyXVC const & Buffer::lyxvc() const
520 string const Buffer::temppath() const
522 return d->temppath.absFileName();
526 TexRow & Buffer::texrow()
532 TexRow const & Buffer::texrow() const
538 TocBackend & Buffer::tocBackend() const
540 return d->toc_backend;
544 Undo & Buffer::undo()
550 void Buffer::setChild(DocIterator const & dit, Buffer * child)
552 d->children_positions[child] = dit;
556 string Buffer::latexName(bool const no_path) const
558 FileName latex_name =
559 makeLatexName(d->exportFileName());
560 return no_path ? latex_name.onlyFileName()
561 : latex_name.absFileName();
565 FileName Buffer::Impl::exportFileName() const
567 docstring const branch_suffix =
568 params.branchlist().getFileNameSuffix();
569 if (branch_suffix.empty())
572 string const name = filename.onlyFileNameWithoutExt()
573 + to_utf8(branch_suffix);
574 FileName res(filename.onlyPath().absFileName() + "/" + name);
575 res.changeExtension(filename.extension());
581 string Buffer::logName(LogType * type) const
583 string const filename = latexName(false);
585 if (filename.empty()) {
591 string const path = temppath();
593 FileName const fname(addName(temppath(),
594 onlyFileName(changeExtension(filename,
597 // FIXME: how do we know this is the name of the build log?
598 FileName const bname(
599 addName(path, onlyFileName(
600 changeExtension(filename,
601 formats.extension(bufferFormat()) + ".out"))));
603 // Also consider the master buffer log file
604 FileName masterfname = fname;
606 if (masterBuffer() != this) {
607 string const mlogfile = masterBuffer()->logName(&mtype);
608 masterfname = FileName(mlogfile);
611 // If no Latex log or Build log is newer, show Build log
612 if (bname.exists() &&
613 ((!fname.exists() && !masterfname.exists())
614 || (fname.lastModified() < bname.lastModified()
615 && masterfname.lastModified() < bname.lastModified()))) {
616 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
619 return bname.absFileName();
620 // If we have a newer master file log or only a master log, show this
621 } else if (fname != masterfname
622 && (!fname.exists() && (masterfname.exists()
623 || fname.lastModified() < masterfname.lastModified()))) {
624 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
627 return masterfname.absFileName();
629 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
632 return fname.absFileName();
636 void Buffer::setReadonly(bool const flag)
638 if (d->read_only != flag) {
645 void Buffer::setFileName(string const & newfile)
647 d->filename = makeAbsPath(newfile);
648 setReadonly(d->filename.isReadOnly());
653 int Buffer::readHeader(Lexer & lex)
655 int unknown_tokens = 0;
657 int begin_header_line = -1;
659 // Initialize parameters that may be/go lacking in header:
660 params().branchlist().clear();
661 params().preamble.erase();
662 params().options.erase();
663 params().master.erase();
664 params().float_placement.erase();
665 params().paperwidth.erase();
666 params().paperheight.erase();
667 params().leftmargin.erase();
668 params().rightmargin.erase();
669 params().topmargin.erase();
670 params().bottommargin.erase();
671 params().headheight.erase();
672 params().headsep.erase();
673 params().footskip.erase();
674 params().columnsep.erase();
675 params().fontsCJK.erase();
676 params().listings_params.clear();
677 params().clearLayoutModules();
678 params().clearRemovedModules();
679 params().clearIncludedChildren();
680 params().pdfoptions().clear();
681 params().indiceslist().clear();
682 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
683 params().isbackgroundcolor = false;
684 params().fontcolor = lyx::rgbFromHexName("#000000");
685 params().isfontcolor = false;
686 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
687 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
688 params().html_latex_start.clear();
689 params().html_latex_end.clear();
690 params().html_math_img_scale = 1.0;
691 params().output_sync_macro.erase();
693 for (int i = 0; i < 4; ++i) {
694 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
695 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
698 ErrorList & errorList = d->errorLists["Parse"];
707 if (token == "\\end_header")
711 if (token == "\\begin_header") {
712 begin_header_line = line;
716 LYXERR(Debug::PARSER, "Handling document header token: `"
719 string unknown = params().readToken(lex, token, d->filename.onlyPath());
720 if (!unknown.empty()) {
721 if (unknown[0] != '\\' && token == "\\textclass") {
722 Alert::warning(_("Unknown document class"),
723 bformat(_("Using the default document class, because the "
724 "class %1$s is unknown."), from_utf8(unknown)));
727 docstring const s = bformat(_("Unknown token: "
731 errorList.push_back(ErrorItem(_("Document header error"),
736 if (begin_header_line) {
737 docstring const s = _("\\begin_header is missing");
738 errorList.push_back(ErrorItem(_("Document header error"),
742 params().makeDocumentClass();
744 return unknown_tokens;
749 // changed to be public and have one parameter
750 // Returns true if "\end_document" is not read (Asger)
751 bool Buffer::readDocument(Lexer & lex)
753 ErrorList & errorList = d->errorLists["Parse"];
756 if (!lex.checkFor("\\begin_document")) {
757 docstring const s = _("\\begin_document is missing");
758 errorList.push_back(ErrorItem(_("Document header error"),
762 // we are reading in a brand new document
763 LASSERT(paragraphs().empty(), /**/);
767 if (params().outputChanges) {
768 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
769 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
770 LaTeXFeatures::isAvailable("xcolor");
772 if (!dvipost && !xcolorulem) {
773 Alert::warning(_("Changes not shown in LaTeX output"),
774 _("Changes will not be highlighted in LaTeX output, "
775 "because neither dvipost nor xcolor/ulem are installed.\n"
776 "Please install these packages or redefine "
777 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
778 } else if (!xcolorulem) {
779 Alert::warning(_("Changes not shown in LaTeX output"),
780 _("Changes will not be highlighted in LaTeX output "
781 "when using pdflatex, because xcolor and ulem are not installed.\n"
782 "Please install both packages or redefine "
783 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
787 if (!params().master.empty()) {
788 FileName const master_file = makeAbsPath(params().master,
789 onlyPath(absFileName()));
790 if (isLyXFileName(master_file.absFileName())) {
792 checkAndLoadLyXFile(master_file, true);
794 // necessary e.g. after a reload
795 // to re-register the child (bug 5873)
796 // FIXME: clean up updateMacros (here, only
797 // child registering is needed).
798 master->updateMacros();
799 // set master as master buffer, but only
800 // if we are a real child
801 if (master->isChild(this))
803 // if the master is not fully loaded
804 // it is probably just loading this
805 // child. No warning needed then.
806 else if (master->isFullyLoaded())
807 LYXERR0("The master '"
809 << "' assigned to this document ("
811 << ") does not include "
812 "this document. Ignoring the master assignment.");
817 // assure we have a default index
818 params().indiceslist().addDefault(B_("Index"));
821 bool const res = text().read(lex, errorList, d->inset);
825 updateMacroInstances();
830 bool Buffer::readString(string const & s)
832 params().compressed = false;
834 // remove dummy empty par
835 paragraphs().clear();
839 FileName const name = FileName::tempName("Buffer_readString");
840 switch (readFile(lex, name, true)) {
844 // We need to call lyx2lyx, so write the input to a file
845 ofstream os(name.toFilesystemEncoding().c_str());
848 return readFile(name);
858 bool Buffer::readFile(FileName const & filename)
860 FileName fname(filename);
862 params().compressed = fname.isZippedFile();
864 // remove dummy empty par
865 paragraphs().clear();
868 if (readFile(lex, fname) != success)
875 bool Buffer::isFullyLoaded() const
877 return d->file_fully_loaded;
881 void Buffer::setFullyLoaded(bool value)
883 d->file_fully_loaded = value;
887 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
890 LASSERT(!filename.empty(), /**/);
892 // the first (non-comment) token _must_ be...
893 if (!lex.checkFor("\\lyxformat")) {
894 Alert::error(_("Document format failure"),
895 bformat(_("%1$s is not a readable LyX document."),
896 from_utf8(filename.absFileName())));
902 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
903 // if present remove ".," from string.
904 size_t dot = tmp_format.find_first_of(".,");
905 //lyxerr << " dot found at " << dot << endl;
906 if (dot != string::npos)
907 tmp_format.erase(dot, 1);
908 int const file_format = convert<int>(tmp_format);
909 //lyxerr << "format: " << file_format << endl;
911 // save timestamp and checksum of the original disk file, making sure
912 // to not overwrite them with those of the file created in the tempdir
913 // when it has to be converted to the current format.
915 // Save the timestamp and checksum of disk file. If filename is an
916 // emergency file, save the timestamp and checksum of the original lyx file
917 // because isExternallyModified will check for this file. (BUG4193)
918 string diskfile = filename.absFileName();
919 if (suffixIs(diskfile, ".emergency"))
920 diskfile = diskfile.substr(0, diskfile.size() - 10);
921 saveCheckSum(FileName(diskfile));
924 if (file_format != LYX_FORMAT) {
927 // lyx2lyx would fail
930 FileName const tmpfile = FileName::tempName("Buffer_readFile");
931 if (tmpfile.empty()) {
932 Alert::error(_("Conversion failed"),
933 bformat(_("%1$s is from a different"
934 " version of LyX, but a temporary"
935 " file for converting it could"
937 from_utf8(filename.absFileName())));
940 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
941 if (lyx2lyx.empty()) {
942 Alert::error(_("Conversion script not found"),
943 bformat(_("%1$s is from a different"
944 " version of LyX, but the"
945 " conversion script lyx2lyx"
946 " could not be found."),
947 from_utf8(filename.absFileName())));
950 ostringstream command;
951 command << os::python()
952 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
953 << " -t " << convert<string>(LYX_FORMAT)
954 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
955 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
956 string const command_str = command.str();
958 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
960 cmd_ret const ret = runCommand(command_str);
961 if (ret.first != 0) {
962 if (file_format < LYX_FORMAT)
963 Alert::error(_("Conversion script failed"),
964 bformat(_("%1$s is from an older version"
965 " of LyX, but the lyx2lyx script"
966 " failed to convert it."),
967 from_utf8(filename.absFileName())));
969 Alert::error(_("Conversion script failed"),
970 bformat(_("%1$s is from a newer version"
971 " of LyX and cannot be converted by the"
973 from_utf8(filename.absFileName())));
976 bool const ret = readFile(tmpfile);
977 // Do stuff with tmpfile name and buffer name here.
978 return ret ? success : failure;
983 if (readDocument(lex)) {
984 Alert::error(_("Document format failure"),
985 bformat(_("%1$s ended unexpectedly, which means"
986 " that it is probably corrupted."),
987 from_utf8(filename.absFileName())));
991 d->file_fully_loaded = true;
996 // Should probably be moved to somewhere else: BufferView? GuiView?
997 bool Buffer::save() const
999 // ask if the disk file has been externally modified (use checksum method)
1000 if (fileName().exists() && isExternallyModified(checksum_method)) {
1001 docstring const file = makeDisplayPath(absFileName(), 20);
1002 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1003 "you want to overwrite this file?"), file);
1004 int const ret = Alert::prompt(_("Overwrite modified file?"),
1005 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1010 // We don't need autosaves in the immediate future. (Asger)
1011 resetAutosaveTimers();
1013 FileName backupName;
1014 bool madeBackup = false;
1016 // make a backup if the file already exists
1017 if (lyxrc.make_backup && fileName().exists()) {
1018 backupName = FileName(absFileName() + '~');
1019 if (!lyxrc.backupdir_path.empty()) {
1020 string const mangledName =
1021 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1022 backupName = FileName(addName(lyxrc.backupdir_path,
1025 // do not copy because of #6587
1026 if (fileName().moveTo(backupName)) {
1029 Alert::error(_("Backup failure"),
1030 bformat(_("Cannot create backup file %1$s.\n"
1031 "Please check whether the directory exists and is writeable."),
1032 from_utf8(backupName.absFileName())));
1033 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1037 if (writeFile(d->filename)) {
1041 // Saving failed, so backup is not backup
1043 backupName.moveTo(d->filename);
1049 bool Buffer::writeFile(FileName const & fname) const
1051 if (d->read_only && fname == d->filename)
1054 bool retval = false;
1056 docstring const str = bformat(_("Saving document %1$s..."),
1057 makeDisplayPath(fname.absFileName()));
1060 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1062 if (params().compressed) {
1063 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1064 retval = ofs && write(ofs);
1066 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1067 retval = ofs && write(ofs);
1071 message(str + _(" could not write file!"));
1076 // removeAutosaveFile();
1078 saveCheckSum(d->filename);
1079 message(str + _(" done."));
1085 docstring Buffer::emergencyWrite()
1087 // No need to save if the buffer has not changed.
1091 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1093 docstring user_message = bformat(
1094 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1096 // We try to save three places:
1097 // 1) Same place as document. Unless it is an unnamed doc.
1099 string s = absFileName();
1102 if (writeFile(FileName(s))) {
1104 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1105 return user_message;
1107 user_message += _(" Save failed! Trying again...\n");
1111 // 2) In HOME directory.
1112 string s = addName(package().home_dir().absFileName(), absFileName());
1114 lyxerr << ' ' << s << endl;
1115 if (writeFile(FileName(s))) {
1117 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1118 return user_message;
1121 user_message += _(" Save failed! Trying yet again...\n");
1123 // 3) In "/tmp" directory.
1124 // MakeAbsPath to prepend the current
1125 // drive letter on OS/2
1126 s = addName(package().temp_dir().absFileName(), absFileName());
1128 lyxerr << ' ' << s << endl;
1129 if (writeFile(FileName(s))) {
1131 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1132 return user_message;
1135 user_message += _(" Save failed! Bummer. Document is lost.");
1138 return user_message;
1142 bool Buffer::write(ostream & ofs) const
1145 // Use the standard "C" locale for file output.
1146 ofs.imbue(locale::classic());
1149 // The top of the file should not be written by params().
1151 // write out a comment in the top of the file
1152 ofs << "#LyX " << lyx_version
1153 << " created this file. For more info see http://www.lyx.org/\n"
1154 << "\\lyxformat " << LYX_FORMAT << "\n"
1155 << "\\begin_document\n";
1157 /// For each author, set 'used' to true if there is a change
1158 /// by this author in the document; otherwise set it to 'false'.
1159 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1160 AuthorList::Authors::const_iterator a_end = params().authors().end();
1161 for (; a_it != a_end; ++a_it)
1162 a_it->setUsed(false);
1164 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1165 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1166 for ( ; it != end; ++it)
1167 it->checkAuthors(params().authors());
1169 // now write out the buffer parameters.
1170 ofs << "\\begin_header\n";
1171 params().writeFile(ofs);
1172 ofs << "\\end_header\n";
1175 ofs << "\n\\begin_body\n";
1177 ofs << "\n\\end_body\n";
1179 // Write marker that shows file is complete
1180 ofs << "\\end_document" << endl;
1182 // Shouldn't really be needed....
1185 // how to check if close went ok?
1186 // Following is an attempt... (BE 20001011)
1188 // good() returns false if any error occured, including some
1189 // formatting error.
1190 // bad() returns true if something bad happened in the buffer,
1191 // which should include file system full errors.
1196 lyxerr << "File was not closed properly." << endl;
1203 bool Buffer::makeLaTeXFile(FileName const & fname,
1204 string const & original_path,
1205 OutputParams const & runparams_in,
1206 bool output_preamble, bool output_body) const
1208 OutputParams runparams = runparams_in;
1209 if (params().useXetex)
1210 runparams.flavor = OutputParams::XETEX;
1212 string const encoding = runparams.encoding->iconvName();
1213 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1216 try { ofs.reset(encoding); }
1217 catch (iconv_codecvt_facet_exception & e) {
1218 lyxerr << "Caught iconv exception: " << e.what() << endl;
1219 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1220 "verify that the support software for your encoding (%1$s) is "
1221 "properly installed"), from_ascii(encoding)));
1224 if (!openFileWrite(ofs, fname))
1227 //TexStream ts(ofs.rdbuf(), &texrow());
1228 ErrorList & errorList = d->errorLists["Export"];
1230 bool failed_export = false;
1233 writeLaTeXSource(ofs, original_path,
1234 runparams, output_preamble, output_body);
1236 catch (EncodingException & e) {
1237 odocstringstream ods;
1238 ods.put(e.failed_char);
1240 oss << "0x" << hex << e.failed_char << dec;
1241 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1242 " (code point %2$s)"),
1243 ods.str(), from_utf8(oss.str()));
1244 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1245 "representable in the chosen encoding.\n"
1246 "Changing the document encoding to utf8 could help."),
1247 e.par_id, e.pos, e.pos + 1));
1248 failed_export = true;
1250 catch (iconv_codecvt_facet_exception & e) {
1251 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1252 _(e.what()), -1, 0, 0));
1253 failed_export = true;
1255 catch (exception const & e) {
1256 errorList.push_back(ErrorItem(_("conversion failed"),
1257 _(e.what()), -1, 0, 0));
1258 failed_export = true;
1261 lyxerr << "Caught some really weird exception..." << endl;
1267 failed_export = true;
1268 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1272 return !failed_export;
1276 void Buffer::writeLaTeXSource(odocstream & os,
1277 string const & original_path,
1278 OutputParams const & runparams_in,
1279 bool const output_preamble, bool const output_body) const
1281 // The child documents, if any, shall be already loaded at this point.
1283 OutputParams runparams = runparams_in;
1285 // Classify the unicode characters appearing in math insets
1286 Encodings::initUnicodeMath(*this);
1288 // validate the buffer.
1289 LYXERR(Debug::LATEX, " Validating buffer...");
1290 LaTeXFeatures features(*this, params(), runparams);
1292 LYXERR(Debug::LATEX, " Buffer validation done.");
1294 // The starting paragraph of the coming rows is the
1295 // first paragraph of the document. (Asger)
1296 if (output_preamble && runparams.nice) {
1297 os << "%% LyX " << lyx_version << " created this file. "
1298 "For more info, see http://www.lyx.org/.\n"
1299 "%% Do not edit unless you really know what "
1301 d->texrow.newline();
1302 d->texrow.newline();
1304 LYXERR(Debug::INFO, "lyx document header finished");
1306 // Don't move this behind the parent_buffer=0 code below,
1307 // because then the macros will not get the right "redefinition"
1308 // flag as they don't see the parent macros which are output before.
1311 // fold macros if possible, still with parent buffer as the
1312 // macros will be put in the prefix anyway.
1313 updateMacroInstances();
1315 // There are a few differences between nice LaTeX and usual files:
1316 // usual is \batchmode and has a
1317 // special input@path to allow the including of figures
1318 // with either \input or \includegraphics (what figinsets do).
1319 // input@path is set when the actual parameter
1320 // original_path is set. This is done for usual tex-file, but not
1321 // for nice-latex-file. (Matthias 250696)
1322 // Note that input@path is only needed for something the user does
1323 // in the preamble, included .tex files or ERT, files included by
1324 // LyX work without it.
1325 if (output_preamble) {
1326 if (!runparams.nice) {
1327 // code for usual, NOT nice-latex-file
1328 os << "\\batchmode\n"; // changed
1329 // from \nonstopmode
1330 d->texrow.newline();
1332 if (!original_path.empty()) {
1334 // We don't know the encoding of inputpath
1335 docstring const inputpath = from_utf8(support::latex_path(original_path));
1336 docstring uncodable_glyphs;
1337 Encoding const * const enc = runparams.encoding;
1339 for (size_t n = 0; n < inputpath.size(); ++n) {
1340 docstring const glyph =
1341 docstring(1, inputpath[n]);
1342 if (enc->latexChar(inputpath[n], true) != glyph) {
1343 LYXERR0("Uncodable character '"
1345 << "' in input path!");
1346 uncodable_glyphs += glyph;
1351 // warn user if we found uncodable glyphs.
1352 if (!uncodable_glyphs.empty()) {
1353 frontend::Alert::warning(_("Uncodable character in file path"),
1354 support::bformat(_("The path of your document\n"
1356 "contains glyphs that are unknown in the\n"
1357 "current document encoding (namely %2$s).\n"
1358 "This will likely result in incomplete output.\n\n"
1359 "Choose an appropriate document encoding (such as utf8)\n"
1360 "or change the file path name."), inputpath, uncodable_glyphs));
1362 os << "\\makeatletter\n"
1363 << "\\def\\input@path{{"
1364 << inputpath << "/}}\n"
1365 << "\\makeatother\n";
1366 d->texrow.newline();
1367 d->texrow.newline();
1368 d->texrow.newline();
1372 // get parent macros (if this buffer has a parent) which will be
1373 // written at the document begin further down.
1374 MacroSet parentMacros;
1375 listParentMacros(parentMacros, features);
1377 // Write the preamble
1378 runparams.use_babel = params().writeLaTeX(os, features,
1380 d->filename.onlyPath());
1382 runparams.use_japanese = features.isRequired("japanese");
1388 os << "\\begin{document}\n";
1389 d->texrow.newline();
1391 // output the parent macros
1392 MacroSet::iterator it = parentMacros.begin();
1393 MacroSet::iterator end = parentMacros.end();
1394 for (; it != end; ++it) {
1395 int num_lines = (*it)->write(os, true);
1396 d->texrow.newlines(num_lines);
1399 } // output_preamble
1401 d->texrow.start(paragraphs().begin()->id(), 0);
1403 LYXERR(Debug::INFO, "preamble finished, now the body.");
1405 // if we are doing a real file with body, even if this is the
1406 // child of some other buffer, let's cut the link here.
1407 // This happens for example if only a child document is printed.
1408 Buffer const * save_parent = 0;
1409 if (output_preamble) {
1410 save_parent = d->parent();
1415 latexParagraphs(*this, text(), os, d->texrow, runparams);
1417 // Restore the parenthood if needed
1418 if (output_preamble)
1419 d->setParent(save_parent);
1421 // add this just in case after all the paragraphs
1423 d->texrow.newline();
1425 if (output_preamble) {
1426 os << "\\end{document}\n";
1427 d->texrow.newline();
1428 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1430 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1432 runparams_in.encoding = runparams.encoding;
1434 // Just to be sure. (Asger)
1435 d->texrow.newline();
1437 //for (int i = 0; i<d->texrow.rows(); i++) {
1439 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1440 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1443 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1444 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1448 bool Buffer::isLatex() const
1450 return params().documentClass().outputType() == LATEX;
1454 bool Buffer::isLiterate() const
1456 return params().documentClass().outputType() == LITERATE;
1460 bool Buffer::isDocBook() const
1462 return params().documentClass().outputType() == DOCBOOK;
1466 void Buffer::makeDocBookFile(FileName const & fname,
1467 OutputParams const & runparams,
1468 bool const body_only) const
1470 LYXERR(Debug::LATEX, "makeDocBookFile...");
1473 if (!openFileWrite(ofs, fname))
1476 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1480 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1484 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1485 OutputParams const & runparams,
1486 bool const only_body) const
1488 LaTeXFeatures features(*this, params(), runparams);
1493 DocumentClass const & tclass = params().documentClass();
1494 string const top_element = tclass.latexname();
1497 if (runparams.flavor == OutputParams::XML)
1498 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1501 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1504 if (! tclass.class_header().empty())
1505 os << from_ascii(tclass.class_header());
1506 else if (runparams.flavor == OutputParams::XML)
1507 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1508 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1510 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1512 docstring preamble = from_utf8(params().preamble);
1513 if (runparams.flavor != OutputParams::XML ) {
1514 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1515 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1516 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1517 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1520 string const name = runparams.nice
1521 ? changeExtension(absFileName(), ".sgml") : fname;
1522 preamble += features.getIncludedFiles(name);
1523 preamble += features.getLyXSGMLEntities();
1525 if (!preamble.empty()) {
1526 os << "\n [ " << preamble << " ]";
1531 string top = top_element;
1533 if (runparams.flavor == OutputParams::XML)
1534 top += params().language->code();
1536 top += params().language->code().substr(0, 2);
1539 if (!params().options.empty()) {
1541 top += params().options;
1544 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1545 << " file was created by LyX " << lyx_version
1546 << "\n See http://www.lyx.org/ for more information -->\n";
1548 params().documentClass().counters().reset();
1552 sgml::openTag(os, top);
1554 docbookParagraphs(text(), *this, os, runparams);
1555 sgml::closeTag(os, top_element);
1559 void Buffer::makeLyXHTMLFile(FileName const & fname,
1560 OutputParams const & runparams,
1561 bool const body_only) const
1563 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1566 if (!openFileWrite(ofs, fname))
1569 writeLyXHTMLSource(ofs, runparams, body_only);
1573 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1577 void Buffer::writeLyXHTMLSource(odocstream & os,
1578 OutputParams const & runparams,
1579 bool const only_body) const
1581 LaTeXFeatures features(*this, params(), runparams);
1583 updateBuffer(UpdateMaster, OutputUpdate);
1584 d->bibinfo_.makeCitationLabels(*this);
1586 updateMacroInstances();
1589 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1590 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1591 // FIXME Language should be set properly.
1592 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1594 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1595 // FIXME Presumably need to set this right
1596 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1598 docstring const & doctitle = features.htmlTitle();
1600 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1603 os << "\n<!-- Text Class Preamble -->\n"
1604 << features.getTClassHTMLPreamble()
1605 << "\n<!-- Premable Snippets -->\n"
1606 << from_utf8(features.getPreambleSnippets());
1608 os << "\n<!-- Layout-provided Styles -->\n";
1609 docstring const styleinfo = features.getTClassHTMLStyles();
1610 if (!styleinfo.empty()) {
1611 os << "<style type='text/css'>\n"
1615 os << "</head>\n<body>\n";
1619 params().documentClass().counters().reset();
1620 xhtmlParagraphs(text(), *this, xs, runparams);
1622 os << "</body>\n</html>\n";
1626 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1627 // Other flags: -wall -v0 -x
1628 int Buffer::runChktex()
1632 // get LaTeX-Filename
1633 FileName const path(temppath());
1634 string const name = addName(path.absFileName(), latexName());
1635 string const org_path = filePath();
1637 PathChanger p(path); // path to LaTeX file
1638 message(_("Running chktex..."));
1640 // Generate the LaTeX file if neccessary
1641 OutputParams runparams(¶ms().encoding());
1642 runparams.flavor = OutputParams::LATEX;
1643 runparams.nice = false;
1644 runparams.linelen = lyxrc.plaintext_linelen;
1645 makeLaTeXFile(FileName(name), org_path, runparams);
1648 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1649 int const res = chktex.run(terr); // run chktex
1652 Alert::error(_("chktex failure"),
1653 _("Could not run chktex successfully."));
1654 } else if (res > 0) {
1655 ErrorList & errlist = d->errorLists["ChkTeX"];
1657 bufferErrors(terr, errlist);
1668 void Buffer::validate(LaTeXFeatures & features) const
1670 params().validate(features);
1674 for_each(paragraphs().begin(), paragraphs().end(),
1675 bind(&Paragraph::validate, _1, ref(features)));
1677 if (lyxerr.debugging(Debug::LATEX)) {
1678 features.showStruct();
1683 void Buffer::getLabelList(vector<docstring> & list) const
1685 // If this is a child document, use the parent's list instead.
1686 Buffer const * const pbuf = d->parent();
1688 pbuf->getLabelList(list);
1693 Toc & toc = d->toc_backend.toc("label");
1694 TocIterator toc_it = toc.begin();
1695 TocIterator end = toc.end();
1696 for (; toc_it != end; ++toc_it) {
1697 if (toc_it->depth() == 0)
1698 list.push_back(toc_it->str());
1703 void Buffer::updateBibfilesCache(UpdateScope scope) const
1705 // FIXME This is probably unnecssary, given where we call this.
1706 // If this is a child document, use the parent's cache instead.
1707 Buffer const * const pbuf = d->parent();
1708 if (pbuf && scope != UpdateChildOnly) {
1709 pbuf->updateBibfilesCache();
1713 d->bibfiles_cache_.clear();
1714 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1715 if (it->lyxCode() == BIBTEX_CODE) {
1716 InsetBibtex const & inset =
1717 static_cast<InsetBibtex const &>(*it);
1718 support::FileNameList const bibfiles = inset.getBibFiles();
1719 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1722 } else if (it->lyxCode() == INCLUDE_CODE) {
1723 InsetInclude & inset =
1724 static_cast<InsetInclude &>(*it);
1725 Buffer const * const incbuf = inset.getChildBuffer();
1728 support::FileNameList const & bibfiles =
1729 incbuf->getBibfilesCache(UpdateChildOnly);
1730 if (!bibfiles.empty()) {
1731 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1737 d->bibfile_cache_valid_ = true;
1738 d->bibinfo_cache_valid_ = false;
1742 void Buffer::invalidateBibinfoCache() const
1744 d->bibinfo_cache_valid_ = false;
1745 // also invalidate the cache for the parent buffer
1746 Buffer const * const pbuf = d->parent();
1748 pbuf->invalidateBibinfoCache();
1752 void Buffer::invalidateBibfileCache() const
1754 d->bibfile_cache_valid_ = false;
1755 d->bibinfo_cache_valid_ = false;
1756 // also invalidate the cache for the parent buffer
1757 Buffer const * const pbuf = d->parent();
1759 pbuf->invalidateBibfileCache();
1763 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1765 // FIXME This is probably unnecessary, given where we call this.
1766 // If this is a child document, use the master's cache instead.
1767 Buffer const * const pbuf = masterBuffer();
1768 if (pbuf != this && scope != UpdateChildOnly)
1769 return pbuf->getBibfilesCache();
1771 if (!d->bibfile_cache_valid_)
1772 this->updateBibfilesCache(scope);
1774 return d->bibfiles_cache_;
1778 BiblioInfo const & Buffer::masterBibInfo() const
1780 Buffer const * const tmp = masterBuffer();
1782 return tmp->masterBibInfo();
1787 void Buffer::checkBibInfoCache() const
1789 // use the master's cache
1790 Buffer const * const tmp = masterBuffer();
1792 tmp->checkBibInfoCache();
1796 // this will also reload the cache if it is invalid
1797 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1799 // compare the cached timestamps with the actual ones.
1800 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1801 support::FileNameList::const_iterator en = bibfiles_cache.end();
1802 for (; ei != en; ++ ei) {
1803 time_t lastw = ei->lastModified();
1804 time_t prevw = d->bibfile_status_[*ei];
1805 if (lastw != prevw) {
1806 d->bibinfo_cache_valid_ = false;
1807 d->bibfile_status_[*ei] = lastw;
1811 // if not valid, then reload the info
1812 if (!d->bibinfo_cache_valid_) {
1813 d->bibinfo_.clear();
1814 fillWithBibKeys(d->bibinfo_);
1815 d->bibinfo_cache_valid_ = true;
1820 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1822 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1823 it->fillWithBibKeys(keys, it);
1827 bool Buffer::isDepClean(string const & name) const
1829 DepClean::const_iterator const it = d->dep_clean.find(name);
1830 if (it == d->dep_clean.end())
1836 void Buffer::markDepClean(string const & name)
1838 d->dep_clean[name] = true;
1842 bool Buffer::isExportableFormat(string const & format) const
1844 typedef vector<Format const *> Formats;
1846 formats = exportableFormats(true);
1847 Formats::const_iterator fit = formats.begin();
1848 Formats::const_iterator end = formats.end();
1849 for (; fit != end ; ++fit) {
1850 if ((*fit)->name() == format)
1857 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1860 // FIXME? if there is an Buffer LFUN that can be dispatched even
1861 // if internal, put a switch '(cmd.action)' here.
1867 switch (cmd.action()) {
1869 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1870 flag.setOnOff(isReadonly());
1873 // FIXME: There is need for a command-line import.
1874 //case LFUN_BUFFER_IMPORT:
1876 case LFUN_BUFFER_AUTO_SAVE:
1879 case LFUN_BUFFER_EXPORT_CUSTOM:
1880 // FIXME: Nothing to check here?
1883 case LFUN_BUFFER_EXPORT: {
1884 docstring const arg = cmd.argument();
1885 enable = arg == "custom" || isExportable(to_utf8(arg));
1887 flag.message(bformat(
1888 _("Don't know how to export to format: %1$s"), arg));
1892 case LFUN_BUFFER_CHKTEX:
1893 enable = isLatex() && !lyxrc.chktex_command.empty();
1896 case LFUN_BUILD_PROGRAM:
1897 enable = isExportable("program");
1900 case LFUN_BRANCH_ACTIVATE:
1901 case LFUN_BRANCH_DEACTIVATE: {
1902 BranchList const & branchList = params().branchlist();
1903 docstring const branchName = cmd.argument();
1904 enable = !branchName.empty() && branchList.find(branchName);
1908 case LFUN_BRANCH_ADD:
1909 case LFUN_BRANCHES_RENAME:
1910 case LFUN_BUFFER_PRINT:
1911 // if no Buffer is present, then of course we won't be called!
1914 case LFUN_BUFFER_LANGUAGE:
1915 enable = !isReadonly();
1921 flag.setEnabled(enable);
1926 void Buffer::dispatch(string const & command, DispatchResult & result)
1928 return dispatch(lyxaction.lookupFunc(command), result);
1932 // NOTE We can end up here even if we have no GUI, because we are called
1933 // by LyX::exec to handled command-line requests. So we may need to check
1934 // whether we have a GUI or not. The boolean use_gui holds this information.
1935 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1938 // FIXME? if there is an Buffer LFUN that can be dispatched even
1939 // if internal, put a switch '(cmd.action())' here.
1940 dr.dispatched(false);
1943 string const argument = to_utf8(func.argument());
1944 // We'll set this back to false if need be.
1945 bool dispatched = true;
1946 undo().beginUndoGroup();
1948 switch (func.action()) {
1949 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1950 if (lyxvc().inUse())
1951 lyxvc().toggleReadOnly();
1953 setReadonly(!isReadonly());
1956 case LFUN_BUFFER_EXPORT: {
1957 bool success = doExport(argument, false, false);
1958 dr.setError(!success);
1960 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1965 case LFUN_BUILD_PROGRAM:
1966 doExport("program", true, false);
1969 case LFUN_BUFFER_CHKTEX:
1973 case LFUN_BUFFER_EXPORT_CUSTOM: {
1975 string command = split(argument, format_name, ' ');
1976 Format const * format = formats.getFormat(format_name);
1978 lyxerr << "Format \"" << format_name
1979 << "\" not recognized!"
1984 // The name of the file created by the conversion process
1987 // Output to filename
1988 if (format->name() == "lyx") {
1989 string const latexname = latexName(false);
1990 filename = changeExtension(latexname,
1991 format->extension());
1992 filename = addName(temppath(), filename);
1994 if (!writeFile(FileName(filename)))
1998 doExport(format_name, true, false, filename);
2001 // Substitute $$FName for filename
2002 if (!contains(command, "$$FName"))
2003 command = "( " + command + " ) < $$FName";
2004 command = subst(command, "$$FName", filename);
2006 // Execute the command in the background
2008 call.startscript(Systemcall::DontWait, command);
2012 // FIXME: There is need for a command-line import.
2014 case LFUN_BUFFER_IMPORT:
2019 case LFUN_BUFFER_AUTO_SAVE:
2023 case LFUN_BRANCH_ADD: {
2024 docstring branch_name = func.argument();
2025 if (branch_name.empty()) {
2029 BranchList & branch_list = params().branchlist();
2030 vector<docstring> const branches =
2031 getVectorFromString(branch_name, branch_list.separator());
2033 for (vector<docstring>::const_iterator it = branches.begin();
2034 it != branches.end(); ++it) {
2036 Branch * branch = branch_list.find(branch_name);
2038 LYXERR0("Branch " << branch_name << " already exists.");
2042 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2044 branch_list.add(branch_name);
2045 branch = branch_list.find(branch_name);
2046 string const x11hexname = X11hexname(branch->color());
2047 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2048 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2050 dr.update(Update::Force);
2058 case LFUN_BRANCH_ACTIVATE:
2059 case LFUN_BRANCH_DEACTIVATE: {
2060 BranchList & branchList = params().branchlist();
2061 docstring const branchName = func.argument();
2062 // the case without a branch name is handled elsewhere
2063 if (branchName.empty()) {
2067 Branch * branch = branchList.find(branchName);
2069 LYXERR0("Branch " << branchName << " does not exist.");
2071 docstring const msg =
2072 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2075 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2077 dr.update(Update::Force);
2078 dr.forceBufferUpdate();
2083 case LFUN_BRANCHES_RENAME: {
2084 if (func.argument().empty())
2087 docstring const oldname = from_utf8(func.getArg(0));
2088 docstring const newname = from_utf8(func.getArg(1));
2089 InsetIterator it = inset_iterator_begin(inset());
2090 InsetIterator const end = inset_iterator_end(inset());
2091 bool success = false;
2092 for (; it != end; ++it) {
2093 if (it->lyxCode() == BRANCH_CODE) {
2094 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2095 if (ins.branch() == oldname) {
2096 undo().recordUndo(it);
2097 ins.rename(newname);
2102 if (it->lyxCode() == INCLUDE_CODE) {
2103 // get buffer of external file
2104 InsetInclude const & ins =
2105 static_cast<InsetInclude const &>(*it);
2106 Buffer * child = ins.getChildBuffer();
2109 child->dispatch(func, dr);
2114 dr.update(Update::Force);
2115 dr.forceBufferUpdate();
2120 case LFUN_BUFFER_PRINT: {
2121 // we'll assume there's a problem until we succeed
2123 string target = func.getArg(0);
2124 string target_name = func.getArg(1);
2125 string command = func.getArg(2);
2128 || target_name.empty()
2129 || command.empty()) {
2130 LYXERR0("Unable to parse " << func.argument());
2131 docstring const msg =
2132 bformat(_("Unable to parse \"%1$s\""), func.argument());
2136 if (target != "printer" && target != "file") {
2137 LYXERR0("Unrecognized target \"" << target << '"');
2138 docstring const msg =
2139 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2144 bool const update_unincluded =
2145 params().maintain_unincluded_children
2146 && !params().getIncludedChildren().empty();
2147 if (!doExport("dvi", true, update_unincluded)) {
2148 showPrintError(absFileName());
2149 dr.setMessage(_("Error exporting to DVI."));
2153 // Push directory path.
2154 string const path = temppath();
2155 // Prevent the compiler from optimizing away p
2159 // there are three cases here:
2160 // 1. we print to a file
2161 // 2. we print directly to a printer
2162 // 3. we print using a spool command (print to file first)
2165 string const dviname = changeExtension(latexName(true), "dvi");
2167 if (target == "printer") {
2168 if (!lyxrc.print_spool_command.empty()) {
2169 // case 3: print using a spool
2170 string const psname = changeExtension(dviname,".ps");
2171 command += ' ' + lyxrc.print_to_file
2174 + quoteName(dviname);
2176 string command2 = lyxrc.print_spool_command + ' ';
2177 if (target_name != "default") {
2178 command2 += lyxrc.print_spool_printerprefix
2182 command2 += quoteName(psname);
2184 // If successful, then spool command
2185 res = one.startscript(Systemcall::Wait, command);
2188 // If there's no GUI, we have to wait on this command. Otherwise,
2189 // LyX deletes the temporary directory, and with it the spooled
2190 // file, before it can be printed!!
2191 Systemcall::Starttype stype = use_gui ?
2192 Systemcall::DontWait : Systemcall::Wait;
2193 res = one.startscript(stype, command2);
2196 // case 2: print directly to a printer
2197 if (target_name != "default")
2198 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2200 Systemcall::Starttype stype = use_gui ?
2201 Systemcall::DontWait : Systemcall::Wait;
2202 res = one.startscript(stype, command + quoteName(dviname));
2206 // case 1: print to a file
2207 FileName const filename(makeAbsPath(target_name, filePath()));
2208 FileName const dvifile(makeAbsPath(dviname, path));
2209 if (filename.exists()) {
2210 docstring text = bformat(
2211 _("The file %1$s already exists.\n\n"
2212 "Do you want to overwrite that file?"),
2213 makeDisplayPath(filename.absFileName()));
2214 if (Alert::prompt(_("Overwrite file?"),
2215 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2218 command += ' ' + lyxrc.print_to_file
2219 + quoteName(filename.toFilesystemEncoding())
2221 + quoteName(dvifile.toFilesystemEncoding());
2223 Systemcall::Starttype stype = use_gui ?
2224 Systemcall::DontWait : Systemcall::Wait;
2225 res = one.startscript(stype, command);
2231 dr.setMessage(_("Error running external commands."));
2232 showPrintError(absFileName());
2237 case LFUN_BUFFER_LANGUAGE: {
2238 Language const * oldL = params().language;
2239 Language const * newL = languages.getLanguage(argument);
2240 if (!newL || oldL == newL)
2242 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2243 changeLanguage(oldL, newL);
2244 dr.forceBufferUpdate();
2253 dr.dispatched(dispatched);
2254 undo().endUndoGroup();
2258 void Buffer::changeLanguage(Language const * from, Language const * to)
2260 LASSERT(from, /**/);
2263 for_each(par_iterator_begin(),
2265 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2269 bool Buffer::isMultiLingual() const
2271 ParConstIterator end = par_iterator_end();
2272 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2273 if (it->isMultiLingual(params()))
2280 std::set<Language const *> Buffer::getLanguages() const
2282 std::set<Language const *> languages;
2283 getLanguages(languages);
2288 void Buffer::getLanguages(std::set<Language const *> & languages) const
2290 ParConstIterator end = par_iterator_end();
2291 // add the buffer language, even if it's not actively used
2292 languages.insert(language());
2293 // iterate over the paragraphs
2294 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2295 it->getLanguages(languages);
2297 ListOfBuffers clist = getChildren();
2298 ListOfBuffers::const_iterator cit = clist.begin();
2299 ListOfBuffers::const_iterator const cen = clist.end();
2300 for (; cit != cen; ++cit)
2301 (*cit)->getLanguages(languages);
2305 DocIterator Buffer::getParFromID(int const id) const
2307 Buffer * buf = const_cast<Buffer *>(this);
2309 // John says this is called with id == -1 from undo
2310 lyxerr << "getParFromID(), id: " << id << endl;
2311 return doc_iterator_end(buf);
2314 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2315 if (it.paragraph().id() == id)
2318 return doc_iterator_end(buf);
2322 bool Buffer::hasParWithID(int const id) const
2324 return !getParFromID(id).atEnd();
2328 ParIterator Buffer::par_iterator_begin()
2330 return ParIterator(doc_iterator_begin(this));
2334 ParIterator Buffer::par_iterator_end()
2336 return ParIterator(doc_iterator_end(this));
2340 ParConstIterator Buffer::par_iterator_begin() const
2342 return ParConstIterator(doc_iterator_begin(this));
2346 ParConstIterator Buffer::par_iterator_end() const
2348 return ParConstIterator(doc_iterator_end(this));
2352 Language const * Buffer::language() const
2354 return params().language;
2358 docstring const Buffer::B_(string const & l10n) const
2360 return params().B_(l10n);
2364 bool Buffer::isClean() const
2366 return d->lyx_clean;
2370 bool Buffer::isExternallyModified(CheckMethod method) const
2372 LASSERT(d->filename.exists(), /**/);
2373 // if method == timestamp, check timestamp before checksum
2374 return (method == checksum_method
2375 || d->timestamp_ != d->filename.lastModified())
2376 && d->checksum_ != d->filename.checksum();
2380 void Buffer::saveCheckSum(FileName const & file) const
2382 if (file.exists()) {
2383 d->timestamp_ = file.lastModified();
2384 d->checksum_ = file.checksum();
2386 // in the case of save to a new file.
2393 void Buffer::markClean() const
2395 if (!d->lyx_clean) {
2396 d->lyx_clean = true;
2399 // if the .lyx file has been saved, we don't need an
2401 d->bak_clean = true;
2402 d->undo_.markDirty();
2406 void Buffer::setUnnamed(bool flag)
2412 bool Buffer::isUnnamed() const
2419 /// Don't check unnamed, here: isInternal() is used in
2420 /// newBuffer(), where the unnamed flag has not been set by anyone
2421 /// yet. Also, for an internal buffer, there should be no need for
2422 /// retrieving fileName() nor for checking if it is unnamed or not.
2423 bool Buffer::isInternal() const
2425 return fileName().extension() == "internal";
2429 void Buffer::markDirty()
2432 d->lyx_clean = false;
2435 d->bak_clean = false;
2437 DepClean::iterator it = d->dep_clean.begin();
2438 DepClean::const_iterator const end = d->dep_clean.end();
2440 for (; it != end; ++it)
2445 FileName Buffer::fileName() const
2451 string Buffer::absFileName() const
2453 return d->filename.absFileName();
2457 string Buffer::filePath() const
2459 return d->filename.onlyPath().absFileName() + "/";
2463 bool Buffer::isReadonly() const
2465 return d->read_only;
2469 void Buffer::setParent(Buffer const * buffer)
2471 // Avoids recursive include.
2472 d->setParent(buffer == this ? 0 : buffer);
2477 Buffer const * Buffer::parent() const
2483 ListOfBuffers Buffer::allRelatives() const
2486 return parent()->allRelatives();
2487 return getChildren(/* true */);
2491 Buffer const * Buffer::masterBuffer() const
2493 Buffer const * const pbuf = d->parent();
2497 return pbuf->masterBuffer();
2501 bool Buffer::isChild(Buffer * child) const
2503 return d->children_positions.find(child) != d->children_positions.end();
2507 DocIterator Buffer::firstChildPosition(Buffer const * child)
2509 Impl::BufferPositionMap::iterator it;
2510 it = d->children_positions.find(child);
2511 if (it == d->children_positions.end())
2512 return DocIterator(this);
2517 bool Buffer::hasChildren() const
2519 return !d->children_positions.empty();
2523 void Buffer::getChildren(ListOfBuffers & clist, bool grand_children) const
2525 // loop over children
2526 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2527 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2528 for (; it != end; ++it) {
2529 Buffer * child = const_cast<Buffer *>(it->first);
2530 clist.push_back(child);
2532 // there might be grandchildren
2533 child->getChildren(clist /*, true */);
2538 ListOfBuffers Buffer::getChildren(bool grand_children) const
2541 getChildren(v, grand_children);
2546 template<typename M>
2547 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2552 typename M::const_iterator it = m.lower_bound(x);
2553 if (it == m.begin())
2561 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2562 DocIterator const & pos) const
2564 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2566 // if paragraphs have no macro context set, pos will be empty
2570 // we haven't found anything yet
2571 DocIterator bestPos = owner_->par_iterator_begin();
2572 MacroData const * bestData = 0;
2574 // find macro definitions for name
2575 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2576 if (nameIt != macros.end()) {
2577 // find last definition in front of pos or at pos itself
2578 PositionScopeMacroMap::const_iterator it
2579 = greatest_below(nameIt->second, pos);
2580 if (it != nameIt->second.end()) {
2582 // scope ends behind pos?
2583 if (pos < it->second.first) {
2584 // Looks good, remember this. If there
2585 // is no external macro behind this,
2586 // we found the right one already.
2587 bestPos = it->first;
2588 bestData = &it->second.second;
2592 // try previous macro if there is one
2593 if (it == nameIt->second.begin())
2600 // find macros in included files
2601 PositionScopeBufferMap::const_iterator it
2602 = greatest_below(position_to_children, pos);
2603 if (it == position_to_children.end())
2604 // no children before
2608 // do we know something better (i.e. later) already?
2609 if (it->first < bestPos )
2612 // scope ends behind pos?
2613 if (pos < it->second.first) {
2614 // look for macro in external file
2616 MacroData const * data
2617 = it->second.second->getMacro(name, false);
2620 bestPos = it->first;
2626 // try previous file if there is one
2627 if (it == position_to_children.begin())
2632 // return the best macro we have found
2637 MacroData const * Buffer::getMacro(docstring const & name,
2638 DocIterator const & pos, bool global) const
2643 // query buffer macros
2644 MacroData const * data = d->getBufferMacro(name, pos);
2648 // If there is a master buffer, query that
2649 Buffer const * const pbuf = d->parent();
2651 d->macro_lock = true;
2652 MacroData const * macro = pbuf->getMacro(
2653 name, *this, false);
2654 d->macro_lock = false;
2660 data = MacroTable::globalMacros().get(name);
2669 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2671 // set scope end behind the last paragraph
2672 DocIterator scope = par_iterator_begin();
2673 scope.pit() = scope.lastpit() + 1;
2675 return getMacro(name, scope, global);
2679 MacroData const * Buffer::getMacro(docstring const & name,
2680 Buffer const & child, bool global) const
2682 // look where the child buffer is included first
2683 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2684 if (it == d->children_positions.end())
2687 // check for macros at the inclusion position
2688 return getMacro(name, it->second, global);
2692 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2694 pit_type const lastpit = it.lastpit();
2696 // look for macros in each paragraph
2697 while (it.pit() <= lastpit) {
2698 Paragraph & par = it.paragraph();
2700 // iterate over the insets of the current paragraph
2701 InsetList const & insets = par.insetList();
2702 InsetList::const_iterator iit = insets.begin();
2703 InsetList::const_iterator end = insets.end();
2704 for (; iit != end; ++iit) {
2705 it.pos() = iit->pos;
2707 // is it a nested text inset?
2708 if (iit->inset->asInsetText()) {
2709 // Inset needs its own scope?
2710 InsetText const * itext = iit->inset->asInsetText();
2711 bool newScope = itext->isMacroScope();
2713 // scope which ends just behind the inset
2714 DocIterator insetScope = it;
2717 // collect macros in inset
2718 it.push_back(CursorSlice(*iit->inset));
2719 updateMacros(it, newScope ? insetScope : scope);
2724 // is it an external file?
2725 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2726 // get buffer of external file
2727 InsetInclude const & inset =
2728 static_cast<InsetInclude const &>(*iit->inset);
2730 Buffer * child = inset.getChildBuffer();
2735 // register its position, but only when it is
2736 // included first in the buffer
2737 if (children_positions.find(child) ==
2738 children_positions.end())
2739 children_positions[child] = it;
2741 // register child with its scope
2742 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2746 if (doing_export && iit->inset->asInsetMath()) {
2747 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2748 if (im->asHullInset()) {
2749 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2750 hull->recordLocation(it);
2754 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2758 MathMacroTemplate & macroTemplate =
2759 static_cast<MathMacroTemplate &>(*iit->inset);
2760 MacroContext mc(owner_, it);
2761 macroTemplate.updateToContext(mc);
2764 bool valid = macroTemplate.validMacro();
2765 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2766 // then the BufferView's cursor will be invalid in
2767 // some cases which leads to crashes.
2772 // FIXME (Abdel), I don't understandt why we pass 'it' here
2773 // instead of 'macroTemplate' defined above... is this correct?
2774 macros[macroTemplate.name()][it] =
2775 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2785 void Buffer::updateMacros() const
2790 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2792 // start with empty table
2794 d->children_positions.clear();
2795 d->position_to_children.clear();
2797 // Iterate over buffer, starting with first paragraph
2798 // The scope must be bigger than any lookup DocIterator
2799 // later. For the global lookup, lastpit+1 is used, hence
2800 // we use lastpit+2 here.
2801 DocIterator it = par_iterator_begin();
2802 DocIterator outerScope = it;
2803 outerScope.pit() = outerScope.lastpit() + 2;
2804 d->updateMacros(it, outerScope);
2808 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2810 InsetIterator it = inset_iterator_begin(inset());
2811 InsetIterator const end = inset_iterator_end(inset());
2812 for (; it != end; ++it) {
2813 if (it->lyxCode() == BRANCH_CODE) {
2814 InsetBranch & br = static_cast<InsetBranch &>(*it);
2815 docstring const name = br.branch();
2816 if (!from_master && !params().branchlist().find(name))
2817 result.push_back(name);
2818 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2819 result.push_back(name);
2822 if (it->lyxCode() == INCLUDE_CODE) {
2823 // get buffer of external file
2824 InsetInclude const & ins =
2825 static_cast<InsetInclude const &>(*it);
2826 Buffer * child = ins.getChildBuffer();
2829 child->getUsedBranches(result, true);
2832 // remove duplicates
2837 void Buffer::updateMacroInstances() const
2839 LYXERR(Debug::MACROS, "updateMacroInstances for "
2840 << d->filename.onlyFileName());
2841 DocIterator it = doc_iterator_begin(this);
2843 DocIterator const end = doc_iterator_end(this);
2844 for (; it != end; it.forwardInset()) {
2845 // look for MathData cells in InsetMathNest insets
2846 InsetMath * minset = it.nextInset()->asInsetMath();
2850 // update macro in all cells of the InsetMathNest
2851 DocIterator::idx_type n = minset->nargs();
2852 MacroContext mc = MacroContext(this, it);
2853 for (DocIterator::idx_type i = 0; i < n; ++i) {
2854 MathData & data = minset->cell(i);
2855 data.updateMacros(0, mc);
2861 void Buffer::listMacroNames(MacroNameSet & macros) const
2866 d->macro_lock = true;
2868 // loop over macro names
2869 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2870 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2871 for (; nameIt != nameEnd; ++nameIt)
2872 macros.insert(nameIt->first);
2874 // loop over children
2875 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2876 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2877 for (; it != end; ++it)
2878 it->first->listMacroNames(macros);
2881 Buffer const * const pbuf = d->parent();
2883 pbuf->listMacroNames(macros);
2885 d->macro_lock = false;
2889 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2891 Buffer const * const pbuf = d->parent();
2896 pbuf->listMacroNames(names);
2899 MacroNameSet::iterator it = names.begin();
2900 MacroNameSet::iterator end = names.end();
2901 for (; it != end; ++it) {
2903 MacroData const * data =
2904 pbuf->getMacro(*it, *this, false);
2906 macros.insert(data);
2908 // we cannot access the original MathMacroTemplate anymore
2909 // here to calls validate method. So we do its work here manually.
2910 // FIXME: somehow make the template accessible here.
2911 if (data->optionals() > 0)
2912 features.require("xargs");
2918 Buffer::References & Buffer::references(docstring const & label)
2921 return const_cast<Buffer *>(masterBuffer())->references(label);
2923 RefCache::iterator it = d->ref_cache_.find(label);
2924 if (it != d->ref_cache_.end())
2925 return it->second.second;
2927 static InsetLabel const * dummy_il = 0;
2928 static References const dummy_refs;
2929 it = d->ref_cache_.insert(
2930 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2931 return it->second.second;
2935 Buffer::References const & Buffer::references(docstring const & label) const
2937 return const_cast<Buffer *>(this)->references(label);
2941 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2943 masterBuffer()->d->ref_cache_[label].first = il;
2947 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2949 return masterBuffer()->d->ref_cache_[label].first;
2953 void Buffer::clearReferenceCache() const
2956 d->ref_cache_.clear();
2960 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2963 //FIXME: This does not work for child documents yet.
2964 LASSERT(code == CITE_CODE, /**/);
2965 // Check if the label 'from' appears more than once
2966 vector<docstring> labels;
2968 checkBibInfoCache();
2969 BiblioInfo const & keys = masterBibInfo();
2970 BiblioInfo::const_iterator bit = keys.begin();
2971 BiblioInfo::const_iterator bend = keys.end();
2973 for (; bit != bend; ++bit)
2975 labels.push_back(bit->first);
2978 if (count(labels.begin(), labels.end(), from) > 1)
2981 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2982 if (it->lyxCode() == code) {
2983 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2984 docstring const oldValue = inset.getParam(paramName);
2985 if (oldValue == from)
2986 inset.setParam(paramName, to);
2992 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2993 pit_type par_end, bool full_source) const
2995 OutputParams runparams(¶ms().encoding());
2996 runparams.nice = true;
2997 runparams.flavor = params().useXetex ?
2998 OutputParams::XETEX : OutputParams::LATEX;
2999 runparams.linelen = lyxrc.plaintext_linelen;
3000 // No side effect of file copying and image conversion
3001 runparams.dryrun = true;
3004 os << "% " << _("Preview source code") << "\n\n";
3006 d->texrow.newline();
3007 d->texrow.newline();
3009 writeDocBookSource(os, absFileName(), runparams, false);
3011 // latex or literate
3012 writeLaTeXSource(os, string(), runparams, true, true);
3014 runparams.par_begin = par_begin;
3015 runparams.par_end = par_end;
3016 if (par_begin + 1 == par_end) {
3018 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3022 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3023 convert<docstring>(par_begin),
3024 convert<docstring>(par_end - 1))
3031 // output paragraphs
3033 docbookParagraphs(text(), *this, os, runparams);
3035 // latex or literate
3036 latexParagraphs(*this, text(), os, texrow, runparams);
3041 ErrorList & Buffer::errorList(string const & type) const
3043 static ErrorList emptyErrorList;
3044 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3045 if (it == d->errorLists.end())
3046 return emptyErrorList;
3052 void Buffer::updateTocItem(std::string const & type,
3053 DocIterator const & dit) const
3056 d->gui_->updateTocItem(type, dit);
3060 void Buffer::structureChanged() const
3063 d->gui_->structureChanged();
3067 void Buffer::errors(string const & err, bool from_master) const
3070 d->gui_->errors(err, from_master);
3074 void Buffer::message(docstring const & msg) const
3077 d->gui_->message(msg);
3081 void Buffer::setBusy(bool on) const
3084 d->gui_->setBusy(on);
3088 void Buffer::updateTitles() const
3091 d->wa_->updateTitles();
3095 void Buffer::resetAutosaveTimers() const
3098 d->gui_->resetAutosaveTimers();
3102 bool Buffer::hasGuiDelegate() const
3108 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3117 class AutoSaveBuffer : public ForkedProcess {
3120 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3121 : buffer_(buffer), fname_(fname) {}
3123 virtual shared_ptr<ForkedProcess> clone() const
3125 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3130 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3131 from_utf8(fname_.absFileName())));
3132 return run(DontWait);
3136 virtual int generateChild();
3138 Buffer const & buffer_;
3143 int AutoSaveBuffer::generateChild()
3145 #if defined(__APPLE__)
3146 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3147 * We should use something else like threads.
3149 * Since I do not know how to determine at run time what is the OS X
3150 * version, I just disable forking altogether for now (JMarc)
3152 pid_t const pid = -1;
3154 // tmp_ret will be located (usually) in /tmp
3155 // will that be a problem?
3156 // Note that this calls ForkedCalls::fork(), so it's
3157 // ok cross-platform.
3158 pid_t const pid = fork();
3159 // If you want to debug the autosave
3160 // you should set pid to -1, and comment out the fork.
3161 if (pid != 0 && pid != -1)
3165 // pid = -1 signifies that lyx was unable
3166 // to fork. But we will do the save
3168 bool failed = false;
3169 FileName const tmp_ret = FileName::tempName("lyxauto");
3170 if (!tmp_ret.empty()) {
3171 buffer_.writeFile(tmp_ret);
3172 // assume successful write of tmp_ret
3173 if (!tmp_ret.moveTo(fname_))
3179 // failed to write/rename tmp_ret so try writing direct
3180 if (!buffer_.writeFile(fname_)) {
3181 // It is dangerous to do this in the child,
3182 // but safe in the parent, so...
3183 if (pid == -1) // emit message signal.
3184 buffer_.message(_("Autosave failed!"));
3188 if (pid == 0) // we are the child so...
3197 FileName Buffer::getAutosaveFileName() const
3199 // if the document is unnamed try to save in the backup dir, else
3200 // in the default document path, and as a last try in the filePath,
3201 // which will most often be the temporary directory
3204 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3205 : lyxrc.backupdir_path;
3206 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3209 string const fname = "#" + d->filename.onlyFileName() + "#";
3210 return makeAbsPath(fname, fpath);
3214 void Buffer::removeAutosaveFile() const
3216 FileName const f = getAutosaveFileName();
3222 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3224 FileName const newauto = getAutosaveFileName();
3226 if (newauto != oldauto && oldauto.exists())
3227 if (!oldauto.moveTo(newauto))
3228 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3232 // Perfect target for a thread...
3233 void Buffer::autoSave() const
3235 if (d->bak_clean || isReadonly()) {
3236 // We don't save now, but we'll try again later
3237 resetAutosaveTimers();
3241 // emit message signal.
3242 message(_("Autosaving current document..."));
3243 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3246 d->bak_clean = true;
3248 resetAutosaveTimers();
3252 string Buffer::bufferFormat() const
3254 string format = params().documentClass().outputFormat();
3255 if (format == "latex") {
3256 if (params().useXetex)
3258 if (params().encoding().package() == Encoding::japanese)
3265 string Buffer::getDefaultOutputFormat() const
3267 if (!params().defaultOutputFormat.empty()
3268 && params().defaultOutputFormat != "default")
3269 return params().defaultOutputFormat;
3270 typedef vector<Format const *> Formats;
3271 Formats formats = exportableFormats(true);
3274 || params().useXetex
3275 || params().encoding().package() == Encoding::japanese) {
3276 if (formats.empty())
3278 // return the first we find
3279 return formats.front()->name();
3281 return lyxrc.default_view_format;
3286 // helper class, to guarantee this gets reset properly
3287 class MarkAsExporting {
3289 MarkAsExporting(Buffer const * buf) : buf_(buf)
3291 LASSERT(buf_, /* */);
3292 buf_->setExportStatus(true);
3296 buf_->setExportStatus(false);
3299 Buffer const * const buf_;
3304 void Buffer::setExportStatus(bool e) const
3306 d->doing_export = e;
3310 bool Buffer::isExporting() const
3312 return d->doing_export;
3316 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3317 bool includeall, string & result_file) const
3319 MarkAsExporting exporting(this);
3320 string backend_format;
3321 OutputParams runparams(¶ms().encoding());
3322 runparams.flavor = OutputParams::LATEX;
3323 runparams.linelen = lyxrc.plaintext_linelen;
3324 runparams.includeall = includeall;
3325 vector<string> backs = backends();
3326 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3327 // Get shortest path to format
3328 Graph::EdgePath path;
3329 for (vector<string>::const_iterator it = backs.begin();
3330 it != backs.end(); ++it) {
3331 Graph::EdgePath p = theConverters().getPath(*it, format);
3332 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3333 backend_format = *it;
3338 if (!put_in_tempdir) {
3339 // Only show this alert if this is an export to a non-temporary
3340 // file (not for previewing).
3341 Alert::error(_("Couldn't export file"), bformat(
3342 _("No information for exporting the format %1$s."),
3343 formats.prettyName(format)));
3347 runparams.flavor = theConverters().getFlavor(path);
3350 backend_format = format;
3351 // FIXME: Don't hardcode format names here, but use a flag
3352 if (backend_format == "pdflatex")
3353 runparams.flavor = OutputParams::PDFLATEX;
3356 string filename = latexName(false);
3357 filename = addName(temppath(), filename);
3358 filename = changeExtension(filename,
3359 formats.extension(backend_format));
3362 updateMacroInstances();
3364 // Plain text backend
3365 if (backend_format == "text") {
3366 runparams.flavor = OutputParams::TEXT;
3367 writePlaintextFile(*this, FileName(filename), runparams);
3370 else if (backend_format == "xhtml") {
3371 runparams.flavor = OutputParams::HTML;
3372 switch (params().html_math_output) {
3373 case BufferParams::MathML:
3374 runparams.math_flavor = OutputParams::MathAsMathML;
3376 case BufferParams::HTML:
3377 runparams.math_flavor = OutputParams::MathAsHTML;
3379 case BufferParams::Images:
3380 runparams.math_flavor = OutputParams::MathAsImages;
3382 case BufferParams::LaTeX:
3383 runparams.math_flavor = OutputParams::MathAsLaTeX;
3387 makeLyXHTMLFile(FileName(filename), runparams);
3388 } else if (backend_format == "lyx")
3389 writeFile(FileName(filename));
3391 else if (isDocBook()) {
3392 runparams.nice = !put_in_tempdir;
3393 makeDocBookFile(FileName(filename), runparams);
3396 else if (backend_format == format) {
3397 runparams.nice = true;
3398 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3400 } else if (!lyxrc.tex_allows_spaces
3401 && contains(filePath(), ' ')) {
3402 Alert::error(_("File name error"),
3403 _("The directory path to the document cannot contain spaces."));
3406 runparams.nice = false;
3407 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3411 string const error_type = (format == "program")
3412 ? "Build" : bufferFormat();
3413 ErrorList & error_list = d->errorLists[error_type];
3414 string const ext = formats.extension(format);
3415 FileName const tmp_result_file(changeExtension(filename, ext));
3416 bool const success = theConverters().convert(this, FileName(filename),
3417 tmp_result_file, FileName(absFileName()), backend_format, format,
3420 // Emit the signal to show the error list or copy it back to the
3421 // cloned Buffer so that it cab be emitted afterwards.
3422 if (format != backend_format) {
3423 if (d->cloned_buffer_) {
3424 d->cloned_buffer_->d->errorLists[error_type] =
3425 d->errorLists[error_type];
3428 // also to the children, in case of master-buffer-view
3429 ListOfBuffers clist = getChildren();
3430 ListOfBuffers::const_iterator cit = clist.begin();
3431 ListOfBuffers::const_iterator const cen = clist.end();
3432 for (; cit != cen; ++cit) {
3433 if (d->cloned_buffer_) {
3434 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3435 (*cit)->d->errorLists[error_type];
3437 (*cit)->errors(error_type, true);
3441 if (d->cloned_buffer_) {
3442 // Enable reverse dvi or pdf to work by copying back the texrow
3443 // object to the cloned buffer.
3444 // FIXME: There is a possibility of concurrent access to texrow
3445 // here from the main GUI thread that should be securized.
3446 d->cloned_buffer_->d->texrow = d->texrow;
3447 string const error_type = bufferFormat();
3448 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3454 if (put_in_tempdir) {
3455 result_file = tmp_result_file.absFileName();
3459 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3460 // We need to copy referenced files (e. g. included graphics
3461 // if format == "dvi") to the result dir.
3462 vector<ExportedFile> const files =
3463 runparams.exportdata->externalFiles(format);
3464 string const dest = onlyPath(result_file);
3465 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3466 : force_overwrite == ALL_FILES;
3467 CopyStatus status = use_force ? FORCE : SUCCESS;
3469 vector<ExportedFile>::const_iterator it = files.begin();
3470 vector<ExportedFile>::const_iterator const en = files.end();
3471 for (; it != en && status != CANCEL; ++it) {
3472 string const fmt = formats.getFormatFromFile(it->sourceName);
3473 status = copyFile(fmt, it->sourceName,
3474 makeAbsPath(it->exportName, dest),
3475 it->exportName, status == FORCE);
3478 if (status == CANCEL) {
3479 message(_("Document export cancelled."));
3480 } else if (tmp_result_file.exists()) {
3481 // Finally copy the main file
3482 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3483 : force_overwrite != NO_FILES;
3484 if (status == SUCCESS && use_force)
3486 status = copyFile(format, tmp_result_file,
3487 FileName(result_file), result_file,
3489 message(bformat(_("Document exported as %1$s "
3491 formats.prettyName(format),
3492 makeDisplayPath(result_file)));
3494 // This must be a dummy converter like fax (bug 1888)
3495 message(bformat(_("Document exported as %1$s"),
3496 formats.prettyName(format)));
3503 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3504 bool includeall) const
3507 // (1) export with all included children (omit \includeonly)
3508 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3510 // (2) export with included children only
3511 return doExport(format, put_in_tempdir, false, result_file);
3515 bool Buffer::preview(string const & format, bool includeall) const
3517 MarkAsExporting exporting(this);
3519 // (1) export with all included children (omit \includeonly)
3520 if (includeall && !doExport(format, true, true))
3522 // (2) export with included children only
3523 if (!doExport(format, true, false, result_file))
3525 return formats.view(*this, FileName(result_file), format);
3529 bool Buffer::isExportable(string const & format) const
3531 vector<string> backs = backends();
3532 for (vector<string>::const_iterator it = backs.begin();
3533 it != backs.end(); ++it)
3534 if (theConverters().isReachable(*it, format))
3540 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3542 vector<string> const backs = backends();
3543 vector<Format const *> result =
3544 theConverters().getReachable(backs[0], only_viewable, true);
3545 for (vector<string>::const_iterator it = backs.begin() + 1;
3546 it != backs.end(); ++it) {
3547 vector<Format const *> r =
3548 theConverters().getReachable(*it, only_viewable, false);
3549 result.insert(result.end(), r.begin(), r.end());
3555 vector<string> Buffer::backends() const
3558 v.push_back(bufferFormat());
3559 // FIXME: Don't hardcode format names here, but use a flag
3560 if (v.back() == "latex")
3561 v.push_back("pdflatex");
3562 v.push_back("xhtml");
3563 v.push_back("text");
3569 bool Buffer::readFileHelper(FileName const & s)
3571 // File information about normal file
3573 docstring const file = makeDisplayPath(s.absFileName(), 50);
3574 docstring text = bformat(_("The specified document\n%1$s"
3575 "\ncould not be read."), file);
3576 Alert::error(_("Could not read document"), text);
3580 // Check if emergency save file exists and is newer.
3581 FileName const e(s.absFileName() + ".emergency");
3583 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3584 docstring const file = makeDisplayPath(s.absFileName(), 20);
3585 docstring const text =
3586 bformat(_("An emergency save of the document "
3588 "Recover emergency save?"), file);
3589 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3590 _("&Recover"), _("&Load Original"),
3594 // the file is not saved if we load the emergency file.
3599 if ((res = readFile(e)) == success)
3600 str = _("Document was successfully recovered.");
3602 str = _("Document was NOT successfully recovered.");
3603 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3604 makeDisplayPath(e.absFileName()));
3606 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3607 _("&Remove"), _("&Keep it"))) {
3610 Alert::warning(_("Emergency file deleted"),
3611 _("Do not forget to save your file now!"), true);
3616 if (!Alert::prompt(_("Delete emergency file?"),
3617 _("Remove emergency file now?"), 1, 1,
3618 _("&Remove"), _("&Keep it")))
3626 // Now check if autosave file is newer.
3627 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3629 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3630 docstring const file = makeDisplayPath(s.absFileName(), 20);
3631 docstring const text =
3632 bformat(_("The backup of the document "
3633 "%1$s is newer.\n\nLoad the "
3634 "backup instead?"), file);
3635 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3636 _("&Load backup"), _("Load &original"),
3640 // the file is not saved if we load the autosave file.
3644 // Here we delete the autosave
3655 bool Buffer::loadLyXFile(FileName const & s)
3657 // If the file is not readable, we try to
3658 // retrieve the file from version control.
3659 if (!s.isReadableFile()
3660 && !LyXVC::file_not_found_hook(s))
3663 if (s.isReadableFile()){
3664 // InsetInfo needs to know if file is under VCS
3665 lyxvc().file_found_hook(s);
3666 if (readFileHelper(s)) {
3667 d->read_only = !s.isWritable();
3675 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3677 TeXErrors::Errors::const_iterator cit = terr.begin();
3678 TeXErrors::Errors::const_iterator end = terr.end();
3680 for (; cit != end; ++cit) {
3683 int errorRow = cit->error_in_line;
3684 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3690 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3691 } while (found && id_start == id_end && pos_start == pos_end);
3693 errorList.push_back(ErrorItem(cit->error_desc,
3694 cit->error_text, id_start, pos_start, pos_end));
3699 void Buffer::setBuffersForInsets() const
3701 inset().setBuffer(const_cast<Buffer &>(*this));
3705 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3707 // Use the master text class also for child documents
3708 Buffer const * const master = masterBuffer();
3709 DocumentClass const & textclass = master->params().documentClass();
3711 // do this only if we are the top-level Buffer
3713 checkBibInfoCache();
3715 // keep the buffers to be children in this set. If the call from the
3716 // master comes back we can see which of them were actually seen (i.e.
3717 // via an InsetInclude). The remaining ones in the set need still be updated.
3718 static std::set<Buffer const *> bufToUpdate;
3719 if (scope == UpdateMaster) {
3720 // If this is a child document start with the master
3721 if (master != this) {
3722 bufToUpdate.insert(this);
3723 master->updateBuffer(UpdateMaster, utype);
3724 // Do this here in case the master has no gui associated with it. Then,
3725 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3726 if (!master->d->gui_)
3729 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3730 if (bufToUpdate.find(this) == bufToUpdate.end())
3734 // start over the counters in the master
3735 textclass.counters().reset();
3738 // update will be done below for this buffer
3739 bufToUpdate.erase(this);
3741 // update all caches
3742 clearReferenceCache();
3745 Buffer & cbuf = const_cast<Buffer &>(*this);
3747 LASSERT(!text().paragraphs().empty(), /**/);
3750 ParIterator parit = cbuf.par_iterator_begin();
3751 updateBuffer(parit, utype);
3754 // TocBackend update will be done later.
3757 cbuf.tocBackend().update();
3758 if (scope == UpdateMaster)
3759 cbuf.structureChanged();
3763 static depth_type getDepth(DocIterator const & it)
3765 depth_type depth = 0;
3766 for (size_t i = 0 ; i < it.depth() ; ++i)
3767 if (!it[i].inset().inMathed())
3768 depth += it[i].paragraph().getDepth() + 1;
3769 // remove 1 since the outer inset does not count
3773 static depth_type getItemDepth(ParIterator const & it)
3775 Paragraph const & par = *it;
3776 LabelType const labeltype = par.layout().labeltype;
3778 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3781 // this will hold the lowest depth encountered up to now.
3782 depth_type min_depth = getDepth(it);
3783 ParIterator prev_it = it;
3786 --prev_it.top().pit();
3788 // start of nested inset: go to outer par
3790 if (prev_it.empty()) {
3791 // start of document: nothing to do
3796 // We search for the first paragraph with same label
3797 // that is not more deeply nested.
3798 Paragraph & prev_par = *prev_it;
3799 depth_type const prev_depth = getDepth(prev_it);
3800 if (labeltype == prev_par.layout().labeltype) {
3801 if (prev_depth < min_depth)
3802 return prev_par.itemdepth + 1;
3803 if (prev_depth == min_depth)
3804 return prev_par.itemdepth;
3806 min_depth = min(min_depth, prev_depth);
3807 // small optimization: if we are at depth 0, we won't
3808 // find anything else
3809 if (prev_depth == 0)
3815 static bool needEnumCounterReset(ParIterator const & it)
3817 Paragraph const & par = *it;
3818 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3819 depth_type const cur_depth = par.getDepth();
3820 ParIterator prev_it = it;
3821 while (prev_it.pit()) {
3822 --prev_it.top().pit();
3823 Paragraph const & prev_par = *prev_it;
3824 if (prev_par.getDepth() <= cur_depth)
3825 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3827 // start of nested inset: reset
3832 // set the label of a paragraph. This includes the counters.
3833 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3835 BufferParams const & bp = owner_->masterBuffer()->params();
3836 DocumentClass const & textclass = bp.documentClass();
3837 Paragraph & par = it.paragraph();
3838 Layout const & layout = par.layout();
3839 Counters & counters = textclass.counters();
3841 if (par.params().startOfAppendix()) {
3842 // FIXME: only the counter corresponding to toplevel
3843 // sectioning should be reset
3845 counters.appendix(true);
3847 par.params().appendix(counters.appendix());
3849 // Compute the item depth of the paragraph
3850 par.itemdepth = getItemDepth(it);
3852 if (layout.margintype == MARGIN_MANUAL
3853 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3854 if (par.params().labelWidthString().empty())
3855 par.params().labelWidthString(par.expandLabel(layout, bp));
3857 par.params().labelWidthString(docstring());
3860 switch(layout.labeltype) {
3862 if (layout.toclevel <= bp.secnumdepth
3863 && (layout.latextype != LATEX_ENVIRONMENT
3864 || it.text()->isFirstInSequence(it.pit()))) {
3865 counters.step(layout.counter, utype);
3866 par.params().labelString(
3867 par.expandLabel(layout, bp));
3869 par.params().labelString(docstring());
3872 case LABEL_ITEMIZE: {
3873 // At some point of time we should do something more
3874 // clever here, like:
3875 // par.params().labelString(
3876 // bp.user_defined_bullet(par.itemdepth).getText());
3877 // for now, use a simple hardcoded label
3878 docstring itemlabel;
3879 switch (par.itemdepth) {
3881 itemlabel = char_type(0x2022);
3884 itemlabel = char_type(0x2013);
3887 itemlabel = char_type(0x2217);
3890 itemlabel = char_type(0x2219); // or 0x00b7
3893 par.params().labelString(itemlabel);
3897 case LABEL_ENUMERATE: {
3898 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3900 switch (par.itemdepth) {
3909 enumcounter += "iv";
3912 // not a valid enumdepth...
3916 // Maybe we have to reset the enumeration counter.
3917 if (needEnumCounterReset(it))
3918 counters.reset(enumcounter);
3919 counters.step(enumcounter, utype);
3921 string const & lang = par.getParLanguage(bp)->code();
3922 par.params().labelString(counters.theCounter(enumcounter, lang));
3927 case LABEL_SENSITIVE: {
3928 string const & type = counters.current_float();
3929 docstring full_label;
3931 full_label = owner_->B_("Senseless!!! ");
3933 docstring name = owner_->B_(textclass.floats().getType(type).name());
3934 if (counters.hasCounter(from_utf8(type))) {
3935 string const & lang = par.getParLanguage(bp)->code();
3936 counters.step(from_utf8(type), utype);
3937 full_label = bformat(from_ascii("%1$s %2$s:"),
3939 counters.theCounter(from_utf8(type), lang));
3941 full_label = bformat(from_ascii("%1$s #:"), name);
3943 par.params().labelString(full_label);
3947 case LABEL_NO_LABEL:
3948 par.params().labelString(docstring());
3952 case LABEL_TOP_ENVIRONMENT:
3953 case LABEL_CENTERED_TOP_ENVIRONMENT:
3956 par.params().labelString(par.expandLabel(layout, bp));
3962 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3964 LASSERT(parit.pit() == 0, /**/);
3966 // set the position of the text in the buffer to be able
3967 // to resolve macros in it. This has nothing to do with
3968 // labels, but by putting it here we avoid implementing
3969 // a whole bunch of traversal routines just for this call.
3970 parit.text()->setMacrocontextPosition(parit);
3972 depth_type maxdepth = 0;
3973 pit_type const lastpit = parit.lastpit();
3974 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3975 // reduce depth if necessary
3976 parit->params().depth(min(parit->params().depth(), maxdepth));
3977 maxdepth = parit->getMaxDepthAfter();
3979 if (utype == OutputUpdate) {
3980 // track the active counters
3981 // we have to do this for the master buffer, since the local
3982 // buffer isn't tracking anything.
3983 masterBuffer()->params().documentClass().counters().
3984 setActiveLayout(parit->layout());
3987 // set the counter for this paragraph
3988 d->setLabel(parit, utype);
3991 InsetList::const_iterator iit = parit->insetList().begin();
3992 InsetList::const_iterator end = parit->insetList().end();
3993 for (; iit != end; ++iit) {
3994 parit.pos() = iit->pos;
3995 iit->inset->updateBuffer(parit, utype);
4001 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4002 WordLangTuple & word_lang, docstring_list & suggestions) const
4006 suggestions.clear();
4007 word_lang = WordLangTuple();
4008 // OK, we start from here.
4009 DocIterator const end = doc_iterator_end(this);
4010 for (; from != end; from.forwardPos()) {
4011 // We are only interested in text so remove the math CursorSlice.
4012 while (from.inMathed()) {
4016 // If from is at the end of the document (which is possible
4017 // when leaving the mathed) LyX will crash later.
4021 from.paragraph().spellCheck();
4022 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4023 if (SpellChecker::misspelled(res)) {
4028 // Do not increase progress when from == to, otherwise the word
4029 // count will be wrong.
4039 bool Buffer::reload()
4043 removeAutosaveFile();
4044 // e.g., read-only status could have changed due to version control
4045 d->filename.refresh();
4046 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4048 bool const success = loadLyXFile(d->filename);
4054 message(bformat(_("Document %1$s reloaded."), disp_fn));
4056 message(bformat(_("Could not reload document %1$s."), disp_fn));
4059 thePreviews().removeLoader(*this);
4060 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4061 thePreviews().generateBufferPreviews(*this);
4067 // FIXME We could do better here, but it is complicated. What would be
4068 // nice is to offer either (a) to save the child buffer to an appropriate
4069 // location, so that it would "move with the master", or else (b) to update
4070 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4071 // complicated, because the code for this lives in GuiView.
4072 void Buffer::checkChildBuffers()
4074 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4075 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4076 for (; it != en; ++it) {
4077 DocIterator dit = it->second;
4078 Buffer * cbuf = const_cast<Buffer *>(it->first);
4079 if (!cbuf || !theBufferList().isLoaded(cbuf))
4081 Inset * inset = dit.nextInset();
4082 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4083 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4084 docstring const & incfile = inset_inc->getParam("filename");
4085 string oldloc = cbuf->absFileName();
4086 string newloc = makeAbsPath(to_utf8(incfile),
4087 onlyPath(absFileName())).absFileName();
4088 if (oldloc == newloc)
4090 // the location of the child file is incorrect.
4091 Alert::warning(_("Included File Invalid"),
4092 bformat(_("Saving this document to a new location has made the file:\n"
4094 "inaccessible. You will need to update the included filename."),
4095 from_utf8(oldloc)));
4097 inset_inc->setChildBuffer(0);
4099 // invalidate cache of children
4100 d->children_positions.clear();
4101 d->position_to_children.clear();