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"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.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 <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
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 = 375; // jspitzm: includeonly support
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);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfiles_cache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfo_cache_valid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfile_status_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
316 LYXERR(Debug::INFO, "Buffer::Buffer()");
318 d->inset = new InsetText(*cloned_buffer->d->inset);
319 d->inset->setBuffer(*this);
320 // FIXME: optimize this loop somewhat, maybe by creating a new
321 // general recursive Inset::setId().
322 DocIterator it = doc_iterator_begin(this);
323 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
324 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
325 it.paragraph().setId(cloned_it.paragraph().id());
327 d->inset = new InsetText(this);
328 d->inset->setAutoBreakRows(true);
329 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
335 LYXERR(Debug::INFO, "Buffer::~Buffer()");
336 // here the buffer should take care that it is
337 // saved properly, before it goes into the void.
339 // GuiView already destroyed
343 // No need to do additional cleanups for internal buffer.
348 // loop over children
349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
350 Impl::BufferPositionMap::iterator end = d->children_positions.end();
351 for (; it != end; ++it) {
352 Buffer * child = const_cast<Buffer *>(it->first);
353 // The child buffer might have been closed already.
354 if (theBufferList().isLoaded(child))
355 theBufferList().releaseChild(this, child);
359 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
360 msg += emergencyWrite();
361 Alert::warning(_("Attempting to close changed document!"), msg);
364 // clear references to children in macro tables
365 d->children_positions.clear();
366 d->position_to_children.clear();
368 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
369 Alert::warning(_("Could not remove temporary directory"),
370 bformat(_("Could not remove the temporary directory %1$s"),
371 from_utf8(d->temppath.absFilename())));
374 // Remove any previewed LaTeX snippets associated with this buffer.
375 thePreviews().removeLoader(*this);
381 Buffer * Buffer::clone() const
383 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
384 buffer_clone->d->macro_lock = true;
385 buffer_clone->d->children_positions.clear();
386 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
387 // math macro caches need to be rethought and simplified.
388 // I am not sure wether we should handle Buffer cloning here or in BufferList.
389 // Right now BufferList knows nothing about buffer clones.
390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
392 for (; it != end; ++it) {
393 DocIterator dit = it->second.clone(buffer_clone);
394 dit.setBuffer(buffer_clone);
395 Buffer * child = const_cast<Buffer *>(it->first);
396 Buffer * child_clone = child->clone();
397 Inset * inset = dit.nextInset();
398 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
399 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
400 inset_inc->setChildBuffer(child_clone);
401 child_clone->d->setParent(buffer_clone);
402 buffer_clone->setChild(dit, child_clone);
408 bool Buffer::isClone() const
410 return d->cloned_buffer_;
414 void Buffer::changed(bool update_metrics) const
417 d->wa_->redrawAll(update_metrics);
421 frontend::WorkAreaManager & Buffer::workAreaManager() const
423 LASSERT(d->wa_, /**/);
428 Text & Buffer::text() const
430 return d->inset->text();
434 Inset & Buffer::inset() const
440 BufferParams & Buffer::params()
446 BufferParams const & Buffer::params() const
452 ParagraphList & Buffer::paragraphs()
454 return text().paragraphs();
458 ParagraphList const & Buffer::paragraphs() const
460 return text().paragraphs();
464 LyXVC & Buffer::lyxvc()
470 LyXVC const & Buffer::lyxvc() const
476 string const Buffer::temppath() const
478 return d->temppath.absFilename();
482 TexRow & Buffer::texrow()
488 TexRow const & Buffer::texrow() const
494 TocBackend & Buffer::tocBackend() const
496 return d->toc_backend;
500 Undo & Buffer::undo()
506 void Buffer::setChild(DocIterator const & dit, Buffer * child)
508 d->children_positions[child] = dit;
512 string Buffer::latexName(bool const no_path) const
514 FileName latex_name =
515 makeLatexName(exportFileName());
516 return no_path ? latex_name.onlyFileName()
517 : latex_name.absFilename();
521 FileName Buffer::exportFileName() const
523 docstring const branch_suffix =
524 params().branchlist().getFilenameSuffix();
525 if (branch_suffix.empty())
528 string const name = fileName().onlyFileNameWithoutExt()
529 + to_utf8(branch_suffix);
530 FileName res(fileName().onlyPath().absFilename() + "/" + name);
531 res.changeExtension(fileName().extension());
537 string Buffer::logName(LogType * type) const
539 string const filename = latexName(false);
541 if (filename.empty()) {
547 string const path = temppath();
549 FileName const fname(addName(temppath(),
550 onlyFilename(changeExtension(filename,
553 // FIXME: how do we know this is the name of the build log?
554 FileName const bname(
555 addName(path, onlyFilename(
556 changeExtension(filename,
557 formats.extension(bufferFormat()) + ".out"))));
559 // Also consider the master buffer log file
560 FileName masterfname = fname;
562 if (masterBuffer() != this) {
563 string const mlogfile = masterBuffer()->logName(&mtype);
564 masterfname = FileName(mlogfile);
567 // If no Latex log or Build log is newer, show Build log
568 if (bname.exists() &&
569 ((!fname.exists() && !masterfname.exists())
570 || (fname.lastModified() < bname.lastModified()
571 && masterfname.lastModified() < bname.lastModified()))) {
572 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
575 return bname.absFilename();
576 // If we have a newer master file log or only a master log, show this
577 } else if (fname != masterfname
578 && (!fname.exists() && (masterfname.exists()
579 || fname.lastModified() < masterfname.lastModified()))) {
580 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
583 return masterfname.absFilename();
585 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
588 return fname.absFilename();
592 void Buffer::setReadonly(bool const flag)
594 if (d->read_only != flag) {
601 void Buffer::setFileName(string const & newfile)
603 d->filename = makeAbsPath(newfile);
604 setReadonly(d->filename.isReadOnly());
609 int Buffer::readHeader(Lexer & lex)
611 int unknown_tokens = 0;
613 int begin_header_line = -1;
615 // Initialize parameters that may be/go lacking in header:
616 params().branchlist().clear();
617 params().preamble.erase();
618 params().options.erase();
619 params().master.erase();
620 params().float_placement.erase();
621 params().paperwidth.erase();
622 params().paperheight.erase();
623 params().leftmargin.erase();
624 params().rightmargin.erase();
625 params().topmargin.erase();
626 params().bottommargin.erase();
627 params().headheight.erase();
628 params().headsep.erase();
629 params().footskip.erase();
630 params().columnsep.erase();
631 params().fontsCJK.erase();
632 params().listings_params.clear();
633 params().clearLayoutModules();
634 params().clearRemovedModules();
635 params().clearIncludedChildren();
636 params().pdfoptions().clear();
637 params().indiceslist().clear();
638 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
640 for (int i = 0; i < 4; ++i) {
641 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
642 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
645 ErrorList & errorList = d->errorLists["Parse"];
654 if (token == "\\end_header")
658 if (token == "\\begin_header") {
659 begin_header_line = line;
663 LYXERR(Debug::PARSER, "Handling document header token: `"
666 string unknown = params().readToken(lex, token, d->filename.onlyPath());
667 if (!unknown.empty()) {
668 if (unknown[0] != '\\' && token == "\\textclass") {
669 Alert::warning(_("Unknown document class"),
670 bformat(_("Using the default document class, because the "
671 "class %1$s is unknown."), from_utf8(unknown)));
674 docstring const s = bformat(_("Unknown token: "
678 errorList.push_back(ErrorItem(_("Document header error"),
683 if (begin_header_line) {
684 docstring const s = _("\\begin_header is missing");
685 errorList.push_back(ErrorItem(_("Document header error"),
689 params().makeDocumentClass();
691 return unknown_tokens;
696 // changed to be public and have one parameter
697 // Returns true if "\end_document" is not read (Asger)
698 bool Buffer::readDocument(Lexer & lex)
700 ErrorList & errorList = d->errorLists["Parse"];
703 if (!lex.checkFor("\\begin_document")) {
704 docstring const s = _("\\begin_document is missing");
705 errorList.push_back(ErrorItem(_("Document header error"),
709 // we are reading in a brand new document
710 LASSERT(paragraphs().empty(), /**/);
714 if (params().outputChanges) {
715 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
716 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
717 LaTeXFeatures::isAvailable("xcolor");
719 if (!dvipost && !xcolorulem) {
720 Alert::warning(_("Changes not shown in LaTeX output"),
721 _("Changes will not be highlighted in LaTeX output, "
722 "because neither dvipost nor xcolor/ulem are installed.\n"
723 "Please install these packages or redefine "
724 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
725 } else if (!xcolorulem) {
726 Alert::warning(_("Changes not shown in LaTeX output"),
727 _("Changes will not be highlighted in LaTeX output "
728 "when using pdflatex, because xcolor and ulem are not installed.\n"
729 "Please install both packages or redefine "
730 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
734 if (!params().master.empty()) {
735 FileName const master_file = makeAbsPath(params().master,
736 onlyPath(absFileName()));
737 if (isLyXFilename(master_file.absFilename())) {
739 checkAndLoadLyXFile(master_file, true);
741 // necessary e.g. after a reload
742 // to re-register the child (bug 5873)
743 // FIXME: clean up updateMacros (here, only
744 // child registering is needed).
745 master->updateMacros();
746 // set master as master buffer, but only
747 // if we are a real child
748 if (master->isChild(this))
750 // if the master is not fully loaded
751 // it is probably just loading this
752 // child. No warning needed then.
753 else if (master->isFullyLoaded())
754 LYXERR0("The master '"
756 << "' assigned to this document ("
758 << ") does not include "
759 "this document. Ignoring the master assignment.");
764 // assure we have a default index
765 params().indiceslist().addDefault(B_("Index"));
768 bool const res = text().read(lex, errorList, d->inset);
772 updateMacroInstances();
777 bool Buffer::readString(string const & s)
779 params().compressed = false;
781 // remove dummy empty par
782 paragraphs().clear();
786 FileName const name = FileName::tempName("Buffer_readString");
787 switch (readFile(lex, name, true)) {
791 // We need to call lyx2lyx, so write the input to a file
792 ofstream os(name.toFilesystemEncoding().c_str());
795 return readFile(name);
805 bool Buffer::readFile(FileName const & filename)
807 FileName fname(filename);
809 params().compressed = fname.isZippedFile();
811 // remove dummy empty par
812 paragraphs().clear();
815 if (readFile(lex, fname) != success)
822 bool Buffer::isFullyLoaded() const
824 return d->file_fully_loaded;
828 void Buffer::setFullyLoaded(bool value)
830 d->file_fully_loaded = value;
834 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
837 LASSERT(!filename.empty(), /**/);
839 // the first (non-comment) token _must_ be...
840 if (!lex.checkFor("\\lyxformat")) {
841 Alert::error(_("Document format failure"),
842 bformat(_("%1$s is not a readable LyX document."),
843 from_utf8(filename.absFilename())));
849 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
850 // if present remove ".," from string.
851 size_t dot = tmp_format.find_first_of(".,");
852 //lyxerr << " dot found at " << dot << endl;
853 if (dot != string::npos)
854 tmp_format.erase(dot, 1);
855 int const file_format = convert<int>(tmp_format);
856 //lyxerr << "format: " << file_format << endl;
858 // save timestamp and checksum of the original disk file, making sure
859 // to not overwrite them with those of the file created in the tempdir
860 // when it has to be converted to the current format.
862 // Save the timestamp and checksum of disk file. If filename is an
863 // emergency file, save the timestamp and checksum of the original lyx file
864 // because isExternallyModified will check for this file. (BUG4193)
865 string diskfile = filename.absFilename();
866 if (suffixIs(diskfile, ".emergency"))
867 diskfile = diskfile.substr(0, diskfile.size() - 10);
868 saveCheckSum(FileName(diskfile));
871 if (file_format != LYX_FORMAT) {
874 // lyx2lyx would fail
877 FileName const tmpfile = FileName::tempName("Buffer_readFile");
878 if (tmpfile.empty()) {
879 Alert::error(_("Conversion failed"),
880 bformat(_("%1$s is from a different"
881 " version of LyX, but a temporary"
882 " file for converting it could"
884 from_utf8(filename.absFilename())));
887 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
888 if (lyx2lyx.empty()) {
889 Alert::error(_("Conversion script not found"),
890 bformat(_("%1$s is from a different"
891 " version of LyX, but the"
892 " conversion script lyx2lyx"
893 " could not be found."),
894 from_utf8(filename.absFilename())));
897 ostringstream command;
898 command << os::python()
899 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
900 << " -t " << convert<string>(LYX_FORMAT)
901 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
902 << ' ' << quoteName(filename.toFilesystemEncoding());
903 string const command_str = command.str();
905 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
907 cmd_ret const ret = runCommand(command_str);
908 if (ret.first != 0) {
909 Alert::error(_("Conversion script failed"),
910 bformat(_("%1$s is from a different version"
911 " of LyX, but the lyx2lyx script"
912 " failed to convert it."),
913 from_utf8(filename.absFilename())));
916 bool const ret = readFile(tmpfile);
917 // Do stuff with tmpfile name and buffer name here.
918 return ret ? success : failure;
923 if (readDocument(lex)) {
924 Alert::error(_("Document format failure"),
925 bformat(_("%1$s ended unexpectedly, which means"
926 " that it is probably corrupted."),
927 from_utf8(filename.absFilename())));
930 d->file_fully_loaded = true;
935 // Should probably be moved to somewhere else: BufferView? LyXView?
936 bool Buffer::save() const
938 // We don't need autosaves in the immediate future. (Asger)
939 resetAutosaveTimers();
941 string const encodedFilename = d->filename.toFilesystemEncoding();
944 bool madeBackup = false;
946 // make a backup if the file already exists
947 if (lyxrc.make_backup && fileName().exists()) {
948 backupName = FileName(absFileName() + '~');
949 if (!lyxrc.backupdir_path.empty()) {
950 string const mangledName =
951 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
952 backupName = FileName(addName(lyxrc.backupdir_path,
955 if (fileName().copyTo(backupName)) {
958 Alert::error(_("Backup failure"),
959 bformat(_("Cannot create backup file %1$s.\n"
960 "Please check whether the directory exists and is writeable."),
961 from_utf8(backupName.absFilename())));
962 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
966 // ask if the disk file has been externally modified (use checksum method)
967 if (fileName().exists() && isExternallyModified(checksum_method)) {
968 docstring const file = makeDisplayPath(absFileName(), 20);
969 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
970 "you want to overwrite this file?"), file);
971 int const ret = Alert::prompt(_("Overwrite modified file?"),
972 text, 1, 1, _("&Overwrite"), _("&Cancel"));
977 if (writeFile(d->filename)) {
981 // Saving failed, so backup is not backup
983 backupName.moveTo(d->filename);
989 bool Buffer::writeFile(FileName const & fname) const
991 if (d->read_only && fname == d->filename)
996 docstring const str = bformat(_("Saving document %1$s..."),
997 makeDisplayPath(fname.absFilename()));
1000 if (params().compressed) {
1001 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1002 retval = ofs && write(ofs);
1004 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1005 retval = ofs && write(ofs);
1009 message(str + _(" could not write file!"));
1013 removeAutosaveFile();
1015 saveCheckSum(d->filename);
1016 message(str + _(" done."));
1022 docstring Buffer::emergencyWrite()
1024 // No need to save if the buffer has not changed.
1028 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1030 docstring user_message = bformat(
1031 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1033 // We try to save three places:
1034 // 1) Same place as document. Unless it is an unnamed doc.
1036 string s = absFileName();
1039 if (writeFile(FileName(s))) {
1041 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1042 return user_message;
1044 user_message += _(" Save failed! Trying again...\n");
1048 // 2) In HOME directory.
1049 string s = addName(package().home_dir().absFilename(), absFileName());
1051 lyxerr << ' ' << s << endl;
1052 if (writeFile(FileName(s))) {
1054 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1055 return user_message;
1058 user_message += _(" Save failed! Trying yet again...\n");
1060 // 3) In "/tmp" directory.
1061 // MakeAbsPath to prepend the current
1062 // drive letter on OS/2
1063 s = addName(package().temp_dir().absFilename(), absFileName());
1065 lyxerr << ' ' << s << endl;
1066 if (writeFile(FileName(s))) {
1068 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1069 return user_message;
1072 user_message += _(" Save failed! Bummer. Document is lost.");
1075 return user_message;
1079 bool Buffer::write(ostream & ofs) const
1082 // Use the standard "C" locale for file output.
1083 ofs.imbue(locale::classic());
1086 // The top of the file should not be written by params().
1088 // write out a comment in the top of the file
1089 ofs << "#LyX " << lyx_version
1090 << " created this file. For more info see http://www.lyx.org/\n"
1091 << "\\lyxformat " << LYX_FORMAT << "\n"
1092 << "\\begin_document\n";
1094 /// For each author, set 'used' to true if there is a change
1095 /// by this author in the document; otherwise set it to 'false'.
1096 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1097 AuthorList::Authors::const_iterator a_end = params().authors().end();
1098 for (; a_it != a_end; ++a_it)
1099 a_it->setUsed(false);
1101 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1102 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1103 for ( ; it != end; ++it)
1104 it->checkAuthors(params().authors());
1106 // now write out the buffer parameters.
1107 ofs << "\\begin_header\n";
1108 params().writeFile(ofs);
1109 ofs << "\\end_header\n";
1112 ofs << "\n\\begin_body\n";
1114 ofs << "\n\\end_body\n";
1116 // Write marker that shows file is complete
1117 ofs << "\\end_document" << endl;
1119 // Shouldn't really be needed....
1122 // how to check if close went ok?
1123 // Following is an attempt... (BE 20001011)
1125 // good() returns false if any error occured, including some
1126 // formatting error.
1127 // bad() returns true if something bad happened in the buffer,
1128 // which should include file system full errors.
1133 lyxerr << "File was not closed properly." << endl;
1140 bool Buffer::makeLaTeXFile(FileName const & fname,
1141 string const & original_path,
1142 OutputParams const & runparams_in,
1143 bool output_preamble, bool output_body) const
1145 OutputParams runparams = runparams_in;
1146 if (params().useXetex)
1147 runparams.flavor = OutputParams::XETEX;
1149 string const encoding = runparams.encoding->iconvName();
1150 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1153 try { ofs.reset(encoding); }
1154 catch (iconv_codecvt_facet_exception & e) {
1155 lyxerr << "Caught iconv exception: " << e.what() << endl;
1156 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1157 "verify that the support software for your encoding (%1$s) is "
1158 "properly installed"), from_ascii(encoding)));
1161 if (!openFileWrite(ofs, fname))
1164 //TexStream ts(ofs.rdbuf(), &texrow());
1165 ErrorList & errorList = d->errorLists["Export"];
1167 bool failed_export = false;
1170 writeLaTeXSource(ofs, original_path,
1171 runparams, output_preamble, output_body);
1173 catch (EncodingException & e) {
1174 odocstringstream ods;
1175 ods.put(e.failed_char);
1177 oss << "0x" << hex << e.failed_char << dec;
1178 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1179 " (code point %2$s)"),
1180 ods.str(), from_utf8(oss.str()));
1181 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1182 "representable in the chosen encoding.\n"
1183 "Changing the document encoding to utf8 could help."),
1184 e.par_id, e.pos, e.pos + 1));
1185 failed_export = true;
1187 catch (iconv_codecvt_facet_exception & e) {
1188 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1189 _(e.what()), -1, 0, 0));
1190 failed_export = true;
1192 catch (exception const & e) {
1193 errorList.push_back(ErrorItem(_("conversion failed"),
1194 _(e.what()), -1, 0, 0));
1195 failed_export = true;
1198 lyxerr << "Caught some really weird exception..." << endl;
1204 failed_export = true;
1205 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1209 return !failed_export;
1213 void Buffer::writeLaTeXSource(odocstream & os,
1214 string const & original_path,
1215 OutputParams const & runparams_in,
1216 bool const output_preamble, bool const output_body) const
1218 // The child documents, if any, shall be already loaded at this point.
1220 OutputParams runparams = runparams_in;
1222 // Classify the unicode characters appearing in math insets
1223 Encodings::initUnicodeMath(*this);
1225 // validate the buffer.
1226 LYXERR(Debug::LATEX, " Validating buffer...");
1227 LaTeXFeatures features(*this, params(), runparams);
1229 LYXERR(Debug::LATEX, " Buffer validation done.");
1231 // The starting paragraph of the coming rows is the
1232 // first paragraph of the document. (Asger)
1233 if (output_preamble && runparams.nice) {
1234 os << "%% LyX " << lyx_version << " created this file. "
1235 "For more info, see http://www.lyx.org/.\n"
1236 "%% Do not edit unless you really know what "
1238 d->texrow.newline();
1239 d->texrow.newline();
1241 LYXERR(Debug::INFO, "lyx document header finished");
1243 // Don't move this behind the parent_buffer=0 code below,
1244 // because then the macros will not get the right "redefinition"
1245 // flag as they don't see the parent macros which are output before.
1248 // fold macros if possible, still with parent buffer as the
1249 // macros will be put in the prefix anyway.
1250 updateMacroInstances();
1252 // There are a few differences between nice LaTeX and usual files:
1253 // usual is \batchmode and has a
1254 // special input@path to allow the including of figures
1255 // with either \input or \includegraphics (what figinsets do).
1256 // input@path is set when the actual parameter
1257 // original_path is set. This is done for usual tex-file, but not
1258 // for nice-latex-file. (Matthias 250696)
1259 // Note that input@path is only needed for something the user does
1260 // in the preamble, included .tex files or ERT, files included by
1261 // LyX work without it.
1262 if (output_preamble) {
1263 if (!runparams.nice) {
1264 // code for usual, NOT nice-latex-file
1265 os << "\\batchmode\n"; // changed
1266 // from \nonstopmode
1267 d->texrow.newline();
1269 if (!original_path.empty()) {
1271 // We don't know the encoding of inputpath
1272 docstring const inputpath = from_utf8(latex_path(original_path));
1273 os << "\\makeatletter\n"
1274 << "\\def\\input@path{{"
1275 << inputpath << "/}}\n"
1276 << "\\makeatother\n";
1277 d->texrow.newline();
1278 d->texrow.newline();
1279 d->texrow.newline();
1282 // get parent macros (if this buffer has a parent) which will be
1283 // written at the document begin further down.
1284 MacroSet parentMacros;
1285 listParentMacros(parentMacros, features);
1287 // Write the preamble
1288 runparams.use_babel = params().writeLaTeX(os, features,
1290 d->filename.onlyPath());
1292 runparams.use_japanese = features.isRequired("japanese");
1298 os << "\\begin{document}\n";
1299 d->texrow.newline();
1301 // output the parent macros
1302 MacroSet::iterator it = parentMacros.begin();
1303 MacroSet::iterator end = parentMacros.end();
1304 for (; it != end; ++it)
1305 (*it)->write(os, true);
1306 } // output_preamble
1308 d->texrow.start(paragraphs().begin()->id(), 0);
1310 LYXERR(Debug::INFO, "preamble finished, now the body.");
1312 // if we are doing a real file with body, even if this is the
1313 // child of some other buffer, let's cut the link here.
1314 // This happens for example if only a child document is printed.
1315 Buffer const * save_parent = 0;
1316 if (output_preamble) {
1317 save_parent = d->parent();
1322 latexParagraphs(*this, text(), os, d->texrow, runparams);
1324 // Restore the parenthood if needed
1325 if (output_preamble)
1326 d->setParent(save_parent);
1328 // add this just in case after all the paragraphs
1330 d->texrow.newline();
1332 if (output_preamble) {
1333 os << "\\end{document}\n";
1334 d->texrow.newline();
1335 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1337 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1339 runparams_in.encoding = runparams.encoding;
1341 // Just to be sure. (Asger)
1342 d->texrow.newline();
1344 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1345 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1349 bool Buffer::isLatex() const
1351 return params().documentClass().outputType() == LATEX;
1355 bool Buffer::isLiterate() const
1357 return params().documentClass().outputType() == LITERATE;
1361 bool Buffer::isDocBook() const
1363 return params().documentClass().outputType() == DOCBOOK;
1367 void Buffer::makeDocBookFile(FileName const & fname,
1368 OutputParams const & runparams,
1369 bool const body_only) const
1371 LYXERR(Debug::LATEX, "makeDocBookFile...");
1374 if (!openFileWrite(ofs, fname))
1377 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1381 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1385 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1386 OutputParams const & runparams,
1387 bool const only_body) const
1389 LaTeXFeatures features(*this, params(), runparams);
1394 DocumentClass const & tclass = params().documentClass();
1395 string const top_element = tclass.latexname();
1398 if (runparams.flavor == OutputParams::XML)
1399 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1402 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1405 if (! tclass.class_header().empty())
1406 os << from_ascii(tclass.class_header());
1407 else if (runparams.flavor == OutputParams::XML)
1408 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1409 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1411 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1413 docstring preamble = from_utf8(params().preamble);
1414 if (runparams.flavor != OutputParams::XML ) {
1415 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1416 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1417 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1418 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1421 string const name = runparams.nice
1422 ? changeExtension(absFileName(), ".sgml") : fname;
1423 preamble += features.getIncludedFiles(name);
1424 preamble += features.getLyXSGMLEntities();
1426 if (!preamble.empty()) {
1427 os << "\n [ " << preamble << " ]";
1432 string top = top_element;
1434 if (runparams.flavor == OutputParams::XML)
1435 top += params().language->code();
1437 top += params().language->code().substr(0, 2);
1440 if (!params().options.empty()) {
1442 top += params().options;
1445 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1446 << " file was created by LyX " << lyx_version
1447 << "\n See http://www.lyx.org/ for more information -->\n";
1449 params().documentClass().counters().reset();
1453 sgml::openTag(os, top);
1455 docbookParagraphs(text(), *this, os, runparams);
1456 sgml::closeTag(os, top_element);
1460 void Buffer::makeLyXHTMLFile(FileName const & fname,
1461 OutputParams const & runparams,
1462 bool const body_only) const
1464 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1467 if (!openFileWrite(ofs, fname))
1470 writeLyXHTMLSource(ofs, runparams, body_only);
1474 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1478 void Buffer::writeLyXHTMLSource(odocstream & os,
1479 OutputParams const & runparams,
1480 bool const only_body) const
1482 LaTeXFeatures features(*this, params(), runparams);
1484 updateLabels(UpdateMaster, true);
1485 checkBibInfoCache();
1486 d->bibinfo_.makeCitationLabels(*this);
1489 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1490 os << "<!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";
1491 // FIXME Language should be set properly.
1492 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1495 // FIXME Presumably need to set this right
1496 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1497 // FIXME Get this during validation? What about other meta-data?
1498 os << "<title>TBA</title>\n";
1500 os << "\n<!-- Text Class Preamble -->\n"
1501 << features.getTClassHTMLPreamble()
1502 << "\n<!-- Premable Snippets -->\n"
1503 << from_utf8(features.getPreambleSnippets());
1505 os << "\n<!-- Layout-provided Styles -->\n";
1506 docstring const styleinfo = features.getTClassHTMLStyles();
1507 if (!styleinfo.empty()) {
1508 os << "<style type='text/css'>\n"
1512 os << "</head>\n<body>\n";
1516 params().documentClass().counters().reset();
1517 xhtmlParagraphs(text(), *this, xs, runparams);
1519 os << "</body>\n</html>\n";
1523 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1524 // Other flags: -wall -v0 -x
1525 int Buffer::runChktex()
1529 // get LaTeX-Filename
1530 FileName const path(temppath());
1531 string const name = addName(path.absFilename(), latexName());
1532 string const org_path = filePath();
1534 PathChanger p(path); // path to LaTeX file
1535 message(_("Running chktex..."));
1537 // Generate the LaTeX file if neccessary
1538 OutputParams runparams(¶ms().encoding());
1539 runparams.flavor = OutputParams::LATEX;
1540 runparams.nice = false;
1541 makeLaTeXFile(FileName(name), org_path, runparams);
1544 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1545 int const res = chktex.run(terr); // run chktex
1548 Alert::error(_("chktex failure"),
1549 _("Could not run chktex successfully."));
1550 } else if (res > 0) {
1551 ErrorList & errlist = d->errorLists["ChkTeX"];
1553 bufferErrors(terr, errlist);
1564 void Buffer::validate(LaTeXFeatures & features) const
1566 params().validate(features);
1570 for_each(paragraphs().begin(), paragraphs().end(),
1571 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1573 if (lyxerr.debugging(Debug::LATEX)) {
1574 features.showStruct();
1579 void Buffer::getLabelList(vector<docstring> & list) const
1581 // If this is a child document, use the parent's list instead.
1582 Buffer const * const pbuf = d->parent();
1584 pbuf->getLabelList(list);
1589 Toc & toc = d->toc_backend.toc("label");
1590 TocIterator toc_it = toc.begin();
1591 TocIterator end = toc.end();
1592 for (; toc_it != end; ++toc_it) {
1593 if (toc_it->depth() == 0)
1594 list.push_back(toc_it->str());
1599 void Buffer::updateBibfilesCache(UpdateScope scope) const
1601 // If this is a child document, use the parent's cache instead.
1602 Buffer const * const pbuf = d->parent();
1603 if (pbuf && scope != UpdateChildOnly) {
1604 pbuf->updateBibfilesCache();
1608 d->bibfiles_cache_.clear();
1609 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1610 if (it->lyxCode() == BIBTEX_CODE) {
1611 InsetBibtex const & inset =
1612 static_cast<InsetBibtex const &>(*it);
1613 support::FileNameList const bibfiles = inset.getBibFiles();
1614 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1617 } else if (it->lyxCode() == INCLUDE_CODE) {
1618 InsetInclude & inset =
1619 static_cast<InsetInclude &>(*it);
1620 inset.updateBibfilesCache();
1621 support::FileNameList const & bibfiles =
1622 inset.getBibfilesCache();
1623 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1628 // the bibinfo cache is now invalid
1629 d->bibinfo_cache_valid_ = false;
1633 void Buffer::invalidateBibinfoCache()
1635 d->bibinfo_cache_valid_ = false;
1639 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1641 // If this is a child document, use the parent's cache instead.
1642 Buffer const * const pbuf = d->parent();
1643 if (pbuf && scope != UpdateChildOnly)
1644 return pbuf->getBibfilesCache();
1646 // We update the cache when first used instead of at loading time.
1647 if (d->bibfiles_cache_.empty())
1648 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1650 return d->bibfiles_cache_;
1654 BiblioInfo const & Buffer::masterBibInfo() const
1656 // if this is a child document and the parent is already loaded
1657 // use the parent's list instead [ale990412]
1658 Buffer const * const tmp = masterBuffer();
1661 return tmp->masterBibInfo();
1662 return localBibInfo();
1666 BiblioInfo const & Buffer::localBibInfo() const
1668 checkBibInfoCache();
1673 void Buffer::checkBibInfoCache() const
1675 support::FileNameList const & bibfilesCache = getBibfilesCache();
1676 // compare the cached timestamps with the actual ones.
1677 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1678 support::FileNameList::const_iterator en = bibfilesCache.end();
1679 for (; ei != en; ++ ei) {
1680 time_t lastw = ei->lastModified();
1681 time_t prevw = d->bibfile_status_[*ei];
1682 if (lastw != prevw) {
1683 d->bibinfo_cache_valid_ = false;
1684 d->bibfile_status_[*ei] = lastw;
1688 if (!d->bibinfo_cache_valid_) {
1689 d->bibinfo_.clear();
1690 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1691 it->fillWithBibKeys(d->bibinfo_, it);
1692 d->bibinfo_cache_valid_ = true;
1697 bool Buffer::isDepClean(string const & name) const
1699 DepClean::const_iterator const it = d->dep_clean.find(name);
1700 if (it == d->dep_clean.end())
1706 void Buffer::markDepClean(string const & name)
1708 d->dep_clean[name] = true;
1712 bool Buffer::isExportableFormat(string const & format) const
1714 typedef vector<Format const *> Formats;
1716 formats = exportableFormats(true);
1717 Formats::const_iterator fit = formats.begin();
1718 Formats::const_iterator end = formats.end();
1719 for (; fit != end ; ++fit) {
1720 if ((*fit)->name() == format)
1727 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1730 // FIXME? if there is an Buffer LFUN that can be dispatched even
1731 // if internal, put a switch '(cmd.action)' here.
1737 switch (cmd.action) {
1739 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1740 flag.setOnOff(isReadonly());
1743 // FIXME: There is need for a command-line import.
1744 //case LFUN_BUFFER_IMPORT:
1746 case LFUN_BUFFER_AUTO_SAVE:
1749 case LFUN_BUFFER_EXPORT_CUSTOM:
1750 // FIXME: Nothing to check here?
1753 case LFUN_BUFFER_EXPORT: {
1754 docstring const arg = cmd.argument();
1755 enable = arg == "custom" || isExportable(to_utf8(arg));
1757 flag.message(bformat(
1758 _("Don't know how to export to format: %1$s"), arg));
1762 case LFUN_BUFFER_CHKTEX:
1763 enable = isLatex() && !lyxrc.chktex_command.empty();
1766 case LFUN_BUILD_PROGRAM:
1767 enable = isExportable("program");
1770 case LFUN_BRANCH_ACTIVATE:
1771 case LFUN_BRANCH_DEACTIVATE: {
1772 BranchList const & branchList = params().branchlist();
1773 docstring const branchName = cmd.argument();
1774 enable = !branchName.empty() && branchList.find(branchName);
1778 case LFUN_BRANCH_ADD:
1779 case LFUN_BRANCHES_RENAME:
1780 case LFUN_BUFFER_PRINT:
1781 // if no Buffer is present, then of course we won't be called!
1784 case LFUN_BUFFER_LANGUAGE:
1785 enable = !isReadonly();
1791 flag.setEnabled(enable);
1796 void Buffer::dispatch(string const & command, DispatchResult & result)
1798 return dispatch(lyxaction.lookupFunc(command), result);
1802 // NOTE We can end up here even if we have no GUI, because we are called
1803 // by LyX::exec to handled command-line requests. So we may need to check
1804 // whether we have a GUI or not. The boolean use_gui holds this information.
1805 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1808 // FIXME? if there is an Buffer LFUN that can be dispatched even
1809 // if internal, put a switch '(cmd.action)' here.
1810 dr.dispatched(false);
1813 string const argument = to_utf8(func.argument());
1814 // We'll set this back to false if need be.
1815 bool dispatched = true;
1816 undo().beginUndoGroup();
1818 switch (func.action) {
1819 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1820 if (lyxvc().inUse())
1821 lyxvc().toggleReadOnly();
1823 setReadonly(!isReadonly());
1826 case LFUN_BUFFER_EXPORT: {
1827 bool success = doExport(argument, false);
1828 dr.setError(success);
1830 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1835 case LFUN_BUILD_PROGRAM:
1836 doExport("program", true);
1839 case LFUN_BUFFER_CHKTEX:
1843 case LFUN_BUFFER_EXPORT_CUSTOM: {
1845 string command = split(argument, format_name, ' ');
1846 Format const * format = formats.getFormat(format_name);
1848 lyxerr << "Format \"" << format_name
1849 << "\" not recognized!"
1854 // The name of the file created by the conversion process
1857 // Output to filename
1858 if (format->name() == "lyx") {
1859 string const latexname = latexName(false);
1860 filename = changeExtension(latexname,
1861 format->extension());
1862 filename = addName(temppath(), filename);
1864 if (!writeFile(FileName(filename)))
1868 doExport(format_name, true, filename);
1871 // Substitute $$FName for filename
1872 if (!contains(command, "$$FName"))
1873 command = "( " + command + " ) < $$FName";
1874 command = subst(command, "$$FName", filename);
1876 // Execute the command in the background
1878 call.startscript(Systemcall::DontWait, command);
1882 // FIXME: There is need for a command-line import.
1884 case LFUN_BUFFER_IMPORT:
1889 case LFUN_BUFFER_AUTO_SAVE:
1893 case LFUN_BRANCH_ADD: {
1894 docstring const branch_name = func.argument();
1895 if (branch_name.empty()) {
1899 BranchList & branch_list = params().branchlist();
1900 Branch * branch = branch_list.find(branch_name);
1902 LYXERR0("Branch " << branch_name << " already exists.");
1904 docstring const msg =
1905 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1908 branch_list.add(branch_name);
1909 branch = branch_list.find(branch_name);
1910 string const x11hexname = X11hexname(branch->color());
1911 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1912 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1914 dr.update(Update::Force);
1919 case LFUN_BRANCH_ACTIVATE:
1920 case LFUN_BRANCH_DEACTIVATE: {
1921 BranchList & branchList = params().branchlist();
1922 docstring const branchName = func.argument();
1923 // the case without a branch name is handled elsewhere
1924 if (branchName.empty()) {
1928 Branch * branch = branchList.find(branchName);
1930 LYXERR0("Branch " << branchName << " does not exist.");
1932 docstring const msg =
1933 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1936 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1938 dr.update(Update::Force);
1943 case LFUN_BRANCHES_RENAME: {
1944 if (func.argument().empty())
1947 docstring const oldname = from_utf8(func.getArg(0));
1948 docstring const newname = from_utf8(func.getArg(1));
1949 InsetIterator it = inset_iterator_begin(inset());
1950 InsetIterator const end = inset_iterator_end(inset());
1951 bool success = false;
1952 for (; it != end; ++it) {
1953 if (it->lyxCode() == BRANCH_CODE) {
1954 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1955 if (ins.branch() == oldname) {
1956 undo().recordUndo(it);
1957 ins.rename(newname);
1962 if (it->lyxCode() == INCLUDE_CODE) {
1963 // get buffer of external file
1964 InsetInclude const & ins =
1965 static_cast<InsetInclude const &>(*it);
1966 Buffer * child = ins.getChildBuffer();
1969 child->dispatch(func, dr);
1974 dr.update(Update::Force);
1978 case LFUN_BUFFER_PRINT: {
1979 // we'll assume there's a problem until we succeed
1981 string target = func.getArg(0);
1982 string target_name = func.getArg(1);
1983 string command = func.getArg(2);
1986 || target_name.empty()
1987 || command.empty()) {
1988 LYXERR0("Unable to parse " << func.argument());
1989 docstring const msg =
1990 bformat(_("Unable to parse \"%1$s\""), func.argument());
1994 if (target != "printer" && target != "file") {
1995 LYXERR0("Unrecognized target \"" << target << '"');
1996 docstring const msg =
1997 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2002 if (!doExport("dvi", true)) {
2003 showPrintError(absFileName());
2004 dr.setMessage(_("Error exporting to DVI."));
2008 // Push directory path.
2009 string const path = temppath();
2010 // Prevent the compiler from optimizing away p
2014 // there are three cases here:
2015 // 1. we print to a file
2016 // 2. we print directly to a printer
2017 // 3. we print using a spool command (print to file first)
2020 string const dviname = changeExtension(latexName(true), "dvi");
2022 if (target == "printer") {
2023 if (!lyxrc.print_spool_command.empty()) {
2024 // case 3: print using a spool
2025 string const psname = changeExtension(dviname,".ps");
2026 command += ' ' + lyxrc.print_to_file
2029 + quoteName(dviname);
2031 string command2 = lyxrc.print_spool_command + ' ';
2032 if (target_name != "default") {
2033 command2 += lyxrc.print_spool_printerprefix
2037 command2 += quoteName(psname);
2039 // If successful, then spool command
2040 res = one.startscript(Systemcall::Wait, command);
2043 // If there's no GUI, we have to wait on this command. Otherwise,
2044 // LyX deletes the temporary directory, and with it the spooled
2045 // file, before it can be printed!!
2046 Systemcall::Starttype stype = use_gui ?
2047 Systemcall::DontWait : Systemcall::Wait;
2048 res = one.startscript(stype, command2);
2051 // case 2: print directly to a printer
2052 if (target_name != "default")
2053 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2055 Systemcall::Starttype stype = use_gui ?
2056 Systemcall::DontWait : Systemcall::Wait;
2057 res = one.startscript(stype, command + quoteName(dviname));
2061 // case 1: print to a file
2062 FileName const filename(makeAbsPath(target_name, filePath()));
2063 FileName const dvifile(makeAbsPath(dviname, path));
2064 if (filename.exists()) {
2065 docstring text = bformat(
2066 _("The file %1$s already exists.\n\n"
2067 "Do you want to overwrite that file?"),
2068 makeDisplayPath(filename.absFilename()));
2069 if (Alert::prompt(_("Overwrite file?"),
2070 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2073 command += ' ' + lyxrc.print_to_file
2074 + quoteName(filename.toFilesystemEncoding())
2076 + quoteName(dvifile.toFilesystemEncoding());
2078 Systemcall::Starttype stype = use_gui ?
2079 Systemcall::DontWait : Systemcall::Wait;
2080 res = one.startscript(stype, command);
2086 dr.setMessage(_("Error running external commands."));
2087 showPrintError(absFileName());
2092 case LFUN_BUFFER_LANGUAGE: {
2093 Language const * oldL = params().language;
2094 Language const * newL = languages.getLanguage(argument);
2095 if (!newL || oldL == newL)
2097 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2098 changeLanguage(oldL, newL);
2106 dr.dispatched(dispatched);
2107 undo().endUndoGroup();
2111 void Buffer::changeLanguage(Language const * from, Language const * to)
2113 LASSERT(from, /**/);
2116 for_each(par_iterator_begin(),
2118 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2122 bool Buffer::isMultiLingual() const
2124 ParConstIterator end = par_iterator_end();
2125 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2126 if (it->isMultiLingual(params()))
2133 DocIterator Buffer::getParFromID(int const id) const
2135 Buffer * buf = const_cast<Buffer *>(this);
2137 // John says this is called with id == -1 from undo
2138 lyxerr << "getParFromID(), id: " << id << endl;
2139 return doc_iterator_end(buf);
2142 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2143 if (it.paragraph().id() == id)
2146 return doc_iterator_end(buf);
2150 bool Buffer::hasParWithID(int const id) const
2152 return !getParFromID(id).atEnd();
2156 ParIterator Buffer::par_iterator_begin()
2158 return ParIterator(doc_iterator_begin(this));
2162 ParIterator Buffer::par_iterator_end()
2164 return ParIterator(doc_iterator_end(this));
2168 ParConstIterator Buffer::par_iterator_begin() const
2170 return ParConstIterator(doc_iterator_begin(this));
2174 ParConstIterator Buffer::par_iterator_end() const
2176 return ParConstIterator(doc_iterator_end(this));
2180 Language const * Buffer::language() const
2182 return params().language;
2186 docstring const Buffer::B_(string const & l10n) const
2188 return params().B_(l10n);
2192 bool Buffer::isClean() const
2194 return d->lyx_clean;
2198 bool Buffer::isBakClean() const
2200 return d->bak_clean;
2204 bool Buffer::isExternallyModified(CheckMethod method) const
2206 LASSERT(d->filename.exists(), /**/);
2207 // if method == timestamp, check timestamp before checksum
2208 return (method == checksum_method
2209 || d->timestamp_ != d->filename.lastModified())
2210 && d->checksum_ != d->filename.checksum();
2214 void Buffer::saveCheckSum(FileName const & file) const
2216 if (file.exists()) {
2217 d->timestamp_ = file.lastModified();
2218 d->checksum_ = file.checksum();
2220 // in the case of save to a new file.
2227 void Buffer::markClean() const
2229 if (!d->lyx_clean) {
2230 d->lyx_clean = true;
2233 // if the .lyx file has been saved, we don't need an
2235 d->bak_clean = true;
2239 void Buffer::markBakClean() const
2241 d->bak_clean = true;
2245 void Buffer::setUnnamed(bool flag)
2251 bool Buffer::isUnnamed() const
2258 /// Don't check unnamed, here: isInternal() is used in
2259 /// newBuffer(), where the unnamed flag has not been set by anyone
2260 /// yet. Also, for an internal buffer, there should be no need for
2261 /// retrieving fileName() nor for checking if it is unnamed or not.
2262 bool Buffer::isInternal() const
2264 return fileName().extension() == "internal";
2268 void Buffer::markDirty()
2271 d->lyx_clean = false;
2274 d->bak_clean = false;
2276 DepClean::iterator it = d->dep_clean.begin();
2277 DepClean::const_iterator const end = d->dep_clean.end();
2279 for (; it != end; ++it)
2284 FileName Buffer::fileName() const
2290 string Buffer::absFileName() const
2292 return d->filename.absFilename();
2296 string Buffer::filePath() const
2298 return d->filename.onlyPath().absFilename() + "/";
2302 bool Buffer::isReadonly() const
2304 return d->read_only;
2308 void Buffer::setParent(Buffer const * buffer)
2310 // Avoids recursive include.
2311 d->setParent(buffer == this ? 0 : buffer);
2316 Buffer const * Buffer::parent() const
2322 void Buffer::collectRelatives(BufferSet & bufs) const
2326 parent()->collectRelatives(bufs);
2328 // loop over children
2329 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2330 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2331 for (; it != end; ++it)
2332 bufs.insert(const_cast<Buffer *>(it->first));
2336 std::vector<Buffer const *> Buffer::allRelatives() const
2339 collectRelatives(bufs);
2340 BufferSet::iterator it = bufs.begin();
2341 std::vector<Buffer const *> ret;
2342 for (; it != bufs.end(); ++it)
2348 Buffer const * Buffer::masterBuffer() const
2350 Buffer const * const pbuf = d->parent();
2354 return pbuf->masterBuffer();
2358 bool Buffer::isChild(Buffer * child) const
2360 return d->children_positions.find(child) != d->children_positions.end();
2364 DocIterator Buffer::firstChildPosition(Buffer const * child)
2366 Impl::BufferPositionMap::iterator it;
2367 it = d->children_positions.find(child);
2368 if (it == d->children_positions.end())
2369 return DocIterator(this);
2374 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2376 // loop over children
2377 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2378 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2379 for (; it != end; ++it) {
2380 Buffer * child = const_cast<Buffer *>(it->first);
2381 clist.push_back(child);
2382 if (grand_children) {
2383 // there might be grandchildren
2384 std::vector<Buffer *> glist = child->getChildren();
2385 for (vector<Buffer *>::const_iterator git = glist.begin();
2386 git != glist.end(); ++git)
2387 clist.push_back(*git);
2393 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2395 std::vector<Buffer *> v;
2396 getChildren(v, grand_children);
2401 template<typename M>
2402 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2407 typename M::iterator it = m.lower_bound(x);
2408 if (it == m.begin())
2416 MacroData const * Buffer::getBufferMacro(docstring const & name,
2417 DocIterator const & pos) const
2419 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2421 // if paragraphs have no macro context set, pos will be empty
2425 // we haven't found anything yet
2426 DocIterator bestPos = par_iterator_begin();
2427 MacroData const * bestData = 0;
2429 // find macro definitions for name
2430 Impl::NamePositionScopeMacroMap::iterator nameIt
2431 = d->macros.find(name);
2432 if (nameIt != d->macros.end()) {
2433 // find last definition in front of pos or at pos itself
2434 Impl::PositionScopeMacroMap::const_iterator it
2435 = greatest_below(nameIt->second, pos);
2436 if (it != nameIt->second.end()) {
2438 // scope ends behind pos?
2439 if (pos < it->second.first) {
2440 // Looks good, remember this. If there
2441 // is no external macro behind this,
2442 // we found the right one already.
2443 bestPos = it->first;
2444 bestData = &it->second.second;
2448 // try previous macro if there is one
2449 if (it == nameIt->second.begin())
2456 // find macros in included files
2457 Impl::PositionScopeBufferMap::const_iterator it
2458 = greatest_below(d->position_to_children, pos);
2459 if (it == d->position_to_children.end())
2460 // no children before
2464 // do we know something better (i.e. later) already?
2465 if (it->first < bestPos )
2468 // scope ends behind pos?
2469 if (pos < it->second.first) {
2470 // look for macro in external file
2471 d->macro_lock = true;
2472 MacroData const * data
2473 = it->second.second->getMacro(name, false);
2474 d->macro_lock = false;
2476 bestPos = it->first;
2482 // try previous file if there is one
2483 if (it == d->position_to_children.begin())
2488 // return the best macro we have found
2493 MacroData const * Buffer::getMacro(docstring const & name,
2494 DocIterator const & pos, bool global) const
2499 // query buffer macros
2500 MacroData const * data = getBufferMacro(name, pos);
2504 // If there is a master buffer, query that
2505 Buffer const * const pbuf = d->parent();
2507 d->macro_lock = true;
2508 MacroData const * macro = pbuf->getMacro(
2509 name, *this, false);
2510 d->macro_lock = false;
2516 data = MacroTable::globalMacros().get(name);
2525 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2527 // set scope end behind the last paragraph
2528 DocIterator scope = par_iterator_begin();
2529 scope.pit() = scope.lastpit() + 1;
2531 return getMacro(name, scope, global);
2535 MacroData const * Buffer::getMacro(docstring const & name,
2536 Buffer const & child, bool global) const
2538 // look where the child buffer is included first
2539 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2540 if (it == d->children_positions.end())
2543 // check for macros at the inclusion position
2544 return getMacro(name, it->second, global);
2548 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2550 pit_type lastpit = it.lastpit();
2552 // look for macros in each paragraph
2553 while (it.pit() <= lastpit) {
2554 Paragraph & par = it.paragraph();
2556 // iterate over the insets of the current paragraph
2557 InsetList const & insets = par.insetList();
2558 InsetList::const_iterator iit = insets.begin();
2559 InsetList::const_iterator end = insets.end();
2560 for (; iit != end; ++iit) {
2561 it.pos() = iit->pos;
2563 // is it a nested text inset?
2564 if (iit->inset->asInsetText()) {
2565 // Inset needs its own scope?
2566 InsetText const * itext = iit->inset->asInsetText();
2567 bool newScope = itext->isMacroScope();
2569 // scope which ends just behind the inset
2570 DocIterator insetScope = it;
2573 // collect macros in inset
2574 it.push_back(CursorSlice(*iit->inset));
2575 updateMacros(it, newScope ? insetScope : scope);
2580 // is it an external file?
2581 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2582 // get buffer of external file
2583 InsetInclude const & inset =
2584 static_cast<InsetInclude const &>(*iit->inset);
2585 d->macro_lock = true;
2586 Buffer * child = inset.getChildBuffer();
2587 d->macro_lock = false;
2591 // register its position, but only when it is
2592 // included first in the buffer
2593 if (d->children_positions.find(child) ==
2594 d->children_positions.end())
2595 d->children_positions[child] = it;
2597 // register child with its scope
2598 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2602 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2606 MathMacroTemplate & macroTemplate =
2607 static_cast<MathMacroTemplate &>(*iit->inset);
2608 MacroContext mc(this, it);
2609 macroTemplate.updateToContext(mc);
2612 bool valid = macroTemplate.validMacro();
2613 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2614 // then the BufferView's cursor will be invalid in
2615 // some cases which leads to crashes.
2620 // FIXME (Abdel), I don't understandt why we pass 'it' here
2621 // instead of 'macroTemplate' defined above... is this correct?
2622 d->macros[macroTemplate.name()][it] =
2623 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2633 void Buffer::updateMacros() const
2638 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2640 // start with empty table
2642 d->children_positions.clear();
2643 d->position_to_children.clear();
2645 // Iterate over buffer, starting with first paragraph
2646 // The scope must be bigger than any lookup DocIterator
2647 // later. For the global lookup, lastpit+1 is used, hence
2648 // we use lastpit+2 here.
2649 DocIterator it = par_iterator_begin();
2650 DocIterator outerScope = it;
2651 outerScope.pit() = outerScope.lastpit() + 2;
2652 updateMacros(it, outerScope);
2656 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2658 InsetIterator it = inset_iterator_begin(inset());
2659 InsetIterator const end = inset_iterator_end(inset());
2660 for (; it != end; ++it) {
2661 if (it->lyxCode() == BRANCH_CODE) {
2662 InsetBranch & br = static_cast<InsetBranch &>(*it);
2663 docstring const name = br.branch();
2664 if (!from_master && !params().branchlist().find(name))
2665 result.push_back(name);
2666 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2667 result.push_back(name);
2670 if (it->lyxCode() == INCLUDE_CODE) {
2671 // get buffer of external file
2672 InsetInclude const & ins =
2673 static_cast<InsetInclude const &>(*it);
2674 Buffer * child = ins.getChildBuffer();
2677 child->getUsedBranches(result, true);
2680 // remove duplicates
2685 void Buffer::updateMacroInstances() const
2687 LYXERR(Debug::MACROS, "updateMacroInstances for "
2688 << d->filename.onlyFileName());
2689 DocIterator it = doc_iterator_begin(this);
2691 DocIterator const end = doc_iterator_end(this);
2692 for (; it != end; it.forwardInset()) {
2693 // look for MathData cells in InsetMathNest insets
2694 InsetMath * minset = it.nextInset()->asInsetMath();
2698 // update macro in all cells of the InsetMathNest
2699 DocIterator::idx_type n = minset->nargs();
2700 MacroContext mc = MacroContext(this, it);
2701 for (DocIterator::idx_type i = 0; i < n; ++i) {
2702 MathData & data = minset->cell(i);
2703 data.updateMacros(0, mc);
2709 void Buffer::listMacroNames(MacroNameSet & macros) const
2714 d->macro_lock = true;
2716 // loop over macro names
2717 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2718 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2719 for (; nameIt != nameEnd; ++nameIt)
2720 macros.insert(nameIt->first);
2722 // loop over children
2723 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2724 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2725 for (; it != end; ++it)
2726 it->first->listMacroNames(macros);
2729 Buffer const * const pbuf = d->parent();
2731 pbuf->listMacroNames(macros);
2733 d->macro_lock = false;
2737 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2739 Buffer const * const pbuf = d->parent();
2744 pbuf->listMacroNames(names);
2747 MacroNameSet::iterator it = names.begin();
2748 MacroNameSet::iterator end = names.end();
2749 for (; it != end; ++it) {
2751 MacroData const * data =
2752 pbuf->getMacro(*it, *this, false);
2754 macros.insert(data);
2756 // we cannot access the original MathMacroTemplate anymore
2757 // here to calls validate method. So we do its work here manually.
2758 // FIXME: somehow make the template accessible here.
2759 if (data->optionals() > 0)
2760 features.require("xargs");
2766 Buffer::References & Buffer::references(docstring const & label)
2769 return const_cast<Buffer *>(masterBuffer())->references(label);
2771 RefCache::iterator it = d->ref_cache_.find(label);
2772 if (it != d->ref_cache_.end())
2773 return it->second.second;
2775 static InsetLabel const * dummy_il = 0;
2776 static References const dummy_refs;
2777 it = d->ref_cache_.insert(
2778 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2779 return it->second.second;
2783 Buffer::References const & Buffer::references(docstring const & label) const
2785 return const_cast<Buffer *>(this)->references(label);
2789 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2791 masterBuffer()->d->ref_cache_[label].first = il;
2795 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2797 return masterBuffer()->d->ref_cache_[label].first;
2801 void Buffer::clearReferenceCache() const
2804 d->ref_cache_.clear();
2808 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2811 //FIXME: This does not work for child documents yet.
2812 LASSERT(code == CITE_CODE, /**/);
2813 // Check if the label 'from' appears more than once
2814 vector<docstring> labels;
2816 BiblioInfo const & keys = masterBibInfo();
2817 BiblioInfo::const_iterator bit = keys.begin();
2818 BiblioInfo::const_iterator bend = keys.end();
2820 for (; bit != bend; ++bit)
2822 labels.push_back(bit->first);
2825 if (count(labels.begin(), labels.end(), from) > 1)
2828 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2829 if (it->lyxCode() == code) {
2830 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2831 docstring const oldValue = inset.getParam(paramName);
2832 if (oldValue == from)
2833 inset.setParam(paramName, to);
2839 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2840 pit_type par_end, bool full_source) const
2842 OutputParams runparams(¶ms().encoding());
2843 runparams.nice = true;
2844 runparams.flavor = params().useXetex ?
2845 OutputParams::XETEX : OutputParams::LATEX;
2846 runparams.linelen = lyxrc.plaintext_linelen;
2847 // No side effect of file copying and image conversion
2848 runparams.dryrun = true;
2851 os << "% " << _("Preview source code") << "\n\n";
2853 d->texrow.newline();
2854 d->texrow.newline();
2856 writeDocBookSource(os, absFileName(), runparams, false);
2858 // latex or literate
2859 writeLaTeXSource(os, string(), runparams, true, true);
2861 runparams.par_begin = par_begin;
2862 runparams.par_end = par_end;
2863 if (par_begin + 1 == par_end) {
2865 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2869 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2870 convert<docstring>(par_begin),
2871 convert<docstring>(par_end - 1))
2878 // output paragraphs
2880 docbookParagraphs(text(), *this, os, runparams);
2882 // latex or literate
2883 latexParagraphs(*this, text(), os, texrow, runparams);
2888 ErrorList & Buffer::errorList(string const & type) const
2890 static ErrorList emptyErrorList;
2891 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2892 if (I == d->errorLists.end())
2893 return emptyErrorList;
2899 void Buffer::updateTocItem(std::string const & type,
2900 DocIterator const & dit) const
2903 gui_->updateTocItem(type, dit);
2907 void Buffer::structureChanged() const
2910 gui_->structureChanged();
2914 void Buffer::errors(string const & err, bool from_master) const
2917 gui_->errors(err, from_master);
2921 void Buffer::message(docstring const & msg) const
2928 void Buffer::setBusy(bool on) const
2935 void Buffer::setReadOnly(bool on) const
2938 d->wa_->setReadOnly(on);
2942 void Buffer::updateTitles() const
2945 d->wa_->updateTitles();
2949 void Buffer::resetAutosaveTimers() const
2952 gui_->resetAutosaveTimers();
2956 bool Buffer::hasGuiDelegate() const
2962 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2971 class AutoSaveBuffer : public ForkedProcess {
2974 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2975 : buffer_(buffer), fname_(fname) {}
2977 virtual boost::shared_ptr<ForkedProcess> clone() const
2979 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2984 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2985 from_utf8(fname_.absFilename())));
2986 return run(DontWait);
2990 virtual int generateChild();
2992 Buffer const & buffer_;
2997 int AutoSaveBuffer::generateChild()
2999 #if defined(__APPLE__)
3000 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3001 * We should use something else like threads.
3003 * Since I do not know how to determine at run time what is the OS X
3004 * version, I just disable forking altogether for now (JMarc)
3006 pid_t const pid = -1;
3008 // tmp_ret will be located (usually) in /tmp
3009 // will that be a problem?
3010 // Note that this calls ForkedCalls::fork(), so it's
3011 // ok cross-platform.
3012 pid_t const pid = fork();
3013 // If you want to debug the autosave
3014 // you should set pid to -1, and comment out the fork.
3015 if (pid != 0 && pid != -1)
3019 // pid = -1 signifies that lyx was unable
3020 // to fork. But we will do the save
3022 bool failed = false;
3023 FileName const tmp_ret = FileName::tempName("lyxauto");
3024 if (!tmp_ret.empty()) {
3025 buffer_.writeFile(tmp_ret);
3026 // assume successful write of tmp_ret
3027 if (!tmp_ret.moveTo(fname_))
3033 // failed to write/rename tmp_ret so try writing direct
3034 if (!buffer_.writeFile(fname_)) {
3035 // It is dangerous to do this in the child,
3036 // but safe in the parent, so...
3037 if (pid == -1) // emit message signal.
3038 buffer_.message(_("Autosave failed!"));
3042 if (pid == 0) // we are the child so...
3051 FileName Buffer::getAutosaveFilename() const
3053 // if the document is unnamed try to save in the backup dir, else
3054 // in the default document path, and as a last try in the filePath,
3055 // which will most often be the temporary directory
3058 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3059 : lyxrc.backupdir_path;
3060 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3063 string const fname = "#" + d->filename.onlyFileName() + "#";
3064 return makeAbsPath(fname, fpath);
3068 void Buffer::removeAutosaveFile() const
3070 FileName const f = getAutosaveFilename();
3076 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3078 FileName const newauto = getAutosaveFilename();
3079 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3080 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3084 // Perfect target for a thread...
3085 void Buffer::autoSave() const
3087 if (isBakClean() || isReadonly()) {
3088 // We don't save now, but we'll try again later
3089 resetAutosaveTimers();
3093 // emit message signal.
3094 message(_("Autosaving current document..."));
3095 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3099 resetAutosaveTimers();
3103 string Buffer::bufferFormat() const
3105 string format = params().documentClass().outputFormat();
3106 if (format == "latex") {
3107 if (params().useXetex)
3109 if (params().encoding().package() == Encoding::japanese)
3116 string Buffer::getDefaultOutputFormat() const
3118 if (!params().defaultOutputFormat.empty()
3119 && params().defaultOutputFormat != "default")
3120 return params().defaultOutputFormat;
3121 typedef vector<Format const *> Formats;
3122 Formats formats = exportableFormats(true);
3125 || params().useXetex
3126 || params().encoding().package() == Encoding::japanese) {
3127 if (formats.empty())
3129 // return the first we find
3130 return formats.front()->name();
3132 return lyxrc.default_view_format;
3137 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3138 string & result_file) const
3140 string backend_format;
3141 OutputParams runparams(¶ms().encoding());
3142 runparams.flavor = OutputParams::LATEX;
3143 runparams.linelen = lyxrc.plaintext_linelen;
3144 vector<string> backs = backends();
3145 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3146 // Get shortest path to format
3147 Graph::EdgePath path;
3148 for (vector<string>::const_iterator it = backs.begin();
3149 it != backs.end(); ++it) {
3150 Graph::EdgePath p = theConverters().getPath(*it, format);
3151 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3152 backend_format = *it;
3157 if (!put_in_tempdir) {
3158 // Only show this alert if this is an export to a non-temporary
3159 // file (not for previewing).
3160 Alert::error(_("Couldn't export file"), bformat(
3161 _("No information for exporting the format %1$s."),
3162 formats.prettyName(format)));
3166 runparams.flavor = theConverters().getFlavor(path);
3169 backend_format = format;
3170 // FIXME: Don't hardcode format names here, but use a flag
3171 if (backend_format == "pdflatex")
3172 runparams.flavor = OutputParams::PDFLATEX;
3175 string filename = latexName(false);
3176 filename = addName(temppath(), filename);
3177 filename = changeExtension(filename,
3178 formats.extension(backend_format));
3181 updateMacroInstances();
3183 // Plain text backend
3184 if (backend_format == "text") {
3185 runparams.flavor = OutputParams::TEXT;
3186 writePlaintextFile(*this, FileName(filename), runparams);
3189 else if (backend_format == "xhtml") {
3190 runparams.flavor = OutputParams::HTML;
3191 makeLyXHTMLFile(FileName(filename), runparams);
3192 } else if (backend_format == "lyx")
3193 writeFile(FileName(filename));
3195 else if (isDocBook()) {
3196 runparams.nice = !put_in_tempdir;
3197 makeDocBookFile(FileName(filename), runparams);
3200 else if (backend_format == format) {
3201 runparams.nice = true;
3202 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3204 } else if (!lyxrc.tex_allows_spaces
3205 && contains(filePath(), ' ')) {
3206 Alert::error(_("File name error"),
3207 _("The directory path to the document cannot contain spaces."));
3210 runparams.nice = false;
3211 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3215 string const error_type = (format == "program")
3216 ? "Build" : bufferFormat();
3217 ErrorList & error_list = d->errorLists[error_type];
3218 string const ext = formats.extension(format);
3219 FileName const tmp_result_file(changeExtension(filename, ext));
3220 bool const success = theConverters().convert(this, FileName(filename),
3221 tmp_result_file, FileName(absFileName()), backend_format, format,
3223 // Emit the signal to show the error list.
3224 if (format != backend_format) {
3226 // also to the children, in case of master-buffer-view
3227 std::vector<Buffer *> clist = getChildren();
3228 for (vector<Buffer *>::const_iterator cit = clist.begin();
3229 cit != clist.end(); ++cit)
3230 (*cit)->errors(error_type, true);
3235 if (d->cloned_buffer_) {
3236 // Enable reverse dvi or pdf to work by copying back the texrow
3237 // object to the cloned buffer.
3238 // FIXME: There is a possibility of concurrent access to texrow
3239 // here from the main GUI thread that should be securized.
3240 d->cloned_buffer_->d->texrow = d->texrow;
3243 if (put_in_tempdir) {
3244 result_file = tmp_result_file.absFilename();
3248 result_file = changeExtension(exportFileName().absFilename(), ext);
3249 // We need to copy referenced files (e. g. included graphics
3250 // if format == "dvi") to the result dir.
3251 vector<ExportedFile> const files =
3252 runparams.exportdata->externalFiles(format);
3253 string const dest = onlyPath(result_file);
3254 CopyStatus status = SUCCESS;
3255 for (vector<ExportedFile>::const_iterator it = files.begin();
3256 it != files.end() && status != CANCEL; ++it) {
3257 string const fmt = formats.getFormatFromFile(it->sourceName);
3258 status = copyFile(fmt, it->sourceName,
3259 makeAbsPath(it->exportName, dest),
3260 it->exportName, status == FORCE);
3262 if (status == CANCEL) {
3263 message(_("Document export cancelled."));
3264 } else if (tmp_result_file.exists()) {
3265 // Finally copy the main file
3266 status = copyFile(format, tmp_result_file,
3267 FileName(result_file), result_file,
3269 message(bformat(_("Document exported as %1$s "
3271 formats.prettyName(format),
3272 makeDisplayPath(result_file)));
3274 // This must be a dummy converter like fax (bug 1888)
3275 message(bformat(_("Document exported as %1$s"),
3276 formats.prettyName(format)));
3283 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3286 return doExport(format, put_in_tempdir, result_file);
3290 bool Buffer::preview(string const & format) const
3293 if (!doExport(format, true, result_file))
3295 return formats.view(*this, FileName(result_file), format);
3299 bool Buffer::isExportable(string const & format) const
3301 vector<string> backs = backends();
3302 for (vector<string>::const_iterator it = backs.begin();
3303 it != backs.end(); ++it)
3304 if (theConverters().isReachable(*it, format))
3310 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3312 vector<string> const backs = backends();
3313 vector<Format const *> result =
3314 theConverters().getReachable(backs[0], only_viewable, true);
3315 for (vector<string>::const_iterator it = backs.begin() + 1;
3316 it != backs.end(); ++it) {
3317 vector<Format const *> r =
3318 theConverters().getReachable(*it, only_viewable, false);
3319 result.insert(result.end(), r.begin(), r.end());
3325 vector<string> Buffer::backends() const
3328 v.push_back(bufferFormat());
3329 // FIXME: Don't hardcode format names here, but use a flag
3330 if (v.back() == "latex")
3331 v.push_back("pdflatex");
3332 v.push_back("xhtml");
3333 v.push_back("text");
3339 bool Buffer::readFileHelper(FileName const & s)
3341 // File information about normal file
3343 docstring const file = makeDisplayPath(s.absFilename(), 50);
3344 docstring text = bformat(_("The specified document\n%1$s"
3345 "\ncould not be read."), file);
3346 Alert::error(_("Could not read document"), text);
3350 // Check if emergency save file exists and is newer.
3351 FileName const e(s.absFilename() + ".emergency");
3353 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3354 docstring const file = makeDisplayPath(s.absFilename(), 20);
3355 docstring const text =
3356 bformat(_("An emergency save of the document "
3358 "Recover emergency save?"), file);
3359 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3360 _("&Recover"), _("&Load Original"),
3364 // the file is not saved if we load the emergency file.
3369 if ((res = readFile(e)) == success)
3370 str = _("Document was successfully recovered.");
3372 str = _("Document was NOT successfully recovered.");
3373 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3374 from_utf8(e.absFilename()));
3376 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3377 _("&Remove"), _("&Keep it"))) {
3380 Alert::warning(_("Emergency file deleted"),
3381 _("Do not forget to save your file now!"), true);
3386 if (!Alert::prompt(_("Delete emergency file?"),
3387 _("Remove emergency file now?"), 1, 1,
3388 _("&Remove"), _("&Keep it")))
3396 // Now check if autosave file is newer.
3397 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3399 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3400 docstring const file = makeDisplayPath(s.absFilename(), 20);
3401 docstring const text =
3402 bformat(_("The backup of the document "
3403 "%1$s is newer.\n\nLoad the "
3404 "backup instead?"), file);
3405 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3406 _("&Load backup"), _("Load &original"),
3410 // the file is not saved if we load the autosave file.
3414 // Here we delete the autosave
3425 bool Buffer::loadLyXFile(FileName const & s)
3427 // If the file is not readable, we try to
3428 // retrieve the file from version control.
3429 if (!s.isReadableFile()
3430 && !LyXVC::file_not_found_hook(s))
3433 if (s.isReadableFile()
3434 && readFileHelper(s)) {
3435 lyxvc().file_found_hook(s);
3436 setReadonly(!s.isWritable());
3443 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3445 TeXErrors::Errors::const_iterator cit = terr.begin();
3446 TeXErrors::Errors::const_iterator end = terr.end();
3448 for (; cit != end; ++cit) {
3451 int errorRow = cit->error_in_line;
3452 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3458 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3459 } while (found && id_start == id_end && pos_start == pos_end);
3461 errorList.push_back(ErrorItem(cit->error_desc,
3462 cit->error_text, id_start, pos_start, pos_end));
3467 void Buffer::setBuffersForInsets() const
3469 inset().setBuffer(const_cast<Buffer &>(*this));
3473 void Buffer::updateLabels(UpdateScope scope, bool out) const
3475 // Use the master text class also for child documents
3476 Buffer const * const master = masterBuffer();
3477 DocumentClass const & textclass = master->params().documentClass();
3479 // keep the buffers to be children in this set. If the call from the
3480 // master comes back we can see which of them were actually seen (i.e.
3481 // via an InsetInclude). The remaining ones in the set need still be updated.
3482 static std::set<Buffer const *> bufToUpdate;
3483 if (scope == UpdateMaster) {
3484 // If this is a child document start with the master
3485 if (master != this) {
3486 bufToUpdate.insert(this);
3487 master->updateLabels(UpdateMaster, out);
3488 // Do this here in case the master has no gui associated with it. Then,
3489 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3493 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3494 if (bufToUpdate.find(this) == bufToUpdate.end())
3498 // start over the counters in the master
3499 textclass.counters().reset();
3502 // update will be done below for this buffer
3503 bufToUpdate.erase(this);
3505 // update all caches
3506 clearReferenceCache();
3509 Buffer & cbuf = const_cast<Buffer &>(*this);
3511 LASSERT(!text().paragraphs().empty(), /**/);
3514 ParIterator parit = cbuf.par_iterator_begin();
3515 updateLabels(parit, out);
3518 // TocBackend update will be done later.
3521 cbuf.tocBackend().update();
3522 if (scope == UpdateMaster)
3523 cbuf.structureChanged();
3527 static depth_type getDepth(DocIterator const & it)
3529 depth_type depth = 0;
3530 for (size_t i = 0 ; i < it.depth() ; ++i)
3531 if (!it[i].inset().inMathed())
3532 depth += it[i].paragraph().getDepth() + 1;
3533 // remove 1 since the outer inset does not count
3537 static depth_type getItemDepth(ParIterator const & it)
3539 Paragraph const & par = *it;
3540 LabelType const labeltype = par.layout().labeltype;
3542 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3545 // this will hold the lowest depth encountered up to now.
3546 depth_type min_depth = getDepth(it);
3547 ParIterator prev_it = it;
3550 --prev_it.top().pit();
3552 // start of nested inset: go to outer par
3554 if (prev_it.empty()) {
3555 // start of document: nothing to do
3560 // We search for the first paragraph with same label
3561 // that is not more deeply nested.
3562 Paragraph & prev_par = *prev_it;
3563 depth_type const prev_depth = getDepth(prev_it);
3564 if (labeltype == prev_par.layout().labeltype) {
3565 if (prev_depth < min_depth)
3566 return prev_par.itemdepth + 1;
3567 if (prev_depth == min_depth)
3568 return prev_par.itemdepth;
3570 min_depth = min(min_depth, prev_depth);
3571 // small optimization: if we are at depth 0, we won't
3572 // find anything else
3573 if (prev_depth == 0)
3579 static bool needEnumCounterReset(ParIterator const & it)
3581 Paragraph const & par = *it;
3582 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3583 depth_type const cur_depth = par.getDepth();
3584 ParIterator prev_it = it;
3585 while (prev_it.pit()) {
3586 --prev_it.top().pit();
3587 Paragraph const & prev_par = *prev_it;
3588 if (prev_par.getDepth() <= cur_depth)
3589 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3591 // start of nested inset: reset
3596 // set the label of a paragraph. This includes the counters.
3597 void Buffer::setLabel(ParIterator & it) const
3599 BufferParams const & bp = this->masterBuffer()->params();
3600 DocumentClass const & textclass = bp.documentClass();
3601 Paragraph & par = it.paragraph();
3602 Layout const & layout = par.layout();
3603 Counters & counters = textclass.counters();
3605 if (par.params().startOfAppendix()) {
3606 // FIXME: only the counter corresponding to toplevel
3607 // sectioning should be reset
3609 counters.appendix(true);
3611 par.params().appendix(counters.appendix());
3613 // Compute the item depth of the paragraph
3614 par.itemdepth = getItemDepth(it);
3616 if (layout.margintype == MARGIN_MANUAL
3617 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3618 if (par.params().labelWidthString().empty())
3619 par.params().labelWidthString(par.expandLabel(layout, bp));
3621 par.params().labelWidthString(docstring());
3624 switch(layout.labeltype) {
3626 if (layout.toclevel <= bp.secnumdepth
3627 && (layout.latextype != LATEX_ENVIRONMENT
3628 || it.text()->isFirstInSequence(it.pit()))) {
3629 counters.step(layout.counter);
3630 par.params().labelString(
3631 par.expandLabel(layout, bp));
3633 par.params().labelString(docstring());
3636 case LABEL_ITEMIZE: {
3637 // At some point of time we should do something more
3638 // clever here, like:
3639 // par.params().labelString(
3640 // bp.user_defined_bullet(par.itemdepth).getText());
3641 // for now, use a simple hardcoded label
3642 docstring itemlabel;
3643 switch (par.itemdepth) {
3645 itemlabel = char_type(0x2022);
3648 itemlabel = char_type(0x2013);
3651 itemlabel = char_type(0x2217);
3654 itemlabel = char_type(0x2219); // or 0x00b7
3657 par.params().labelString(itemlabel);
3661 case LABEL_ENUMERATE: {
3662 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3664 switch (par.itemdepth) {
3673 enumcounter += "iv";
3676 // not a valid enumdepth...
3680 // Maybe we have to reset the enumeration counter.
3681 if (needEnumCounterReset(it))
3682 counters.reset(enumcounter);
3683 counters.step(enumcounter);
3685 string const & lang = par.getParLanguage(bp)->code();
3686 par.params().labelString(counters.theCounter(enumcounter, lang));
3691 case LABEL_SENSITIVE: {
3692 string const & type = counters.current_float();
3693 docstring full_label;
3695 full_label = this->B_("Senseless!!! ");
3697 docstring name = this->B_(textclass.floats().getType(type).name());
3698 if (counters.hasCounter(from_utf8(type))) {
3699 string const & lang = par.getParLanguage(bp)->code();
3700 counters.step(from_utf8(type));
3701 full_label = bformat(from_ascii("%1$s %2$s:"),
3703 counters.theCounter(from_utf8(type), lang));
3705 full_label = bformat(from_ascii("%1$s #:"), name);
3707 par.params().labelString(full_label);
3711 case LABEL_NO_LABEL:
3712 par.params().labelString(docstring());
3716 case LABEL_TOP_ENVIRONMENT:
3717 case LABEL_CENTERED_TOP_ENVIRONMENT:
3720 par.params().labelString(par.expandLabel(layout, bp));
3726 void Buffer::updateLabels(ParIterator & parit, bool out) const
3728 LASSERT(parit.pit() == 0, /**/);
3730 // set the position of the text in the buffer to be able
3731 // to resolve macros in it. This has nothing to do with
3732 // labels, but by putting it here we avoid implementing
3733 // a whole bunch of traversal routines just for this call.
3734 parit.text()->setMacrocontextPosition(parit);
3736 depth_type maxdepth = 0;
3737 pit_type const lastpit = parit.lastpit();
3738 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3739 // reduce depth if necessary
3740 parit->params().depth(min(parit->params().depth(), maxdepth));
3741 maxdepth = parit->getMaxDepthAfter();
3743 // set the counter for this paragraph
3747 InsetList::const_iterator iit = parit->insetList().begin();
3748 InsetList::const_iterator end = parit->insetList().end();
3749 for (; iit != end; ++iit) {
3750 parit.pos() = iit->pos;
3751 iit->inset->updateLabels(parit, out);
3757 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3758 WordLangTuple & word_lang, docstring_list & suggestions) const
3762 suggestions.clear();
3763 word_lang = WordLangTuple();
3764 // OK, we start from here.
3765 DocIterator const end = doc_iterator_end(this);
3766 for (; from != end; from.forwardPos()) {
3767 // We are only interested in text so remove the math CursorSlice.
3768 while (from.inMathed()) {
3772 // If from is at the end of the document (which is possible
3773 // when leaving the mathed) LyX will crash later.
3777 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3782 // Do not increase progress when from == to, otherwise the word
3783 // count will be wrong.
3793 bool Buffer::reload()
3796 // e.g., read-only status could have changed due to version control
3797 d->filename.refresh();
3798 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3800 bool const success = loadLyXFile(d->filename);
3805 message(bformat(_("Document %1$s reloaded."), disp_fn));
3807 message(bformat(_("Could not reload document %1$s."), disp_fn));