4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
18 #include "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
81 typedef std::list<Buffer *> ListOfBuffers;
84 /** The buffer object.
85 * This is the buffer object. It contains all the informations about
86 * a document loaded into LyX.
87 * The buffer object owns the Text (wrapped in an InsetText), which
88 * contains the individual paragraphs of the document.
91 * I am not sure if the class is complete or
92 * minimal, probably not.
93 * \author Lars Gullik Bjønnes
97 /// What type of log will \c getLogName() return?
99 latexlog, ///< LaTeX log
100 buildlog ///< Literate build log
103 /// Result of \c readFile()
113 ReadEmergencyFailure,
129 ExportNoPathToFormat,
130 ExportTexPathHasSpaces,
131 ExportConverterError,
137 /// Method to check if a file is externally modified, used by
138 /// isExternallyModified()
140 * timestamp is fast but inaccurate. For example, the granularity
141 * of timestamp on a FAT filesystem is 2 second. Also, various operations
142 * may touch the timestamp of a file even when its content is unchanged.
144 * checksum is accurate but slow, which can be a problem when it is
145 * frequently used, or used for a large file on a slow (network) file
148 * FIXME: replace this method with support/FileMonitor.
151 checksum_method, ///< Use file checksum
152 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
162 explicit Buffer(std::string const & file, bool readonly = false,
163 Buffer const * cloned_buffer = 0);
169 Buffer * clone() const;
171 bool isClone() const;
173 /** High-level interface to buffer functionality.
174 This function parses a command string and executes it.
176 void dispatch(std::string const & command, DispatchResult & result);
178 /// Maybe we know the function already by number...
179 void dispatch(FuncRequest const & func, DispatchResult & result);
181 /// Can this function be exectued?
182 /// \return true if we made a decision
183 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
186 DocIterator getParFromID(int id) const;
187 /// do we have a paragraph with this id?
188 bool hasParWithID(int id) const;
191 frontend::WorkAreaManager & workAreaManager() const;
194 Takes care of auto-save files and backup file if requested.
195 Returns \c true if the save is successful, \c false otherwise.
198 /// Renames and saves the buffer
199 bool saveAs(support::FileName const & fn);
201 /// Write document to stream. Returns \c false if unsuccessful.
202 bool write(std::ostream &) const;
203 /// Write file. Returns \c false if unsuccessful.
204 bool writeFile(support::FileName const &) const;
206 /// \name Functions involved in reading files/strings.
208 /// Loads the LyX file into the buffer. This function
209 /// tries to extract the file from version control if it
210 /// cannot be found. If it can be found, it will try to
211 /// read an emergency save file or an autosave file.
212 /// \sa loadThisLyXFile
213 ReadStatus loadLyXFile();
214 /// Loads the LyX file \c fn into the buffer. If you want
215 /// to check for files in a version control container,
216 /// emergency or autosave files, one should use \c loadLyXFile.
218 ReadStatus loadThisLyXFile(support::FileName const & fn);
219 /// read a new document from a string
220 bool readString(std::string const &);
221 /// Reloads the LyX file
223 //FIXME: The following function should be private
225 /// read the header, returns number of unknown tokens
226 int readHeader(Lexer & lex);
230 typedef std::map<Buffer const *, Buffer *> BufferMap;
232 void clone(BufferMap &) const;
233 /// save timestamp and checksum of the given file.
234 void saveCheckSum() const;
236 ReadStatus readFile(support::FileName const & fn);
237 /// Reads a file without header.
238 /// \param par if != 0 insert the file.
239 /// \return \c true if file is not completely read.
240 bool readDocument(Lexer &);
241 /// Try to extract the file from a version control container
242 /// before reading if the file cannot be found. This is only
243 /// implemented for RCS.
244 /// \sa LyXVC::file_not_found_hook
245 ReadStatus extractFromVC();
246 /// Reads the first tag of a LyX File and
247 /// returns the file format number.
248 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
249 int & file_format) const;
250 /// Convert the LyX file to the LYX_FORMAT using
251 /// the lyx2lyx script and returns the filename
252 /// of the temporary file to be read
253 ReadStatus convertLyXFormat(support::FileName const & fn,
254 support::FileName & tmpfile, int from_format);
258 /// \name Functions involved in autosave and emergency files.
260 /// Save an autosave file to #filename.lyx#
261 bool autoSave() const;
262 /// save emergency file
263 /// \return a status message towards the user.
264 docstring emergencyWrite();
266 //FIXME:The following function should be private
269 void removeAutosaveFile() const;
272 /// Try to load an autosave file associated to \c fn.
273 ReadStatus loadAutosave();
274 /// Try to load an emergency file associated to \c fn.
275 ReadStatus loadEmergency();
276 /// Get the filename of the emergency file associated with the Buffer
277 support::FileName getEmergencyFileName() const;
278 /// Get the filename of the autosave file associated with the Buffer
279 support::FileName getAutosaveFileName() const;
281 void moveAutosaveFile(support::FileName const & old) const;
285 /// Fill in the ErrorList with the TeXErrors
286 void bufferErrors(TeXErrors const &, ErrorList &) const;
288 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
289 bool makeLaTeXFile(support::FileName const & filename,
290 std::string const & original_path,
291 OutputParams const &,
292 bool output_preamble = true,
293 bool output_body = true) const;
294 /** Export the buffer to LaTeX.
295 If \p os is a file stream, and params().inputenc is "auto" or
296 "default", and the buffer contains text in different languages
297 with more than one encoding, then this method will change the
298 encoding associated to \p os. Therefore you must not call this
299 method with a string stream if the output is supposed to go to a
302 otexstream os(ofs, texrow);
303 ofs.open("test.tex");
304 writeLaTeXSource(os, ...);
306 \endcode is NOT equivalent to \code
307 odocstringstream oss;
308 otexstream os(oss, texrow);
309 writeLaTeXSource(os, ...);
311 ofs.open("test.tex");
316 void writeLaTeXSource(otexstream & os,
317 std::string const & original_path,
318 OutputParams const &,
319 bool output_preamble = true,
320 bool output_body = true) const;
322 void makeDocBookFile(support::FileName const & filename,
323 OutputParams const & runparams_in,
324 bool only_body = false) const;
326 void writeDocBookSource(odocstream & os, std::string const & filename,
327 OutputParams const & runparams_in,
328 bool only_body = false) const;
330 void makeLyXHTMLFile(support::FileName const & filename,
331 OutputParams const & runparams_in) const;
333 void writeLyXHTMLSource(odocstream & os,
334 OutputParams const & runparams_in,
335 bool only_body = false) const;
336 /// returns the main language for the buffer (document)
337 Language const * language() const;
338 /// get l10n translated to the buffers language
339 docstring const B_(std::string const & l10n) const;
343 /// return true if the main lyx file does not need saving
344 bool isClean() const;
346 bool isDepClean(std::string const & name) const;
348 /// whether or not disk file has been externally modified
349 bool isExternallyModified(CheckMethod method) const;
351 /// mark the main lyx file as not needing saving
352 void markClean() const;
355 void markDepClean(std::string const & name);
358 void setUnnamed(bool flag = true);
360 /// Whether or not a filename has been assigned to this buffer
361 bool isUnnamed() const;
363 /// Whether or not this buffer is internal.
365 /// An internal buffer does not contain a real document, but some auxiliary text segment.
366 /// It is not associated with a filename, it is never saved, thus it does not need to be
367 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
368 bool isInternal() const;
370 /// Mark this buffer as dirty.
373 /// Returns the buffer's filename. It is always an absolute path.
374 support::FileName fileName() const;
376 /// Returns the buffer's filename. It is always an absolute path.
377 std::string absFileName() const;
379 /// Returns the the path where the buffer lives.
380 /// It is always an absolute path.
381 std::string filePath() const;
383 /** A transformed version of the file name, adequate for LaTeX.
384 \param no_path optional if \c true then the path is stripped.
386 std::string latexName(bool no_path = true) const;
388 /// Get the name and type of the log.
389 std::string logName(LogType * type = 0) const;
391 /// Set document's parent Buffer.
392 void setParent(Buffer const *);
393 Buffer const * parent() const;
395 /** Get the document's master (or \c this if this is not a
398 Buffer const * masterBuffer() const;
400 /// \return true if \p child is a child of this \c Buffer.
401 bool isChild(Buffer * child) const;
403 /// \return true if this \c Buffer has children
404 bool hasChildren() const;
406 /// \return a list of the direct children of this Buffer.
407 /// this list has no duplicates and is in the order in which
408 /// the children appear.
409 ListOfBuffers getChildren() const;
411 /// \return a list of all descendents of this Buffer (children,
412 /// grandchildren, etc). this list has no duplicates and is in
413 /// the order in which the children appear.
414 ListOfBuffers getDescendents() const;
416 /// Collect all relative buffers, in the order in which they appear.
417 /// I.e., the "root" Buffer is first, then its first child, then any
418 /// of its children, etc. However, there are no duplicates in this
420 /// This is "stable", too, in the sense that it returns the same
421 /// thing from whichever Buffer it is called.
422 ListOfBuffers allRelatives() const;
424 /// Is buffer read-only?
425 bool isReadonly() const;
427 /// Set buffer read-only flag
428 void setReadonly(bool flag = true);
430 /** Validate a buffer for LaTeX.
431 This validates the buffer, and returns a struct for use by
432 #makeLaTeX# and others. Its main use is to figure out what
433 commands and packages need to be included in the LaTeX file.
434 It (should) also check that the needed constructs are there
435 (i.e. that the \refs points to coresponding \labels). It
436 should perhaps inset "error" insets to help the user correct
439 void validate(LaTeXFeatures &) const;
441 /// Reference information is cached in the Buffer, so we do not
442 /// have to check or read things over and over.
444 /// There are two caches.
446 /// One is a cache of the BibTeX files from which reference info is
447 /// being gathered. This cache is PER BUFFER, and the cache for the
448 /// master essentially includes the cache for its children. This gets
449 /// invalidated when an InsetBibtex is created, deleted, or modified.
451 /// The other is a cache of the reference information itself. This
452 /// exists only in the master buffer, and when it needs to be updated,
453 /// the children add their information to the master's cache.
455 /// Calling this method invalidates the cache and so requires a
457 void invalidateBibinfoCache() const;
458 /// This invalidates the cache of files we need to check.
459 void invalidateBibfileCache() const;
460 /// Updates the cached bibliography information, checking first to see
461 /// whether the cache is valid. If so, we do nothing. If not, then we
462 /// reload all the BibTeX info.
463 /// Note that this operates on the master document.
464 void reloadBibInfoCache() const;
465 /// \return the bibliography information for this buffer's master,
466 /// or just for it, if it isn't a child.
467 BiblioInfo const & masterBibInfo() const;
468 /// collect bibliography info from the various insets in this buffer.
469 void collectBibKeys() const;
470 /// add some BiblioInfo to our cache
471 void addBiblioInfo(BiblioInfo const & bi) const;
472 /// add a single piece of bibliography info to our cache
473 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
475 bool citeLabelsValid() const;
477 void getLabelList(std::vector<docstring> &) const;
480 void changeLanguage(Language const * from, Language const * to);
483 bool isMultiLingual() const;
485 std::set<Language const *> getLanguages() const;
488 BufferParams & params();
489 BufferParams const & params() const;
491 /** The list of paragraphs.
492 This is a linked list of paragraph, this list holds the
493 whole contents of the document.
495 ParagraphList & paragraphs();
496 ParagraphList const & paragraphs() const;
498 /// LyX version control object.
500 LyXVC const & lyxvc() const;
502 /// Where to put temporary files.
503 std::string const temppath() const;
505 /// Used when typesetting to place errorboxes.
506 TexRow const & texrow() const;
510 ParIterator par_iterator_begin();
512 ParConstIterator par_iterator_begin() const;
514 ParIterator par_iterator_end();
516 ParConstIterator par_iterator_end() const;
518 // Position of the child buffer where it appears first in the master.
519 DocIterator firstChildPosition(Buffer const * child);
521 /** \returns true only when the file is fully loaded.
522 * Used to prevent the premature generation of previews
523 * and by the citation inset.
525 bool isFullyLoaded() const;
526 /// Set by buffer_funcs' newFile.
527 void setFullyLoaded(bool);
529 /// FIXME: Needed by RenderPreview.
530 graphics::PreviewLoader * loader() const;
531 /// Update the LaTeX preview snippets associated with this buffer
532 void updatePreviews() const;
533 /// Remove any previewed LaTeX snippets associated with this buffer
534 void removePreviews() const;
536 /// Our main text (inside the top InsetText)
539 /// Our top InsetText
540 Inset & inset() const;
545 /// Collect macro definitions in paragraphs
546 void updateMacros() const;
547 /// Iterate through the whole buffer and try to resolve macros
548 void updateMacroInstances(UpdateType) const;
550 /// List macro names of this buffer, the parent and the children
551 void listMacroNames(MacroNameSet & macros) const;
552 /// Collect macros of the parent and its children in front of this buffer.
553 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
555 /// Return macro defined before pos (or in the master buffer)
556 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
557 /// Return macro defined anywhere in the buffer (or in the master buffer)
558 MacroData const * getMacro(docstring const & name, bool global = true) const;
559 /// Return macro defined before the inclusion of the child
560 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
562 /// Collect user macro names at loading time
563 typedef std::set<docstring> UserMacroSet;
564 mutable UserMacroSet usermacros;
566 /// Replace the inset contents for insets which InsetCode is equal
567 /// to the passed \p inset_code.
568 void changeRefsIfUnique(docstring const & from, docstring const & to,
571 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
572 /// including preamble
573 void getSourceCode(odocstream & os, std::string const format,
574 pit_type par_begin, pit_type par_end, bool full_source) const;
576 /// Access to error list.
577 /// This method is used only for GUI visualisation of Buffer related
578 /// errors (like parsing or LateX compilation). This method is const
579 /// because modifying the returned ErrorList does not touch the document
581 ErrorList & errorList(std::string const & type) const;
584 /// This is useful only for screen visualisation of the Buffer. This
585 /// method is const because modifying this backend does not touch
586 /// the document contents.
587 TocBackend & tocBackend() const;
592 /// This function is called when the buffer is changed.
593 void changed(bool update_metrics) const;
595 void setChild(DocIterator const & dit, Buffer * child);
597 void updateTocItem(std::string const &, DocIterator const &) const;
598 /// This function is called when the buffer structure is changed.
599 void structureChanged() const;
600 /// This function is called when some parsing error shows up.
601 void errors(std::string const & err, bool from_master = false) const;
602 /// This function is called when the buffer busy status change.
603 void setBusy(bool on) const;
604 /// Update window titles of all users.
605 void updateTitles() const;
606 /// Reset autosave timers for all users.
607 void resetAutosaveTimers() const;
609 void message(docstring const & msg) const;
612 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
614 bool hasGuiDelegate() const;
617 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
619 ExportStatus preview(std::string const & format) const;
622 /// target is a format name optionally followed by a space
623 /// and a destination file-name
624 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
625 bool includeall, std::string & result_file) const;
627 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
628 bool includeall) const;
630 ExportStatus preview(std::string const & format, bool includeall = false) const;
633 /// mark the buffer as busy exporting something, or not
634 void setExportStatus(bool e) const;
636 bool isExporting() const;
639 typedef std::vector<std::pair<Inset *, ParIterator> > References;
640 References & references(docstring const & label);
641 References const & references(docstring const & label) const;
642 void clearReferenceCache() const;
643 void setInsetLabel(docstring const & label, InsetLabel const * il);
644 InsetLabel const * insetLabel(docstring const & label) const;
646 /// return a list of all used branches (also in children)
647 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
649 /// sets the buffer_ member for every inset in this buffer.
650 // FIXME This really shouldn't be needed, but at the moment it's not
651 // clear how to do it just for the individual pieces we need.
652 void setBuffersForInsets() const;
653 /// Updates screen labels and some other information associated with
654 /// insets and paragraphs. Actually, it's more like a general "recurse
655 /// through the Buffer" routine, that visits all the insets and paragraphs.
656 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
657 /// \param scope: whether to start with the master document or just
659 /// \param output: whether we are preparing for output.
660 void updateBuffer(UpdateScope scope, UpdateType utype) const;
662 void updateBuffer(ParIterator & parit, UpdateType utype) const;
664 /// Spellcheck starting from \p from.
665 /// \p from initial position, will then points to the next misspelled
667 /// \p to will points to the end of the next misspelled word.
668 /// \p word_lang will contain the found misspelled word.
669 /// \return progress if a new word was found.
670 int spellCheck(DocIterator & from, DocIterator & to,
671 WordLangTuple & word_lang, docstring_list & suggestions) const;
673 void checkChildBuffers();
676 /// Change name of buffer. Updates "read-only" flag.
677 void setFileName(support::FileName const & fname);
679 void getLanguages(std::set<Language const *> &) const;
680 /// Checks whether any of the referenced bibfiles have changed since the
681 /// last time we loaded the cache. Note that this does NOT update the
682 /// cached information.
683 void checkIfBibInfoCacheIsValid() const;
684 /// Update the list of all bibfiles in use (including bibfiles
685 /// of loaded child documents).
686 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
687 /// Return the list with all bibfiles in use (including bibfiles
688 /// of loaded child documents).
689 support::FileNameList const &
690 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
692 void collectChildren(ListOfBuffers & children, bool grand_children) const;
695 Buffer(Buffer const &);
696 void operator=(Buffer const &);
698 /// Use the Pimpl idiom to hide the internals.
700 /// The pointer never changes although *pimpl_'s contents may.