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 bibfilesCache_;
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 bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
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), bibinfoCacheValid_(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 // FIXME for asynchronous export and preview: We must also clone all
384 // the child buffers!
385 return new Buffer(fileName().absFilename(), false, this);
389 bool Buffer::isClone() const
391 return d->cloned_buffer_;
395 void Buffer::changed(bool update_metrics) const
398 d->wa_->redrawAll(update_metrics);
402 frontend::WorkAreaManager & Buffer::workAreaManager() const
404 LASSERT(d->wa_, /**/);
409 Text & Buffer::text() const
411 return d->inset->text();
415 Inset & Buffer::inset() const
421 BufferParams & Buffer::params()
427 BufferParams const & Buffer::params() const
433 ParagraphList & Buffer::paragraphs()
435 return text().paragraphs();
439 ParagraphList const & Buffer::paragraphs() const
441 return text().paragraphs();
445 LyXVC & Buffer::lyxvc()
451 LyXVC const & Buffer::lyxvc() const
457 string const Buffer::temppath() const
459 return d->temppath.absFilename();
463 TexRow & Buffer::texrow()
469 TexRow const & Buffer::texrow() const
475 TocBackend & Buffer::tocBackend() const
477 return d->toc_backend;
481 Undo & Buffer::undo()
487 string Buffer::latexName(bool const no_path) const
489 FileName latex_name =
490 makeLatexName(exportFileName());
491 return no_path ? latex_name.onlyFileName()
492 : latex_name.absFilename();
496 FileName Buffer::exportFileName() const
498 docstring const branch_suffix =
499 params().branchlist().getFilenameSuffix();
500 if (branch_suffix.empty())
503 string const name = fileName().onlyFileNameWithoutExt()
504 + to_utf8(branch_suffix);
505 FileName res(fileName().onlyPath().absFilename() + "/" + name);
506 res.changeExtension(fileName().extension());
512 string Buffer::logName(LogType * type) const
514 string const filename = latexName(false);
516 if (filename.empty()) {
522 string const path = temppath();
524 FileName const fname(addName(temppath(),
525 onlyFilename(changeExtension(filename,
528 // FIXME: how do we know this is the name of the build log?
529 FileName const bname(
530 addName(path, onlyFilename(
531 changeExtension(filename,
532 formats.extension(bufferFormat()) + ".out"))));
534 // Also consider the master buffer log file
535 FileName masterfname = fname;
537 if (masterBuffer() != this) {
538 string const mlogfile = masterBuffer()->logName(&mtype);
539 masterfname = FileName(mlogfile);
542 // If no Latex log or Build log is newer, show Build log
543 if (bname.exists() &&
544 ((!fname.exists() && !masterfname.exists())
545 || (fname.lastModified() < bname.lastModified()
546 && masterfname.lastModified() < bname.lastModified()))) {
547 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
550 return bname.absFilename();
551 // If we have a newer master file log or only a master log, show this
552 } else if (fname != masterfname
553 && (!fname.exists() && (masterfname.exists()
554 || fname.lastModified() < masterfname.lastModified()))) {
555 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
558 return masterfname.absFilename();
560 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
563 return fname.absFilename();
567 void Buffer::setReadonly(bool const flag)
569 if (d->read_only != flag) {
576 void Buffer::setFileName(string const & newfile)
578 d->filename = makeAbsPath(newfile);
579 setReadonly(d->filename.isReadOnly());
584 int Buffer::readHeader(Lexer & lex)
586 int unknown_tokens = 0;
588 int begin_header_line = -1;
590 // Initialize parameters that may be/go lacking in header:
591 params().branchlist().clear();
592 params().preamble.erase();
593 params().options.erase();
594 params().master.erase();
595 params().float_placement.erase();
596 params().paperwidth.erase();
597 params().paperheight.erase();
598 params().leftmargin.erase();
599 params().rightmargin.erase();
600 params().topmargin.erase();
601 params().bottommargin.erase();
602 params().headheight.erase();
603 params().headsep.erase();
604 params().footskip.erase();
605 params().columnsep.erase();
606 params().fontsCJK.erase();
607 params().listings_params.clear();
608 params().clearLayoutModules();
609 params().clearRemovedModules();
610 params().clearIncludedChildren();
611 params().pdfoptions().clear();
612 params().indiceslist().clear();
613 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
615 for (int i = 0; i < 4; ++i) {
616 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
617 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
620 ErrorList & errorList = d->errorLists["Parse"];
629 if (token == "\\end_header")
633 if (token == "\\begin_header") {
634 begin_header_line = line;
638 LYXERR(Debug::PARSER, "Handling document header token: `"
641 string unknown = params().readToken(lex, token, d->filename.onlyPath());
642 if (!unknown.empty()) {
643 if (unknown[0] != '\\' && token == "\\textclass") {
644 Alert::warning(_("Unknown document class"),
645 bformat(_("Using the default document class, because the "
646 "class %1$s is unknown."), from_utf8(unknown)));
649 docstring const s = bformat(_("Unknown token: "
653 errorList.push_back(ErrorItem(_("Document header error"),
658 if (begin_header_line) {
659 docstring const s = _("\\begin_header is missing");
660 errorList.push_back(ErrorItem(_("Document header error"),
664 params().makeDocumentClass();
666 return unknown_tokens;
671 // changed to be public and have one parameter
672 // Returns true if "\end_document" is not read (Asger)
673 bool Buffer::readDocument(Lexer & lex)
675 ErrorList & errorList = d->errorLists["Parse"];
678 if (!lex.checkFor("\\begin_document")) {
679 docstring const s = _("\\begin_document is missing");
680 errorList.push_back(ErrorItem(_("Document header error"),
684 // we are reading in a brand new document
685 LASSERT(paragraphs().empty(), /**/);
689 if (params().outputChanges) {
690 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
691 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
692 LaTeXFeatures::isAvailable("xcolor");
694 if (!dvipost && !xcolorulem) {
695 Alert::warning(_("Changes not shown in LaTeX output"),
696 _("Changes will not be highlighted in LaTeX output, "
697 "because neither dvipost nor xcolor/ulem are installed.\n"
698 "Please install these packages or redefine "
699 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
700 } else if (!xcolorulem) {
701 Alert::warning(_("Changes not shown in LaTeX output"),
702 _("Changes will not be highlighted in LaTeX output "
703 "when using pdflatex, because xcolor and ulem are not installed.\n"
704 "Please install both packages or redefine "
705 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
709 if (!params().master.empty()) {
710 FileName const master_file = makeAbsPath(params().master,
711 onlyPath(absFileName()));
712 if (isLyXFilename(master_file.absFilename())) {
714 checkAndLoadLyXFile(master_file, true);
716 // necessary e.g. after a reload
717 // to re-register the child (bug 5873)
718 // FIXME: clean up updateMacros (here, only
719 // child registering is needed).
720 master->updateMacros();
721 // set master as master buffer, but only
722 // if we are a real child
723 if (master->isChild(this))
725 // if the master is not fully loaded
726 // it is probably just loading this
727 // child. No warning needed then.
728 else if (master->isFullyLoaded())
729 LYXERR0("The master '"
731 << "' assigned to this document ("
733 << ") does not include "
734 "this document. Ignoring the master assignment.");
739 // assure we have a default index
740 params().indiceslist().addDefault(B_("Index"));
743 bool const res = text().read(lex, errorList, d->inset);
747 updateMacroInstances();
752 bool Buffer::readString(string const & s)
754 params().compressed = false;
756 // remove dummy empty par
757 paragraphs().clear();
761 FileName const name = FileName::tempName("Buffer_readString");
762 switch (readFile(lex, name, true)) {
766 // We need to call lyx2lyx, so write the input to a file
767 ofstream os(name.toFilesystemEncoding().c_str());
770 return readFile(name);
780 bool Buffer::readFile(FileName const & filename)
782 FileName fname(filename);
784 params().compressed = fname.isZippedFile();
786 // remove dummy empty par
787 paragraphs().clear();
790 if (readFile(lex, fname) != success)
797 bool Buffer::isFullyLoaded() const
799 return d->file_fully_loaded;
803 void Buffer::setFullyLoaded(bool value)
805 d->file_fully_loaded = value;
809 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
812 LASSERT(!filename.empty(), /**/);
814 // the first (non-comment) token _must_ be...
815 if (!lex.checkFor("\\lyxformat")) {
816 Alert::error(_("Document format failure"),
817 bformat(_("%1$s is not a readable LyX document."),
818 from_utf8(filename.absFilename())));
824 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
825 // if present remove ".," from string.
826 size_t dot = tmp_format.find_first_of(".,");
827 //lyxerr << " dot found at " << dot << endl;
828 if (dot != string::npos)
829 tmp_format.erase(dot, 1);
830 int const file_format = convert<int>(tmp_format);
831 //lyxerr << "format: " << file_format << endl;
833 // save timestamp and checksum of the original disk file, making sure
834 // to not overwrite them with those of the file created in the tempdir
835 // when it has to be converted to the current format.
837 // Save the timestamp and checksum of disk file. If filename is an
838 // emergency file, save the timestamp and checksum of the original lyx file
839 // because isExternallyModified will check for this file. (BUG4193)
840 string diskfile = filename.absFilename();
841 if (suffixIs(diskfile, ".emergency"))
842 diskfile = diskfile.substr(0, diskfile.size() - 10);
843 saveCheckSum(FileName(diskfile));
846 if (file_format != LYX_FORMAT) {
849 // lyx2lyx would fail
852 FileName const tmpfile = FileName::tempName("Buffer_readFile");
853 if (tmpfile.empty()) {
854 Alert::error(_("Conversion failed"),
855 bformat(_("%1$s is from a different"
856 " version of LyX, but a temporary"
857 " file for converting it could"
859 from_utf8(filename.absFilename())));
862 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
863 if (lyx2lyx.empty()) {
864 Alert::error(_("Conversion script not found"),
865 bformat(_("%1$s is from a different"
866 " version of LyX, but the"
867 " conversion script lyx2lyx"
868 " could not be found."),
869 from_utf8(filename.absFilename())));
872 ostringstream command;
873 command << os::python()
874 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
875 << " -t " << convert<string>(LYX_FORMAT)
876 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
877 << ' ' << quoteName(filename.toFilesystemEncoding());
878 string const command_str = command.str();
880 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
882 cmd_ret const ret = runCommand(command_str);
883 if (ret.first != 0) {
884 Alert::error(_("Conversion script failed"),
885 bformat(_("%1$s is from a different version"
886 " of LyX, but the lyx2lyx script"
887 " failed to convert it."),
888 from_utf8(filename.absFilename())));
891 bool const ret = readFile(tmpfile);
892 // Do stuff with tmpfile name and buffer name here.
893 return ret ? success : failure;
898 if (readDocument(lex)) {
899 Alert::error(_("Document format failure"),
900 bformat(_("%1$s ended unexpectedly, which means"
901 " that it is probably corrupted."),
902 from_utf8(filename.absFilename())));
905 d->file_fully_loaded = true;
910 // Should probably be moved to somewhere else: BufferView? LyXView?
911 bool Buffer::save() const
913 // We don't need autosaves in the immediate future. (Asger)
914 resetAutosaveTimers();
916 string const encodedFilename = d->filename.toFilesystemEncoding();
919 bool madeBackup = false;
921 // make a backup if the file already exists
922 if (lyxrc.make_backup && fileName().exists()) {
923 backupName = FileName(absFileName() + '~');
924 if (!lyxrc.backupdir_path.empty()) {
925 string const mangledName =
926 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
927 backupName = FileName(addName(lyxrc.backupdir_path,
930 if (fileName().copyTo(backupName)) {
933 Alert::error(_("Backup failure"),
934 bformat(_("Cannot create backup file %1$s.\n"
935 "Please check whether the directory exists and is writeable."),
936 from_utf8(backupName.absFilename())));
937 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
941 // ask if the disk file has been externally modified (use checksum method)
942 if (fileName().exists() && isExternallyModified(checksum_method)) {
943 docstring const file = makeDisplayPath(absFileName(), 20);
944 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
945 "you want to overwrite this file?"), file);
946 int const ret = Alert::prompt(_("Overwrite modified file?"),
947 text, 1, 1, _("&Overwrite"), _("&Cancel"));
952 if (writeFile(d->filename)) {
956 // Saving failed, so backup is not backup
958 backupName.moveTo(d->filename);
964 bool Buffer::writeFile(FileName const & fname) const
966 if (d->read_only && fname == d->filename)
971 docstring const str = bformat(_("Saving document %1$s..."),
972 makeDisplayPath(fname.absFilename()));
975 if (params().compressed) {
976 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
977 retval = ofs && write(ofs);
979 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
980 retval = ofs && write(ofs);
984 message(str + _(" could not write file!"));
988 removeAutosaveFile();
990 saveCheckSum(d->filename);
991 message(str + _(" done."));
997 docstring Buffer::emergencyWrite()
999 // No need to save if the buffer has not changed.
1003 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1005 docstring user_message = bformat(
1006 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1008 // We try to save three places:
1009 // 1) Same place as document. Unless it is an unnamed doc.
1011 string s = absFileName();
1014 if (writeFile(FileName(s))) {
1016 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1017 return user_message;
1019 user_message += _(" Save failed! Trying again...\n");
1023 // 2) In HOME directory.
1024 string s = addName(package().home_dir().absFilename(), absFileName());
1026 lyxerr << ' ' << s << endl;
1027 if (writeFile(FileName(s))) {
1029 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1030 return user_message;
1033 user_message += _(" Save failed! Trying yet again...\n");
1035 // 3) In "/tmp" directory.
1036 // MakeAbsPath to prepend the current
1037 // drive letter on OS/2
1038 s = addName(package().temp_dir().absFilename(), absFileName());
1040 lyxerr << ' ' << s << endl;
1041 if (writeFile(FileName(s))) {
1043 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1044 return user_message;
1047 user_message += _(" Save failed! Bummer. Document is lost.");
1050 return user_message;
1054 bool Buffer::write(ostream & ofs) const
1057 // Use the standard "C" locale for file output.
1058 ofs.imbue(locale::classic());
1061 // The top of the file should not be written by params().
1063 // write out a comment in the top of the file
1064 ofs << "#LyX " << lyx_version
1065 << " created this file. For more info see http://www.lyx.org/\n"
1066 << "\\lyxformat " << LYX_FORMAT << "\n"
1067 << "\\begin_document\n";
1069 /// For each author, set 'used' to true if there is a change
1070 /// by this author in the document; otherwise set it to 'false'.
1071 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1072 AuthorList::Authors::const_iterator a_end = params().authors().end();
1073 for (; a_it != a_end; ++a_it)
1074 a_it->setUsed(false);
1076 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1077 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1078 for ( ; it != end; ++it)
1079 it->checkAuthors(params().authors());
1081 // now write out the buffer parameters.
1082 ofs << "\\begin_header\n";
1083 params().writeFile(ofs);
1084 ofs << "\\end_header\n";
1087 ofs << "\n\\begin_body\n";
1089 ofs << "\n\\end_body\n";
1091 // Write marker that shows file is complete
1092 ofs << "\\end_document" << endl;
1094 // Shouldn't really be needed....
1097 // how to check if close went ok?
1098 // Following is an attempt... (BE 20001011)
1100 // good() returns false if any error occured, including some
1101 // formatting error.
1102 // bad() returns true if something bad happened in the buffer,
1103 // which should include file system full errors.
1108 lyxerr << "File was not closed properly." << endl;
1115 bool Buffer::makeLaTeXFile(FileName const & fname,
1116 string const & original_path,
1117 OutputParams const & runparams_in,
1118 bool output_preamble, bool output_body) const
1120 OutputParams runparams = runparams_in;
1121 if (params().useXetex)
1122 runparams.flavor = OutputParams::XETEX;
1124 string const encoding = runparams.encoding->iconvName();
1125 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1128 try { ofs.reset(encoding); }
1129 catch (iconv_codecvt_facet_exception & e) {
1130 lyxerr << "Caught iconv exception: " << e.what() << endl;
1131 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1132 "verify that the support software for your encoding (%1$s) is "
1133 "properly installed"), from_ascii(encoding)));
1136 if (!openFileWrite(ofs, fname))
1139 //TexStream ts(ofs.rdbuf(), &texrow());
1140 ErrorList & errorList = d->errorLists["Export"];
1142 bool failed_export = false;
1145 writeLaTeXSource(ofs, original_path,
1146 runparams, output_preamble, output_body);
1148 catch (EncodingException & e) {
1149 odocstringstream ods;
1150 ods.put(e.failed_char);
1152 oss << "0x" << hex << e.failed_char << dec;
1153 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1154 " (code point %2$s)"),
1155 ods.str(), from_utf8(oss.str()));
1156 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1157 "representable in the chosen encoding.\n"
1158 "Changing the document encoding to utf8 could help."),
1159 e.par_id, e.pos, e.pos + 1));
1160 failed_export = true;
1162 catch (iconv_codecvt_facet_exception & e) {
1163 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1164 _(e.what()), -1, 0, 0));
1165 failed_export = true;
1167 catch (exception const & e) {
1168 errorList.push_back(ErrorItem(_("conversion failed"),
1169 _(e.what()), -1, 0, 0));
1170 failed_export = true;
1173 lyxerr << "Caught some really weird exception..." << endl;
1179 failed_export = true;
1180 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1184 return !failed_export;
1188 void Buffer::writeLaTeXSource(odocstream & os,
1189 string const & original_path,
1190 OutputParams const & runparams_in,
1191 bool const output_preamble, bool const output_body) const
1193 // The child documents, if any, shall be already loaded at this point.
1195 OutputParams runparams = runparams_in;
1197 // Classify the unicode characters appearing in math insets
1198 Encodings::initUnicodeMath(*this);
1200 // validate the buffer.
1201 LYXERR(Debug::LATEX, " Validating buffer...");
1202 LaTeXFeatures features(*this, params(), runparams);
1204 LYXERR(Debug::LATEX, " Buffer validation done.");
1206 // The starting paragraph of the coming rows is the
1207 // first paragraph of the document. (Asger)
1208 if (output_preamble && runparams.nice) {
1209 os << "%% LyX " << lyx_version << " created this file. "
1210 "For more info, see http://www.lyx.org/.\n"
1211 "%% Do not edit unless you really know what "
1213 d->texrow.newline();
1214 d->texrow.newline();
1216 LYXERR(Debug::INFO, "lyx document header finished");
1218 // Don't move this behind the parent_buffer=0 code below,
1219 // because then the macros will not get the right "redefinition"
1220 // flag as they don't see the parent macros which are output before.
1223 // fold macros if possible, still with parent buffer as the
1224 // macros will be put in the prefix anyway.
1225 updateMacroInstances();
1227 // There are a few differences between nice LaTeX and usual files:
1228 // usual is \batchmode and has a
1229 // special input@path to allow the including of figures
1230 // with either \input or \includegraphics (what figinsets do).
1231 // input@path is set when the actual parameter
1232 // original_path is set. This is done for usual tex-file, but not
1233 // for nice-latex-file. (Matthias 250696)
1234 // Note that input@path is only needed for something the user does
1235 // in the preamble, included .tex files or ERT, files included by
1236 // LyX work without it.
1237 if (output_preamble) {
1238 if (!runparams.nice) {
1239 // code for usual, NOT nice-latex-file
1240 os << "\\batchmode\n"; // changed
1241 // from \nonstopmode
1242 d->texrow.newline();
1244 if (!original_path.empty()) {
1246 // We don't know the encoding of inputpath
1247 docstring const inputpath = from_utf8(latex_path(original_path));
1248 os << "\\makeatletter\n"
1249 << "\\def\\input@path{{"
1250 << inputpath << "/}}\n"
1251 << "\\makeatother\n";
1252 d->texrow.newline();
1253 d->texrow.newline();
1254 d->texrow.newline();
1257 // get parent macros (if this buffer has a parent) which will be
1258 // written at the document begin further down.
1259 MacroSet parentMacros;
1260 listParentMacros(parentMacros, features);
1262 // Write the preamble
1263 runparams.use_babel = params().writeLaTeX(os, features,
1265 d->filename.onlyPath());
1267 runparams.use_japanese = features.isRequired("japanese");
1273 os << "\\begin{document}\n";
1274 d->texrow.newline();
1276 // output the parent macros
1277 MacroSet::iterator it = parentMacros.begin();
1278 MacroSet::iterator end = parentMacros.end();
1279 for (; it != end; ++it)
1280 (*it)->write(os, true);
1281 } // output_preamble
1283 d->texrow.start(paragraphs().begin()->id(), 0);
1285 LYXERR(Debug::INFO, "preamble finished, now the body.");
1287 // if we are doing a real file with body, even if this is the
1288 // child of some other buffer, let's cut the link here.
1289 // This happens for example if only a child document is printed.
1290 Buffer const * save_parent = 0;
1291 if (output_preamble) {
1292 save_parent = d->parent();
1297 latexParagraphs(*this, text(), os, d->texrow, runparams);
1299 // Restore the parenthood if needed
1300 if (output_preamble)
1301 d->setParent(save_parent);
1303 // add this just in case after all the paragraphs
1305 d->texrow.newline();
1307 if (output_preamble) {
1308 os << "\\end{document}\n";
1309 d->texrow.newline();
1310 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1312 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1314 runparams_in.encoding = runparams.encoding;
1316 // Just to be sure. (Asger)
1317 d->texrow.newline();
1319 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1320 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1324 bool Buffer::isLatex() const
1326 return params().documentClass().outputType() == LATEX;
1330 bool Buffer::isLiterate() const
1332 return params().documentClass().outputType() == LITERATE;
1336 bool Buffer::isDocBook() const
1338 return params().documentClass().outputType() == DOCBOOK;
1342 void Buffer::makeDocBookFile(FileName const & fname,
1343 OutputParams const & runparams,
1344 bool const body_only) const
1346 LYXERR(Debug::LATEX, "makeDocBookFile...");
1349 if (!openFileWrite(ofs, fname))
1352 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1356 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1360 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1361 OutputParams const & runparams,
1362 bool const only_body) const
1364 LaTeXFeatures features(*this, params(), runparams);
1369 DocumentClass const & tclass = params().documentClass();
1370 string const top_element = tclass.latexname();
1373 if (runparams.flavor == OutputParams::XML)
1374 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1377 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1380 if (! tclass.class_header().empty())
1381 os << from_ascii(tclass.class_header());
1382 else if (runparams.flavor == OutputParams::XML)
1383 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1384 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1386 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1388 docstring preamble = from_utf8(params().preamble);
1389 if (runparams.flavor != OutputParams::XML ) {
1390 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1391 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1392 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1393 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1396 string const name = runparams.nice
1397 ? changeExtension(absFileName(), ".sgml") : fname;
1398 preamble += features.getIncludedFiles(name);
1399 preamble += features.getLyXSGMLEntities();
1401 if (!preamble.empty()) {
1402 os << "\n [ " << preamble << " ]";
1407 string top = top_element;
1409 if (runparams.flavor == OutputParams::XML)
1410 top += params().language->code();
1412 top += params().language->code().substr(0, 2);
1415 if (!params().options.empty()) {
1417 top += params().options;
1420 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1421 << " file was created by LyX " << lyx_version
1422 << "\n See http://www.lyx.org/ for more information -->\n";
1424 params().documentClass().counters().reset();
1428 sgml::openTag(os, top);
1430 docbookParagraphs(text(), *this, os, runparams);
1431 sgml::closeTag(os, top_element);
1435 void Buffer::makeLyXHTMLFile(FileName const & fname,
1436 OutputParams const & runparams,
1437 bool const body_only) const
1439 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1442 if (!openFileWrite(ofs, fname))
1445 writeLyXHTMLSource(ofs, runparams, body_only);
1449 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1453 void Buffer::writeLyXHTMLSource(odocstream & os,
1454 OutputParams const & runparams,
1455 bool const only_body) const
1457 LaTeXFeatures features(*this, params(), runparams);
1459 updateLabels(UpdateMaster, true);
1460 checkBibInfoCache();
1461 d->bibinfo_.collectCitedEntries(*this);
1464 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1465 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";
1466 // FIXME Language should be set properly.
1467 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1470 // FIXME Presumably need to set this right
1471 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1472 // FIXME Get this during validation? What about other meta-data?
1473 os << "<title>TBA</title>\n";
1475 os << "\n<!-- Text Class Preamble -->\n"
1476 << features.getTClassHTMLPreamble()
1477 << "\n<!-- Premable Snippets -->\n"
1478 << from_utf8(features.getPreambleSnippets());
1480 os << "\n<!-- Layout-provided Styles -->\n";
1481 docstring const styleinfo = features.getTClassHTMLStyles();
1482 if (!styleinfo.empty()) {
1483 os << "<style type='text/css'>\n"
1487 os << "</head>\n<body>\n";
1491 params().documentClass().counters().reset();
1492 xhtmlParagraphs(text(), *this, xs, runparams);
1494 os << "</body>\n</html>\n";
1498 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1499 // Other flags: -wall -v0 -x
1500 int Buffer::runChktex()
1504 // get LaTeX-Filename
1505 FileName const path(temppath());
1506 string const name = addName(path.absFilename(), latexName());
1507 string const org_path = filePath();
1509 PathChanger p(path); // path to LaTeX file
1510 message(_("Running chktex..."));
1512 // Generate the LaTeX file if neccessary
1513 OutputParams runparams(¶ms().encoding());
1514 runparams.flavor = OutputParams::LATEX;
1515 runparams.nice = false;
1516 makeLaTeXFile(FileName(name), org_path, runparams);
1519 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1520 int const res = chktex.run(terr); // run chktex
1523 Alert::error(_("chktex failure"),
1524 _("Could not run chktex successfully."));
1525 } else if (res > 0) {
1526 ErrorList & errlist = d->errorLists["ChkTeX"];
1528 bufferErrors(terr, errlist);
1539 void Buffer::validate(LaTeXFeatures & features) const
1541 params().validate(features);
1545 for_each(paragraphs().begin(), paragraphs().end(),
1546 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1548 if (lyxerr.debugging(Debug::LATEX)) {
1549 features.showStruct();
1554 void Buffer::getLabelList(vector<docstring> & list) const
1556 // If this is a child document, use the parent's list instead.
1557 Buffer const * const pbuf = d->parent();
1559 pbuf->getLabelList(list);
1564 Toc & toc = d->toc_backend.toc("label");
1565 TocIterator toc_it = toc.begin();
1566 TocIterator end = toc.end();
1567 for (; toc_it != end; ++toc_it) {
1568 if (toc_it->depth() == 0)
1569 list.push_back(toc_it->str());
1574 void Buffer::updateBibfilesCache(UpdateScope scope) const
1576 // If this is a child document, use the parent's cache instead.
1577 Buffer const * const pbuf = d->parent();
1578 if (pbuf && scope != UpdateChildOnly) {
1579 pbuf->updateBibfilesCache();
1583 d->bibfilesCache_.clear();
1584 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1585 if (it->lyxCode() == BIBTEX_CODE) {
1586 InsetBibtex const & inset =
1587 static_cast<InsetBibtex const &>(*it);
1588 support::FileNameList const bibfiles = inset.getBibFiles();
1589 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1592 } else if (it->lyxCode() == INCLUDE_CODE) {
1593 InsetInclude & inset =
1594 static_cast<InsetInclude &>(*it);
1595 inset.updateBibfilesCache();
1596 support::FileNameList const & bibfiles =
1597 inset.getBibfilesCache();
1598 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1603 // the bibinfo cache is now invalid
1604 d->bibinfoCacheValid_ = false;
1608 void Buffer::invalidateBibinfoCache()
1610 d->bibinfoCacheValid_ = false;
1614 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1616 // If this is a child document, use the parent's cache instead.
1617 Buffer const * const pbuf = d->parent();
1618 if (pbuf && scope != UpdateChildOnly)
1619 return pbuf->getBibfilesCache();
1621 // We update the cache when first used instead of at loading time.
1622 if (d->bibfilesCache_.empty())
1623 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1625 return d->bibfilesCache_;
1629 BiblioInfo const & Buffer::masterBibInfo() const
1631 // if this is a child document and the parent is already loaded
1632 // use the parent's list instead [ale990412]
1633 Buffer const * const tmp = masterBuffer();
1636 return tmp->masterBibInfo();
1637 return localBibInfo();
1641 BiblioInfo const & Buffer::localBibInfo() const
1643 checkBibInfoCache();
1648 void Buffer::checkBibInfoCache() const
1650 support::FileNameList const & bibfilesCache = getBibfilesCache();
1651 // compare the cached timestamps with the actual ones.
1652 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1653 support::FileNameList::const_iterator en = bibfilesCache.end();
1654 for (; ei != en; ++ ei) {
1655 time_t lastw = ei->lastModified();
1656 time_t prevw = d->bibfileStatus_[*ei];
1657 if (lastw != prevw) {
1658 d->bibinfoCacheValid_ = false;
1659 d->bibfileStatus_[*ei] = lastw;
1663 if (!d->bibinfoCacheValid_) {
1664 d->bibinfo_.clear();
1665 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1666 it->fillWithBibKeys(d->bibinfo_, it);
1667 d->bibinfoCacheValid_ = true;
1672 bool Buffer::isDepClean(string const & name) const
1674 DepClean::const_iterator const it = d->dep_clean.find(name);
1675 if (it == d->dep_clean.end())
1681 void Buffer::markDepClean(string const & name)
1683 d->dep_clean[name] = true;
1687 bool Buffer::isExportableFormat(string const & format) const
1689 typedef vector<Format const *> Formats;
1691 formats = exportableFormats(true);
1692 Formats::const_iterator fit = formats.begin();
1693 Formats::const_iterator end = formats.end();
1694 for (; fit != end ; ++fit) {
1695 if ((*fit)->name() == format)
1702 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1705 // FIXME? if there is an Buffer LFUN that can be dispatched even
1706 // if internal, put a switch '(cmd.action)' here.
1712 switch (cmd.action) {
1714 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1715 flag.setOnOff(isReadonly());
1718 // FIXME: There is need for a command-line import.
1719 //case LFUN_BUFFER_IMPORT:
1721 case LFUN_BUFFER_AUTO_SAVE:
1724 case LFUN_BUFFER_EXPORT_CUSTOM:
1725 // FIXME: Nothing to check here?
1728 case LFUN_BUFFER_EXPORT: {
1729 docstring const arg = cmd.argument();
1730 enable = arg == "custom" || isExportable(to_utf8(arg));
1732 flag.message(bformat(
1733 _("Don't know how to export to format: %1$s"), arg));
1737 case LFUN_BUFFER_CHKTEX:
1738 enable = isLatex() && !lyxrc.chktex_command.empty();
1741 case LFUN_BUILD_PROGRAM:
1742 enable = isExportable("program");
1745 case LFUN_BRANCH_ACTIVATE:
1746 case LFUN_BRANCH_DEACTIVATE: {
1747 BranchList const & branchList = params().branchlist();
1748 docstring const branchName = cmd.argument();
1749 enable = !branchName.empty() && branchList.find(branchName);
1753 case LFUN_BRANCH_ADD:
1754 case LFUN_BRANCHES_RENAME:
1755 case LFUN_BUFFER_PRINT:
1756 // if no Buffer is present, then of course we won't be called!
1759 case LFUN_BUFFER_LANGUAGE:
1760 enable = !isReadonly();
1766 flag.setEnabled(enable);
1771 void Buffer::dispatch(string const & command, DispatchResult & result)
1773 return dispatch(lyxaction.lookupFunc(command), result);
1777 // NOTE We can end up here even if we have no GUI, because we are called
1778 // by LyX::exec to handled command-line requests. So we may need to check
1779 // whether we have a GUI or not. The boolean use_gui holds this information.
1780 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1783 // FIXME? if there is an Buffer LFUN that can be dispatched even
1784 // if internal, put a switch '(cmd.action)' here.
1785 dr.dispatched(false);
1788 string const argument = to_utf8(func.argument());
1789 // We'll set this back to false if need be.
1790 bool dispatched = true;
1791 undo().beginUndoGroup();
1793 switch (func.action) {
1794 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1795 if (lyxvc().inUse())
1796 lyxvc().toggleReadOnly();
1798 setReadonly(!isReadonly());
1801 case LFUN_BUFFER_EXPORT: {
1802 bool success = doExport(argument, false);
1803 dr.setError(success);
1805 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1810 case LFUN_BUILD_PROGRAM:
1811 doExport("program", true);
1814 case LFUN_BUFFER_CHKTEX:
1818 case LFUN_BUFFER_EXPORT_CUSTOM: {
1820 string command = split(argument, format_name, ' ');
1821 Format const * format = formats.getFormat(format_name);
1823 lyxerr << "Format \"" << format_name
1824 << "\" not recognized!"
1829 // The name of the file created by the conversion process
1832 // Output to filename
1833 if (format->name() == "lyx") {
1834 string const latexname = latexName(false);
1835 filename = changeExtension(latexname,
1836 format->extension());
1837 filename = addName(temppath(), filename);
1839 if (!writeFile(FileName(filename)))
1843 doExport(format_name, true, filename);
1846 // Substitute $$FName for filename
1847 if (!contains(command, "$$FName"))
1848 command = "( " + command + " ) < $$FName";
1849 command = subst(command, "$$FName", filename);
1851 // Execute the command in the background
1853 call.startscript(Systemcall::DontWait, command);
1857 // FIXME: There is need for a command-line import.
1859 case LFUN_BUFFER_IMPORT:
1864 case LFUN_BUFFER_AUTO_SAVE:
1868 case LFUN_BRANCH_ADD: {
1869 docstring const branch_name = func.argument();
1870 if (branch_name.empty()) {
1874 BranchList & branch_list = params().branchlist();
1875 Branch * branch = branch_list.find(branch_name);
1877 LYXERR0("Branch " << branch_name << " already exists.");
1879 docstring const msg =
1880 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1883 branch_list.add(branch_name);
1884 branch = branch_list.find(branch_name);
1885 string const x11hexname = X11hexname(branch->color());
1886 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1887 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1889 dr.update(Update::Force);
1894 case LFUN_BRANCH_ACTIVATE:
1895 case LFUN_BRANCH_DEACTIVATE: {
1896 BranchList & branchList = params().branchlist();
1897 docstring const branchName = func.argument();
1898 // the case without a branch name is handled elsewhere
1899 if (branchName.empty()) {
1903 Branch * branch = branchList.find(branchName);
1905 LYXERR0("Branch " << branchName << " does not exist.");
1907 docstring const msg =
1908 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1911 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1913 dr.update(Update::Force);
1918 case LFUN_BRANCHES_RENAME: {
1919 if (func.argument().empty())
1922 docstring const oldname = from_utf8(func.getArg(0));
1923 docstring const newname = from_utf8(func.getArg(1));
1924 InsetIterator it = inset_iterator_begin(inset());
1925 InsetIterator const end = inset_iterator_end(inset());
1926 bool success = false;
1927 for (; it != end; ++it) {
1928 if (it->lyxCode() == BRANCH_CODE) {
1929 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1930 if (ins.branch() == oldname) {
1931 undo().recordUndo(it);
1932 ins.rename(newname);
1937 if (it->lyxCode() == INCLUDE_CODE) {
1938 // get buffer of external file
1939 InsetInclude const & ins =
1940 static_cast<InsetInclude const &>(*it);
1941 Buffer * child = ins.getChildBuffer();
1944 child->dispatch(func, dr);
1949 dr.update(Update::Force);
1953 case LFUN_BUFFER_PRINT: {
1954 // we'll assume there's a problem until we succeed
1956 string target = func.getArg(0);
1957 string target_name = func.getArg(1);
1958 string command = func.getArg(2);
1961 || target_name.empty()
1962 || command.empty()) {
1963 LYXERR0("Unable to parse " << func.argument());
1964 docstring const msg =
1965 bformat(_("Unable to parse \"%1$s\""), func.argument());
1969 if (target != "printer" && target != "file") {
1970 LYXERR0("Unrecognized target \"" << target << '"');
1971 docstring const msg =
1972 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1977 if (!doExport("dvi", true)) {
1978 showPrintError(absFileName());
1979 dr.setMessage(_("Error exporting to DVI."));
1983 // Push directory path.
1984 string const path = temppath();
1985 // Prevent the compiler from optimizing away p
1989 // there are three cases here:
1990 // 1. we print to a file
1991 // 2. we print directly to a printer
1992 // 3. we print using a spool command (print to file first)
1995 string const dviname = changeExtension(latexName(true), "dvi");
1997 if (target == "printer") {
1998 if (!lyxrc.print_spool_command.empty()) {
1999 // case 3: print using a spool
2000 string const psname = changeExtension(dviname,".ps");
2001 command += ' ' + lyxrc.print_to_file
2004 + quoteName(dviname);
2006 string command2 = lyxrc.print_spool_command + ' ';
2007 if (target_name != "default") {
2008 command2 += lyxrc.print_spool_printerprefix
2012 command2 += quoteName(psname);
2014 // If successful, then spool command
2015 res = one.startscript(Systemcall::Wait, command);
2018 // If there's no GUI, we have to wait on this command. Otherwise,
2019 // LyX deletes the temporary directory, and with it the spooled
2020 // file, before it can be printed!!
2021 Systemcall::Starttype stype = use_gui ?
2022 Systemcall::DontWait : Systemcall::Wait;
2023 res = one.startscript(stype, command2);
2026 // case 2: print directly to a printer
2027 if (target_name != "default")
2028 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2030 Systemcall::Starttype stype = use_gui ?
2031 Systemcall::DontWait : Systemcall::Wait;
2032 res = one.startscript(stype, command + quoteName(dviname));
2036 // case 1: print to a file
2037 FileName const filename(makeAbsPath(target_name, filePath()));
2038 FileName const dvifile(makeAbsPath(dviname, path));
2039 if (filename.exists()) {
2040 docstring text = bformat(
2041 _("The file %1$s already exists.\n\n"
2042 "Do you want to overwrite that file?"),
2043 makeDisplayPath(filename.absFilename()));
2044 if (Alert::prompt(_("Overwrite file?"),
2045 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2048 command += ' ' + lyxrc.print_to_file
2049 + quoteName(filename.toFilesystemEncoding())
2051 + quoteName(dvifile.toFilesystemEncoding());
2053 Systemcall::Starttype stype = use_gui ?
2054 Systemcall::DontWait : Systemcall::Wait;
2055 res = one.startscript(stype, command);
2061 dr.setMessage(_("Error running external commands."));
2062 showPrintError(absFileName());
2067 case LFUN_BUFFER_LANGUAGE: {
2068 Language const * oldL = params().language;
2069 Language const * newL = languages.getLanguage(argument);
2070 if (!newL || oldL == newL)
2072 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2073 changeLanguage(oldL, newL);
2081 dr.dispatched(dispatched);
2082 undo().endUndoGroup();
2086 void Buffer::changeLanguage(Language const * from, Language const * to)
2088 LASSERT(from, /**/);
2091 for_each(par_iterator_begin(),
2093 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2097 bool Buffer::isMultiLingual() const
2099 ParConstIterator end = par_iterator_end();
2100 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2101 if (it->isMultiLingual(params()))
2108 DocIterator Buffer::getParFromID(int const id) const
2110 Buffer * buf = const_cast<Buffer *>(this);
2112 // John says this is called with id == -1 from undo
2113 lyxerr << "getParFromID(), id: " << id << endl;
2114 return doc_iterator_end(buf);
2117 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2118 if (it.paragraph().id() == id)
2121 return doc_iterator_end(buf);
2125 bool Buffer::hasParWithID(int const id) const
2127 return !getParFromID(id).atEnd();
2131 ParIterator Buffer::par_iterator_begin()
2133 return ParIterator(doc_iterator_begin(this));
2137 ParIterator Buffer::par_iterator_end()
2139 return ParIterator(doc_iterator_end(this));
2143 ParConstIterator Buffer::par_iterator_begin() const
2145 return ParConstIterator(doc_iterator_begin(this));
2149 ParConstIterator Buffer::par_iterator_end() const
2151 return ParConstIterator(doc_iterator_end(this));
2155 Language const * Buffer::language() const
2157 return params().language;
2161 docstring const Buffer::B_(string const & l10n) const
2163 return params().B_(l10n);
2167 bool Buffer::isClean() const
2169 return d->lyx_clean;
2173 bool Buffer::isBakClean() const
2175 return d->bak_clean;
2179 bool Buffer::isExternallyModified(CheckMethod method) const
2181 LASSERT(d->filename.exists(), /**/);
2182 // if method == timestamp, check timestamp before checksum
2183 return (method == checksum_method
2184 || d->timestamp_ != d->filename.lastModified())
2185 && d->checksum_ != d->filename.checksum();
2189 void Buffer::saveCheckSum(FileName const & file) const
2191 if (file.exists()) {
2192 d->timestamp_ = file.lastModified();
2193 d->checksum_ = file.checksum();
2195 // in the case of save to a new file.
2202 void Buffer::markClean() const
2204 if (!d->lyx_clean) {
2205 d->lyx_clean = true;
2208 // if the .lyx file has been saved, we don't need an
2210 d->bak_clean = true;
2214 void Buffer::markBakClean() const
2216 d->bak_clean = true;
2220 void Buffer::setUnnamed(bool flag)
2226 bool Buffer::isUnnamed() const
2233 /// Don't check unnamed, here: isInternal() is used in
2234 /// newBuffer(), where the unnamed flag has not been set by anyone
2235 /// yet. Also, for an internal buffer, there should be no need for
2236 /// retrieving fileName() nor for checking if it is unnamed or not.
2237 bool Buffer::isInternal() const
2239 return fileName().extension() == "internal";
2243 void Buffer::markDirty()
2246 d->lyx_clean = false;
2249 d->bak_clean = false;
2251 DepClean::iterator it = d->dep_clean.begin();
2252 DepClean::const_iterator const end = d->dep_clean.end();
2254 for (; it != end; ++it)
2259 FileName Buffer::fileName() const
2265 string Buffer::absFileName() const
2267 return d->filename.absFilename();
2271 string Buffer::filePath() const
2273 return d->filename.onlyPath().absFilename() + "/";
2277 bool Buffer::isReadonly() const
2279 return d->read_only;
2283 void Buffer::setParent(Buffer const * buffer)
2285 // Avoids recursive include.
2286 d->setParent(buffer == this ? 0 : buffer);
2291 Buffer const * Buffer::parent() const
2297 void Buffer::collectRelatives(BufferSet & bufs) const
2301 parent()->collectRelatives(bufs);
2303 // loop over children
2304 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2305 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2306 for (; it != end; ++it)
2307 bufs.insert(const_cast<Buffer *>(it->first));
2311 std::vector<Buffer const *> Buffer::allRelatives() const
2314 collectRelatives(bufs);
2315 BufferSet::iterator it = bufs.begin();
2316 std::vector<Buffer const *> ret;
2317 for (; it != bufs.end(); ++it)
2323 Buffer const * Buffer::masterBuffer() const
2325 Buffer const * const pbuf = d->parent();
2329 return pbuf->masterBuffer();
2333 bool Buffer::isChild(Buffer * child) const
2335 return d->children_positions.find(child) != d->children_positions.end();
2339 DocIterator Buffer::firstChildPosition(Buffer const * child)
2341 Impl::BufferPositionMap::iterator it;
2342 it = d->children_positions.find(child);
2343 if (it == d->children_positions.end())
2344 return DocIterator(this);
2349 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2351 // loop over children
2352 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2353 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2354 for (; it != end; ++it) {
2355 Buffer * child = const_cast<Buffer *>(it->first);
2356 clist.push_back(child);
2357 if (grand_children) {
2358 // there might be grandchildren
2359 std::vector<Buffer *> glist = child->getChildren();
2360 for (vector<Buffer *>::const_iterator git = glist.begin();
2361 git != glist.end(); ++git)
2362 clist.push_back(*git);
2368 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2370 std::vector<Buffer *> v;
2371 getChildren(v, grand_children);
2376 template<typename M>
2377 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2382 typename M::iterator it = m.lower_bound(x);
2383 if (it == m.begin())
2391 MacroData const * Buffer::getBufferMacro(docstring const & name,
2392 DocIterator const & pos) const
2394 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2396 // if paragraphs have no macro context set, pos will be empty
2400 // we haven't found anything yet
2401 DocIterator bestPos = par_iterator_begin();
2402 MacroData const * bestData = 0;
2404 // find macro definitions for name
2405 Impl::NamePositionScopeMacroMap::iterator nameIt
2406 = d->macros.find(name);
2407 if (nameIt != d->macros.end()) {
2408 // find last definition in front of pos or at pos itself
2409 Impl::PositionScopeMacroMap::const_iterator it
2410 = greatest_below(nameIt->second, pos);
2411 if (it != nameIt->second.end()) {
2413 // scope ends behind pos?
2414 if (pos < it->second.first) {
2415 // Looks good, remember this. If there
2416 // is no external macro behind this,
2417 // we found the right one already.
2418 bestPos = it->first;
2419 bestData = &it->second.second;
2423 // try previous macro if there is one
2424 if (it == nameIt->second.begin())
2431 // find macros in included files
2432 Impl::PositionScopeBufferMap::const_iterator it
2433 = greatest_below(d->position_to_children, pos);
2434 if (it == d->position_to_children.end())
2435 // no children before
2439 // do we know something better (i.e. later) already?
2440 if (it->first < bestPos )
2443 // scope ends behind pos?
2444 if (pos < it->second.first) {
2445 // look for macro in external file
2446 d->macro_lock = true;
2447 MacroData const * data
2448 = it->second.second->getMacro(name, false);
2449 d->macro_lock = false;
2451 bestPos = it->first;
2457 // try previous file if there is one
2458 if (it == d->position_to_children.begin())
2463 // return the best macro we have found
2468 MacroData const * Buffer::getMacro(docstring const & name,
2469 DocIterator const & pos, bool global) const
2474 // query buffer macros
2475 MacroData const * data = getBufferMacro(name, pos);
2479 // If there is a master buffer, query that
2480 Buffer const * const pbuf = d->parent();
2482 d->macro_lock = true;
2483 MacroData const * macro = pbuf->getMacro(
2484 name, *this, false);
2485 d->macro_lock = false;
2491 data = MacroTable::globalMacros().get(name);
2500 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2502 // set scope end behind the last paragraph
2503 DocIterator scope = par_iterator_begin();
2504 scope.pit() = scope.lastpit() + 1;
2506 return getMacro(name, scope, global);
2510 MacroData const * Buffer::getMacro(docstring const & name,
2511 Buffer const & child, bool global) const
2513 // look where the child buffer is included first
2514 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2515 if (it == d->children_positions.end())
2518 // check for macros at the inclusion position
2519 return getMacro(name, it->second, global);
2523 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2525 pit_type lastpit = it.lastpit();
2527 // look for macros in each paragraph
2528 while (it.pit() <= lastpit) {
2529 Paragraph & par = it.paragraph();
2531 // iterate over the insets of the current paragraph
2532 InsetList const & insets = par.insetList();
2533 InsetList::const_iterator iit = insets.begin();
2534 InsetList::const_iterator end = insets.end();
2535 for (; iit != end; ++iit) {
2536 it.pos() = iit->pos;
2538 // is it a nested text inset?
2539 if (iit->inset->asInsetText()) {
2540 // Inset needs its own scope?
2541 InsetText const * itext = iit->inset->asInsetText();
2542 bool newScope = itext->isMacroScope();
2544 // scope which ends just behind the inset
2545 DocIterator insetScope = it;
2548 // collect macros in inset
2549 it.push_back(CursorSlice(*iit->inset));
2550 updateMacros(it, newScope ? insetScope : scope);
2555 // is it an external file?
2556 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2557 // get buffer of external file
2558 InsetInclude const & inset =
2559 static_cast<InsetInclude const &>(*iit->inset);
2560 d->macro_lock = true;
2561 Buffer * child = inset.getChildBuffer();
2562 d->macro_lock = false;
2566 // register its position, but only when it is
2567 // included first in the buffer
2568 if (d->children_positions.find(child) ==
2569 d->children_positions.end())
2570 d->children_positions[child] = it;
2572 // register child with its scope
2573 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2577 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2581 MathMacroTemplate & macroTemplate =
2582 static_cast<MathMacroTemplate &>(*iit->inset);
2583 MacroContext mc(this, it);
2584 macroTemplate.updateToContext(mc);
2587 bool valid = macroTemplate.validMacro();
2588 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2589 // then the BufferView's cursor will be invalid in
2590 // some cases which leads to crashes.
2595 // FIXME (Abdel), I don't understandt why we pass 'it' here
2596 // instead of 'macroTemplate' defined above... is this correct?
2597 d->macros[macroTemplate.name()][it] =
2598 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2608 void Buffer::updateMacros() const
2613 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2615 // start with empty table
2617 d->children_positions.clear();
2618 d->position_to_children.clear();
2620 // Iterate over buffer, starting with first paragraph
2621 // The scope must be bigger than any lookup DocIterator
2622 // later. For the global lookup, lastpit+1 is used, hence
2623 // we use lastpit+2 here.
2624 DocIterator it = par_iterator_begin();
2625 DocIterator outerScope = it;
2626 outerScope.pit() = outerScope.lastpit() + 2;
2627 updateMacros(it, outerScope);
2631 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2633 InsetIterator it = inset_iterator_begin(inset());
2634 InsetIterator const end = inset_iterator_end(inset());
2635 for (; it != end; ++it) {
2636 if (it->lyxCode() == BRANCH_CODE) {
2637 InsetBranch & br = static_cast<InsetBranch &>(*it);
2638 docstring const name = br.branch();
2639 if (!from_master && !params().branchlist().find(name))
2640 result.push_back(name);
2641 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2642 result.push_back(name);
2645 if (it->lyxCode() == INCLUDE_CODE) {
2646 // get buffer of external file
2647 InsetInclude const & ins =
2648 static_cast<InsetInclude const &>(*it);
2649 Buffer * child = ins.getChildBuffer();
2652 child->getUsedBranches(result, true);
2655 // remove duplicates
2660 void Buffer::updateMacroInstances() const
2662 LYXERR(Debug::MACROS, "updateMacroInstances for "
2663 << d->filename.onlyFileName());
2664 DocIterator it = doc_iterator_begin(this);
2666 DocIterator const end = doc_iterator_end(this);
2667 for (; it != end; it.forwardInset()) {
2668 // look for MathData cells in InsetMathNest insets
2669 InsetMath * minset = it.nextInset()->asInsetMath();
2673 // update macro in all cells of the InsetMathNest
2674 DocIterator::idx_type n = minset->nargs();
2675 MacroContext mc = MacroContext(this, it);
2676 for (DocIterator::idx_type i = 0; i < n; ++i) {
2677 MathData & data = minset->cell(i);
2678 data.updateMacros(0, mc);
2684 void Buffer::listMacroNames(MacroNameSet & macros) const
2689 d->macro_lock = true;
2691 // loop over macro names
2692 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2693 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2694 for (; nameIt != nameEnd; ++nameIt)
2695 macros.insert(nameIt->first);
2697 // loop over children
2698 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2699 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2700 for (; it != end; ++it)
2701 it->first->listMacroNames(macros);
2704 Buffer const * const pbuf = d->parent();
2706 pbuf->listMacroNames(macros);
2708 d->macro_lock = false;
2712 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2714 Buffer const * const pbuf = d->parent();
2719 pbuf->listMacroNames(names);
2722 MacroNameSet::iterator it = names.begin();
2723 MacroNameSet::iterator end = names.end();
2724 for (; it != end; ++it) {
2726 MacroData const * data =
2727 pbuf->getMacro(*it, *this, false);
2729 macros.insert(data);
2731 // we cannot access the original MathMacroTemplate anymore
2732 // here to calls validate method. So we do its work here manually.
2733 // FIXME: somehow make the template accessible here.
2734 if (data->optionals() > 0)
2735 features.require("xargs");
2741 Buffer::References & Buffer::references(docstring const & label)
2744 return const_cast<Buffer *>(masterBuffer())->references(label);
2746 RefCache::iterator it = d->ref_cache_.find(label);
2747 if (it != d->ref_cache_.end())
2748 return it->second.second;
2750 static InsetLabel const * dummy_il = 0;
2751 static References const dummy_refs;
2752 it = d->ref_cache_.insert(
2753 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2754 return it->second.second;
2758 Buffer::References const & Buffer::references(docstring const & label) const
2760 return const_cast<Buffer *>(this)->references(label);
2764 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2766 masterBuffer()->d->ref_cache_[label].first = il;
2770 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2772 return masterBuffer()->d->ref_cache_[label].first;
2776 void Buffer::clearReferenceCache() const
2779 d->ref_cache_.clear();
2783 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2786 //FIXME: This does not work for child documents yet.
2787 LASSERT(code == CITE_CODE, /**/);
2788 // Check if the label 'from' appears more than once
2789 vector<docstring> labels;
2791 BiblioInfo const & keys = masterBibInfo();
2792 BiblioInfo::const_iterator bit = keys.begin();
2793 BiblioInfo::const_iterator bend = keys.end();
2795 for (; bit != bend; ++bit)
2797 labels.push_back(bit->first);
2800 if (count(labels.begin(), labels.end(), from) > 1)
2803 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2804 if (it->lyxCode() == code) {
2805 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2806 docstring const oldValue = inset.getParam(paramName);
2807 if (oldValue == from)
2808 inset.setParam(paramName, to);
2814 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2815 pit_type par_end, bool full_source) const
2817 OutputParams runparams(¶ms().encoding());
2818 runparams.nice = true;
2819 runparams.flavor = params().useXetex ?
2820 OutputParams::XETEX : OutputParams::LATEX;
2821 runparams.linelen = lyxrc.plaintext_linelen;
2822 // No side effect of file copying and image conversion
2823 runparams.dryrun = true;
2826 os << "% " << _("Preview source code") << "\n\n";
2828 d->texrow.newline();
2829 d->texrow.newline();
2831 writeDocBookSource(os, absFileName(), runparams, false);
2833 // latex or literate
2834 writeLaTeXSource(os, string(), runparams, true, true);
2836 runparams.par_begin = par_begin;
2837 runparams.par_end = par_end;
2838 if (par_begin + 1 == par_end) {
2840 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2844 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2845 convert<docstring>(par_begin),
2846 convert<docstring>(par_end - 1))
2853 // output paragraphs
2855 docbookParagraphs(text(), *this, os, runparams);
2857 // latex or literate
2858 latexParagraphs(*this, text(), os, texrow, runparams);
2863 ErrorList & Buffer::errorList(string const & type) const
2865 static ErrorList emptyErrorList;
2866 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2867 if (I == d->errorLists.end())
2868 return emptyErrorList;
2874 void Buffer::updateTocItem(std::string const & type,
2875 DocIterator const & dit) const
2878 gui_->updateTocItem(type, dit);
2882 void Buffer::structureChanged() const
2885 gui_->structureChanged();
2889 void Buffer::errors(string const & err, bool from_master) const
2892 gui_->errors(err, from_master);
2896 void Buffer::message(docstring const & msg) const
2903 void Buffer::setBusy(bool on) const
2910 void Buffer::setReadOnly(bool on) const
2913 d->wa_->setReadOnly(on);
2917 void Buffer::updateTitles() const
2920 d->wa_->updateTitles();
2924 void Buffer::resetAutosaveTimers() const
2927 gui_->resetAutosaveTimers();
2931 bool Buffer::hasGuiDelegate() const
2937 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2946 class AutoSaveBuffer : public ForkedProcess {
2949 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2950 : buffer_(buffer), fname_(fname) {}
2952 virtual boost::shared_ptr<ForkedProcess> clone() const
2954 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2959 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2960 from_utf8(fname_.absFilename())));
2961 return run(DontWait);
2965 virtual int generateChild();
2967 Buffer const & buffer_;
2972 int AutoSaveBuffer::generateChild()
2974 #if defined(__APPLE__)
2975 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2976 * We should use something else like threads.
2978 * Since I do not know how to determine at run time what is the OS X
2979 * version, I just disable forking altogether for now (JMarc)
2981 pid_t const pid = -1;
2983 // tmp_ret will be located (usually) in /tmp
2984 // will that be a problem?
2985 // Note that this calls ForkedCalls::fork(), so it's
2986 // ok cross-platform.
2987 pid_t const pid = fork();
2988 // If you want to debug the autosave
2989 // you should set pid to -1, and comment out the fork.
2990 if (pid != 0 && pid != -1)
2994 // pid = -1 signifies that lyx was unable
2995 // to fork. But we will do the save
2997 bool failed = false;
2998 FileName const tmp_ret = FileName::tempName("lyxauto");
2999 if (!tmp_ret.empty()) {
3000 buffer_.writeFile(tmp_ret);
3001 // assume successful write of tmp_ret
3002 if (!tmp_ret.moveTo(fname_))
3008 // failed to write/rename tmp_ret so try writing direct
3009 if (!buffer_.writeFile(fname_)) {
3010 // It is dangerous to do this in the child,
3011 // but safe in the parent, so...
3012 if (pid == -1) // emit message signal.
3013 buffer_.message(_("Autosave failed!"));
3017 if (pid == 0) // we are the child so...
3026 FileName Buffer::getAutosaveFilename() const
3028 // if the document is unnamed try to save in the backup dir, else
3029 // in the default document path, and as a last try in the filePath,
3030 // which will most often be the temporary directory
3033 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3034 : lyxrc.backupdir_path;
3035 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3038 string const fname = "#" + d->filename.onlyFileName() + "#";
3039 return makeAbsPath(fname, fpath);
3043 void Buffer::removeAutosaveFile() const
3045 FileName const f = getAutosaveFilename();
3051 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3053 FileName const newauto = getAutosaveFilename();
3054 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3055 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3059 // Perfect target for a thread...
3060 void Buffer::autoSave() const
3062 if (isBakClean() || isReadonly()) {
3063 // We don't save now, but we'll try again later
3064 resetAutosaveTimers();
3068 // emit message signal.
3069 message(_("Autosaving current document..."));
3070 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3074 resetAutosaveTimers();
3078 string Buffer::bufferFormat() const
3080 string format = params().documentClass().outputFormat();
3081 if (format == "latex") {
3082 if (params().useXetex)
3084 if (params().encoding().package() == Encoding::japanese)
3091 string Buffer::getDefaultOutputFormat() const
3093 if (!params().defaultOutputFormat.empty()
3094 && params().defaultOutputFormat != "default")
3095 return params().defaultOutputFormat;
3096 typedef vector<Format const *> Formats;
3097 Formats formats = exportableFormats(true);
3100 || params().useXetex
3101 || params().encoding().package() == Encoding::japanese) {
3102 if (formats.empty())
3104 // return the first we find
3105 return formats.front()->name();
3107 return lyxrc.default_view_format;
3112 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3113 string & result_file) const
3115 string backend_format;
3116 OutputParams runparams(¶ms().encoding());
3117 runparams.flavor = OutputParams::LATEX;
3118 runparams.linelen = lyxrc.plaintext_linelen;
3119 vector<string> backs = backends();
3120 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3121 // Get shortest path to format
3122 Graph::EdgePath path;
3123 for (vector<string>::const_iterator it = backs.begin();
3124 it != backs.end(); ++it) {
3125 Graph::EdgePath p = theConverters().getPath(*it, format);
3126 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3127 backend_format = *it;
3132 if (!put_in_tempdir) {
3133 // Only show this alert if this is an export to a non-temporary
3134 // file (not for previewing).
3135 Alert::error(_("Couldn't export file"), bformat(
3136 _("No information for exporting the format %1$s."),
3137 formats.prettyName(format)));
3141 runparams.flavor = theConverters().getFlavor(path);
3144 backend_format = format;
3145 // FIXME: Don't hardcode format names here, but use a flag
3146 if (backend_format == "pdflatex")
3147 runparams.flavor = OutputParams::PDFLATEX;
3150 string filename = latexName(false);
3151 filename = addName(temppath(), filename);
3152 filename = changeExtension(filename,
3153 formats.extension(backend_format));
3156 updateMacroInstances();
3158 // Plain text backend
3159 if (backend_format == "text") {
3160 runparams.flavor = OutputParams::TEXT;
3161 writePlaintextFile(*this, FileName(filename), runparams);
3164 else if (backend_format == "xhtml") {
3165 runparams.flavor = OutputParams::HTML;
3166 makeLyXHTMLFile(FileName(filename), runparams);
3167 } else if (backend_format == "lyx")
3168 writeFile(FileName(filename));
3170 else if (isDocBook()) {
3171 runparams.nice = !put_in_tempdir;
3172 makeDocBookFile(FileName(filename), runparams);
3175 else if (backend_format == format) {
3176 runparams.nice = true;
3177 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3179 } else if (!lyxrc.tex_allows_spaces
3180 && contains(filePath(), ' ')) {
3181 Alert::error(_("File name error"),
3182 _("The directory path to the document cannot contain spaces."));
3185 runparams.nice = false;
3186 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3190 string const error_type = (format == "program")
3191 ? "Build" : bufferFormat();
3192 ErrorList & error_list = d->errorLists[error_type];
3193 string const ext = formats.extension(format);
3194 FileName const tmp_result_file(changeExtension(filename, ext));
3195 bool const success = theConverters().convert(this, FileName(filename),
3196 tmp_result_file, FileName(absFileName()), backend_format, format,
3198 // Emit the signal to show the error list.
3199 if (format != backend_format) {
3201 // also to the children, in case of master-buffer-view
3202 std::vector<Buffer *> clist = getChildren();
3203 for (vector<Buffer *>::const_iterator cit = clist.begin();
3204 cit != clist.end(); ++cit)
3205 (*cit)->errors(error_type, true);
3210 if (d->cloned_buffer_) {
3211 // Enable reverse dvi or pdf to work by copying back the texrow
3212 // object to the cloned buffer.
3213 // FIXME: There is a possibility of concurrent access to texrow
3214 // here from the main GUI thread that should be securized.
3215 d->cloned_buffer_->d->texrow = d->texrow;
3218 if (put_in_tempdir) {
3219 result_file = tmp_result_file.absFilename();
3223 result_file = changeExtension(exportFileName().absFilename(), ext);
3224 // We need to copy referenced files (e. g. included graphics
3225 // if format == "dvi") to the result dir.
3226 vector<ExportedFile> const files =
3227 runparams.exportdata->externalFiles(format);
3228 string const dest = onlyPath(result_file);
3229 CopyStatus status = SUCCESS;
3230 for (vector<ExportedFile>::const_iterator it = files.begin();
3231 it != files.end() && status != CANCEL; ++it) {
3232 string const fmt = formats.getFormatFromFile(it->sourceName);
3233 status = copyFile(fmt, it->sourceName,
3234 makeAbsPath(it->exportName, dest),
3235 it->exportName, status == FORCE);
3237 if (status == CANCEL) {
3238 message(_("Document export cancelled."));
3239 } else if (tmp_result_file.exists()) {
3240 // Finally copy the main file
3241 status = copyFile(format, tmp_result_file,
3242 FileName(result_file), result_file,
3244 message(bformat(_("Document exported as %1$s "
3246 formats.prettyName(format),
3247 makeDisplayPath(result_file)));
3249 // This must be a dummy converter like fax (bug 1888)
3250 message(bformat(_("Document exported as %1$s"),
3251 formats.prettyName(format)));
3258 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3261 return doExport(format, put_in_tempdir, result_file);
3265 bool Buffer::preview(string const & format) const
3268 if (!doExport(format, true, result_file))
3270 return formats.view(*this, FileName(result_file), format);
3274 bool Buffer::isExportable(string const & format) const
3276 vector<string> backs = backends();
3277 for (vector<string>::const_iterator it = backs.begin();
3278 it != backs.end(); ++it)
3279 if (theConverters().isReachable(*it, format))
3285 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3287 vector<string> const backs = backends();
3288 vector<Format const *> result =
3289 theConverters().getReachable(backs[0], only_viewable, true);
3290 for (vector<string>::const_iterator it = backs.begin() + 1;
3291 it != backs.end(); ++it) {
3292 vector<Format const *> r =
3293 theConverters().getReachable(*it, only_viewable, false);
3294 result.insert(result.end(), r.begin(), r.end());
3300 vector<string> Buffer::backends() const
3303 v.push_back(bufferFormat());
3304 // FIXME: Don't hardcode format names here, but use a flag
3305 if (v.back() == "latex")
3306 v.push_back("pdflatex");
3307 v.push_back("xhtml");
3308 v.push_back("text");
3314 bool Buffer::readFileHelper(FileName const & s)
3316 // File information about normal file
3318 docstring const file = makeDisplayPath(s.absFilename(), 50);
3319 docstring text = bformat(_("The specified document\n%1$s"
3320 "\ncould not be read."), file);
3321 Alert::error(_("Could not read document"), text);
3325 // Check if emergency save file exists and is newer.
3326 FileName const e(s.absFilename() + ".emergency");
3328 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3329 docstring const file = makeDisplayPath(s.absFilename(), 20);
3330 docstring const text =
3331 bformat(_("An emergency save of the document "
3333 "Recover emergency save?"), file);
3334 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3335 _("&Recover"), _("&Load Original"),
3339 // the file is not saved if we load the emergency file.
3344 if ((res = readFile(e)) == success)
3345 str = _("Document was successfully recovered.");
3347 str = _("Document was NOT successfully recovered.");
3348 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3349 from_utf8(e.absFilename()));
3351 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3352 _("&Remove"), _("&Keep it"))) {
3355 Alert::warning(_("Emergency file deleted"),
3356 _("Do not forget to save your file now!"), true);
3361 if (!Alert::prompt(_("Delete emergency file?"),
3362 _("Remove emergency file now?"), 1, 1,
3363 _("&Remove"), _("&Keep it")))
3371 // Now check if autosave file is newer.
3372 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3374 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3375 docstring const file = makeDisplayPath(s.absFilename(), 20);
3376 docstring const text =
3377 bformat(_("The backup of the document "
3378 "%1$s is newer.\n\nLoad the "
3379 "backup instead?"), file);
3380 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3381 _("&Load backup"), _("Load &original"),
3385 // the file is not saved if we load the autosave file.
3389 // Here we delete the autosave
3400 bool Buffer::loadLyXFile(FileName const & s)
3402 if (s.isReadableFile()) {
3403 if (readFileHelper(s)) {
3404 lyxvc().file_found_hook(s);
3405 if (!s.isWritable())
3410 docstring const file = makeDisplayPath(s.absFilename(), 20);
3411 // Here we probably should run
3412 if (LyXVC::file_not_found_hook(s)) {
3413 docstring const text =
3414 bformat(_("Do you want to retrieve the document"
3415 " %1$s from version control?"), file);
3416 int const ret = Alert::prompt(_("Retrieve from version control?"),
3417 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3420 // How can we know _how_ to do the checkout?
3421 // With the current VC support it has to be,
3422 // a RCS file since CVS do not have special ,v files.
3424 return loadLyXFile(s);
3432 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3434 TeXErrors::Errors::const_iterator cit = terr.begin();
3435 TeXErrors::Errors::const_iterator end = terr.end();
3437 for (; cit != end; ++cit) {
3440 int errorRow = cit->error_in_line;
3441 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3447 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3448 } while (found && id_start == id_end && pos_start == pos_end);
3450 errorList.push_back(ErrorItem(cit->error_desc,
3451 cit->error_text, id_start, pos_start, pos_end));
3456 void Buffer::setBuffersForInsets() const
3458 inset().setBuffer(const_cast<Buffer &>(*this));
3462 void Buffer::updateLabels(UpdateScope scope, bool out) const
3464 // Use the master text class also for child documents
3465 Buffer const * const master = masterBuffer();
3466 DocumentClass const & textclass = master->params().documentClass();
3468 // keep the buffers to be children in this set. If the call from the
3469 // master comes back we can see which of them were actually seen (i.e.
3470 // via an InsetInclude). The remaining ones in the set need still be updated.
3471 static std::set<Buffer const *> bufToUpdate;
3472 if (scope == UpdateMaster) {
3473 // If this is a child document start with the master
3474 if (master != this) {
3475 bufToUpdate.insert(this);
3476 master->updateLabels(UpdateMaster, out);
3477 // Do this here in case the master has no gui associated with it. Then,
3478 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3482 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3483 if (bufToUpdate.find(this) == bufToUpdate.end())
3487 // start over the counters in the master
3488 textclass.counters().reset();
3491 // update will be done below for this buffer
3492 bufToUpdate.erase(this);
3494 // update all caches
3495 clearReferenceCache();
3498 Buffer & cbuf = const_cast<Buffer &>(*this);
3500 LASSERT(!text().paragraphs().empty(), /**/);
3503 ParIterator parit = cbuf.par_iterator_begin();
3504 updateLabels(parit, out);
3507 // TocBackend update will be done later.
3510 cbuf.tocBackend().update();
3511 if (scope == UpdateMaster)
3512 cbuf.structureChanged();
3516 static depth_type getDepth(DocIterator const & it)
3518 depth_type depth = 0;
3519 for (size_t i = 0 ; i < it.depth() ; ++i)
3520 if (!it[i].inset().inMathed())
3521 depth += it[i].paragraph().getDepth() + 1;
3522 // remove 1 since the outer inset does not count
3526 static depth_type getItemDepth(ParIterator const & it)
3528 Paragraph const & par = *it;
3529 LabelType const labeltype = par.layout().labeltype;
3531 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3534 // this will hold the lowest depth encountered up to now.
3535 depth_type min_depth = getDepth(it);
3536 ParIterator prev_it = it;
3539 --prev_it.top().pit();
3541 // start of nested inset: go to outer par
3543 if (prev_it.empty()) {
3544 // start of document: nothing to do
3549 // We search for the first paragraph with same label
3550 // that is not more deeply nested.
3551 Paragraph & prev_par = *prev_it;
3552 depth_type const prev_depth = getDepth(prev_it);
3553 if (labeltype == prev_par.layout().labeltype) {
3554 if (prev_depth < min_depth)
3555 return prev_par.itemdepth + 1;
3556 if (prev_depth == min_depth)
3557 return prev_par.itemdepth;
3559 min_depth = min(min_depth, prev_depth);
3560 // small optimization: if we are at depth 0, we won't
3561 // find anything else
3562 if (prev_depth == 0)
3568 static bool needEnumCounterReset(ParIterator const & it)
3570 Paragraph const & par = *it;
3571 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3572 depth_type const cur_depth = par.getDepth();
3573 ParIterator prev_it = it;
3574 while (prev_it.pit()) {
3575 --prev_it.top().pit();
3576 Paragraph const & prev_par = *prev_it;
3577 if (prev_par.getDepth() <= cur_depth)
3578 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3580 // start of nested inset: reset
3585 // set the label of a paragraph. This includes the counters.
3586 void Buffer::setLabel(ParIterator & it) const
3588 BufferParams const & bp = this->masterBuffer()->params();
3589 DocumentClass const & textclass = bp.documentClass();
3590 Paragraph & par = it.paragraph();
3591 Layout const & layout = par.layout();
3592 Counters & counters = textclass.counters();
3594 if (par.params().startOfAppendix()) {
3595 // FIXME: only the counter corresponding to toplevel
3596 // sectioning should be reset
3598 counters.appendix(true);
3600 par.params().appendix(counters.appendix());
3602 // Compute the item depth of the paragraph
3603 par.itemdepth = getItemDepth(it);
3605 if (layout.margintype == MARGIN_MANUAL
3606 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3607 if (par.params().labelWidthString().empty())
3608 par.params().labelWidthString(par.expandLabel(layout, bp));
3610 par.params().labelWidthString(docstring());
3613 switch(layout.labeltype) {
3615 if (layout.toclevel <= bp.secnumdepth
3616 && (layout.latextype != LATEX_ENVIRONMENT
3617 || it.text()->isFirstInSequence(it.pit()))) {
3618 counters.step(layout.counter);
3619 par.params().labelString(
3620 par.expandLabel(layout, bp));
3622 par.params().labelString(docstring());
3625 case LABEL_ITEMIZE: {
3626 // At some point of time we should do something more
3627 // clever here, like:
3628 // par.params().labelString(
3629 // bp.user_defined_bullet(par.itemdepth).getText());
3630 // for now, use a simple hardcoded label
3631 docstring itemlabel;
3632 switch (par.itemdepth) {
3634 itemlabel = char_type(0x2022);
3637 itemlabel = char_type(0x2013);
3640 itemlabel = char_type(0x2217);
3643 itemlabel = char_type(0x2219); // or 0x00b7
3646 par.params().labelString(itemlabel);
3650 case LABEL_ENUMERATE: {
3651 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3653 switch (par.itemdepth) {
3662 enumcounter += "iv";
3665 // not a valid enumdepth...
3669 // Maybe we have to reset the enumeration counter.
3670 if (needEnumCounterReset(it))
3671 counters.reset(enumcounter);
3672 counters.step(enumcounter);
3674 string const & lang = par.getParLanguage(bp)->code();
3675 par.params().labelString(counters.theCounter(enumcounter, lang));
3680 case LABEL_SENSITIVE: {
3681 string const & type = counters.current_float();
3682 docstring full_label;
3684 full_label = this->B_("Senseless!!! ");
3686 docstring name = this->B_(textclass.floats().getType(type).name());
3687 if (counters.hasCounter(from_utf8(type))) {
3688 string const & lang = par.getParLanguage(bp)->code();
3689 counters.step(from_utf8(type));
3690 full_label = bformat(from_ascii("%1$s %2$s:"),
3692 counters.theCounter(from_utf8(type), lang));
3694 full_label = bformat(from_ascii("%1$s #:"), name);
3696 par.params().labelString(full_label);
3700 case LABEL_NO_LABEL:
3701 par.params().labelString(docstring());
3705 case LABEL_TOP_ENVIRONMENT:
3706 case LABEL_CENTERED_TOP_ENVIRONMENT:
3709 par.params().labelString(par.expandLabel(layout, bp));
3715 void Buffer::updateLabels(ParIterator & parit, bool out) const
3717 LASSERT(parit.pit() == 0, /**/);
3719 // set the position of the text in the buffer to be able
3720 // to resolve macros in it. This has nothing to do with
3721 // labels, but by putting it here we avoid implementing
3722 // a whole bunch of traversal routines just for this call.
3723 parit.text()->setMacrocontextPosition(parit);
3725 depth_type maxdepth = 0;
3726 pit_type const lastpit = parit.lastpit();
3727 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3728 // reduce depth if necessary
3729 parit->params().depth(min(parit->params().depth(), maxdepth));
3730 maxdepth = parit->getMaxDepthAfter();
3732 // set the counter for this paragraph
3736 InsetList::const_iterator iit = parit->insetList().begin();
3737 InsetList::const_iterator end = parit->insetList().end();
3738 for (; iit != end; ++iit) {
3739 parit.pos() = iit->pos;
3740 iit->inset->updateLabels(parit, out);
3746 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3747 WordLangTuple & word_lang, docstring_list & suggestions) const
3751 suggestions.clear();
3752 word_lang = WordLangTuple();
3753 // OK, we start from here.
3754 DocIterator const end = doc_iterator_end(this);
3755 for (; from != end; from.forwardPos()) {
3756 // We are only interested in text so remove the math CursorSlice.
3757 while (from.inMathed()) {
3761 // If from is at the end of the document (which is possible
3762 // when leaving the mathed) LyX will crash later.
3766 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3771 // Do not increase progress when from == to, otherwise the word
3772 // count will be wrong.
3782 bool Buffer::reload()
3785 // e.g., read-only status could have changed due to version control
3786 d->filename.refresh();
3787 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3789 bool const success = loadLyXFile(d->filename);
3794 message(bformat(_("Document %1$s reloaded."), disp_fn));
3796 message(bformat(_("Could not reload document %1$s."), disp_fn));