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"
17 #include "insets/InsetCode.h"
19 #include "support/strfwd.h"
20 #include "support/types.h"
53 class ParConstIterator;
63 class GuiBufferDelegate;
64 class WorkAreaManager;
74 typedef std::list<Buffer *> ListOfBuffers;
77 /** The buffer object.
78 * This is the buffer object. It contains all the informations about
79 * a document loaded into LyX.
80 * The buffer object owns the Text (wrapped in an InsetText), which
81 * contains the individual paragraphs of the document.
84 * I am not sure if the class is complete or
85 * minimal, probably not.
86 * \author Lars Gullik Bjønnes
90 /// What type of log will \c getLogName() return?
92 latexlog, ///< LaTeX log
93 buildlog ///< Literate build log
96 /// Result of \c readFile()
106 ReadEmergencyFailure,
119 /// Method to check if a file is externally modified, used by
120 /// isExternallyModified()
122 * timestamp is fast but inaccurate. For example, the granularity
123 * of timestamp on a FAT filesystem is 2 second. Also, various operations
124 * may touch the timestamp of a file even when its content is unchanged.
126 * checksum is accurate but slow, which can be a problem when it is
127 * frequently used, or used for a large file on a slow (network) file
130 * FIXME: replace this method with support/FileMonitor.
133 checksum_method, ///< Use file checksum
134 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
144 explicit Buffer(std::string const & file, bool readonly = false,
145 Buffer const * cloned_buffer = 0);
151 Buffer * clone() const;
153 bool isClone() const;
155 /** High-level interface to buffer functionality.
156 This function parses a command string and executes it.
158 void dispatch(std::string const & command, DispatchResult & result);
160 /// Maybe we know the function already by number...
161 void dispatch(FuncRequest const & func, DispatchResult & result);
163 /// Can this function be exectued?
164 /// \return true if we made a decision
165 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
168 DocIterator getParFromID(int id) const;
169 /// do we have a paragraph with this id?
170 bool hasParWithID(int id) const;
173 frontend::WorkAreaManager & workAreaManager() const;
176 Takes care of auto-save files and backup file if requested.
177 Returns \c true if the save is successful, \c false otherwise.
181 /// Write document to stream. Returns \c false if unsuccesful.
182 bool write(std::ostream &) const;
183 /// Write file. Returns \c false if unsuccesful.
184 bool writeFile(support::FileName const &) const;
186 /// \name Functions involved in reading files/strings.
188 /// Loads the LyX file into the buffer. This function
189 /// tries to extract the file from version control if it
190 /// cannot be found. If it can be found, it will try to
191 /// read an emergency save file or an autosave file.
192 /// \sa loadThisLyXFile
193 ReadStatus loadLyXFile();
194 /// Loads the LyX file \c fn into the buffer. If you want
195 /// to check for files in a version control container,
196 /// emergency or autosave files, one should use \c loadLyXFile.
198 ReadStatus loadThisLyXFile(support::FileName const & fn);
199 /// read a new document from a string
200 bool readString(std::string const &);
201 /// Reloads the LyX file
203 //FIXME: The following two functions should be private
205 /// read the header, returns number of unknown tokens
206 int readHeader(Lexer & lex);
207 /// save timestamp and checksum of the given file.
208 void saveCheckSum() const;
212 ReadStatus readFile(support::FileName const & fn);
213 /// Reads a file without header.
214 /// \param par if != 0 insert the file.
215 /// \return \c true if file is not completely read.
216 bool readDocument(Lexer &);
217 /// Try to extract the file from a version control container
218 /// before reading if the file cannot be found. This is only
219 /// implemented for RCS.
220 /// \sa LyXVC::file_not_found_hook
221 ReadStatus extractFromVC();
222 /// Reads the first tag of a LyX File and
223 /// returns the file format number.
224 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
225 int & file_format) const;
226 /// Convert the LyX file to the LYX_FORMAT using
227 /// the lyx2lyx script and returns the filename
228 /// of the temporary file to be read
229 ReadStatus convertLyXFormat(support::FileName const & fn,
230 support::FileName & tmpfile, int from_format);
234 /// \name Functions involved in autosave and emergency files.
237 void autoSave() const;
238 /// save emergency file
239 /// \return a status message towards the user.
240 docstring emergencyWrite();
242 //FIXME:The following three functions should be private
245 void removeAutosaveFile() const;
247 void moveAutosaveFile(support::FileName const & old) const;
248 /// Get the filename of the autosave file associated with the Buffer
249 support::FileName getAutosaveFileName() const;
252 /// Try to load an autosave file associated to \c fn.
253 ReadStatus loadAutosave();
254 /// Try to load an emergency file associated to \c fn.
255 ReadStatus loadEmergency();
256 /// Get the filename of the emergency file associated with the Buffer
257 support::FileName getEmergencyFileName() const;
261 /// Fill in the ErrorList with the TeXErrors
262 void bufferErrors(TeXErrors const &, ErrorList &) const;
264 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
265 bool makeLaTeXFile(support::FileName const & filename,
266 std::string const & original_path,
267 OutputParams const &,
268 bool output_preamble = true,
269 bool output_body = true) const;
270 /** Export the buffer to LaTeX.
271 If \p os is a file stream, and params().inputenc is "auto" or
272 "default", and the buffer contains text in different languages
273 with more than one encoding, then this method will change the
274 encoding associated to \p os. Therefore you must not call this
275 method with a string stream if the output is supposed to go to a
278 ofs.open("test.tex");
279 writeLaTeXSource(ofs, ...);
281 \endcode is NOT equivalent to \code
282 odocstringstream oss;
283 writeLaTeXSource(oss, ...);
285 ofs.open("test.tex");
290 void writeLaTeXSource(odocstream & os,
291 std::string const & original_path,
292 OutputParams const &,
293 bool output_preamble = true,
294 bool output_body = true) const;
296 void makeDocBookFile(support::FileName const & filename,
297 OutputParams const & runparams_in,
298 bool only_body = false) const;
300 void writeDocBookSource(odocstream & os, std::string const & filename,
301 OutputParams const & runparams_in,
302 bool only_body = false) const;
304 void makeLyXHTMLFile(support::FileName const & filename,
305 OutputParams const & runparams_in,
306 bool only_body = false) const;
308 void writeLyXHTMLSource(odocstream & os,
309 OutputParams const & runparams_in,
310 bool only_body = false) const;
311 /// returns the main language for the buffer (document)
312 Language const * language() const;
313 /// get l10n translated to the buffers language
314 docstring const B_(std::string const & l10n) const;
318 /// return true if the main lyx file does not need saving
319 bool isClean() const;
321 bool isDepClean(std::string const & name) const;
323 /// whether or not disk file has been externally modified
324 bool isExternallyModified(CheckMethod method) const;
326 /// mark the main lyx file as not needing saving
327 void markClean() const;
330 void markDepClean(std::string const & name);
333 void setUnnamed(bool flag = true);
335 /// Whether or not a filename has been assigned to this buffer
336 bool isUnnamed() const;
338 /// Whether or not this buffer is internal.
340 /// An internal buffer does not contain a real document, but some auxiliary text segment.
341 /// It is not associated with a filename, it is never saved, thus it does not need to be
342 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
343 bool isInternal() const;
345 /// Mark this buffer as dirty.
348 /// Returns the buffer's filename. It is always an absolute path.
349 support::FileName fileName() const;
351 /// Returns the buffer's filename. It is always an absolute path.
352 std::string absFileName() const;
354 /// Returns the the path where the buffer lives.
355 /// It is always an absolute path.
356 std::string filePath() const;
358 /** A transformed version of the file name, adequate for LaTeX.
359 \param no_path optional if \c true then the path is stripped.
361 std::string latexName(bool no_path = true) const;
363 /// Get the name and type of the log.
364 std::string logName(LogType * type = 0) const;
366 /// Change name of buffer. Updates "read-only" flag.
367 void setFileName(std::string const & newfile);
369 /// Set document's parent Buffer.
370 void setParent(Buffer const *);
371 Buffer const * parent() const;
373 /** Get the document's master (or \c this if this is not a
376 Buffer const * masterBuffer() const;
378 /// \return true if \p child is a child of this \c Buffer.
379 bool isChild(Buffer * child) const;
381 /// \return true if this \c Buffer has children
382 bool hasChildren() const;
384 /// \return a list of the direct children of this Buffer.
385 /// this list has no duplicates and is in the order in which
386 /// the children appear.
387 ListOfBuffers getChildren() const;
389 /// \return a list of all descendents of this Buffer (children,
390 /// grandchildren, etc). this list has no duplicates and is in
391 /// the order in which the children appear.
392 ListOfBuffers getDescendents() const;
394 /// Collect all relative buffers, in the order in which they appear.
395 /// I.e., the "root" Buffer is first, then its first child, then any
396 /// of its children, etc. However, there are no duplicates in this
398 /// This is "stable", too, in the sense that it returns the same
399 /// thing from whichever Buffer it is called.
400 ListOfBuffers allRelatives() const;
402 /// Is buffer read-only?
403 bool isReadonly() const;
405 /// Set buffer read-only flag
406 void setReadonly(bool flag = true);
408 /// returns \c true if the buffer contains a LaTeX document
409 bool isLatex() const;
410 /// returns \c true if the buffer contains a DocBook document
411 bool isDocBook() const;
412 /// returns \c true if the buffer contains a Wed document
413 bool isLiterate() const;
415 /** Validate a buffer for LaTeX.
416 This validates the buffer, and returns a struct for use by
417 #makeLaTeX# and others. Its main use is to figure out what
418 commands and packages need to be included in the LaTeX file.
419 It (should) also check that the needed constructs are there
420 (i.e. that the \refs points to coresponding \labels). It
421 should perhaps inset "error" insets to help the user correct
424 void validate(LaTeXFeatures &) const;
426 /// Reference information is cached in the Buffer, so we do not
427 /// have to check or read things over and over.
429 /// There are two caches.
431 /// One is a cache of the BibTeX files from which reference info is
432 /// being gathered. This cache is PER BUFFER, and the cache for the
433 /// master essentially includes the cache for its children. This gets
434 /// invalidated when an InsetBibtex is created, deleted, or modified.
436 /// The other is a cache of the reference information itself. This
437 /// exists only in the master buffer, and when it needs to be updated,
438 /// the children add their information to the master's cache.
440 /// Calling this method invalidates the cache and so requires a
442 void invalidateBibinfoCache() const;
443 /// This invalidates the cache of files we need to check.
444 void invalidateBibfileCache() const;
445 /// Updates the cached bibliography information.
446 /// Note that you MUST call this method to update the cache. It will
447 /// not happen otherwise. (Currently, it is called at the start of
448 /// updateBuffer() and from GuiCitation.)
449 /// Note that this operates on the master document.
450 void checkBibInfoCache() const;
451 /// \return the bibliography information for this buffer's master,
452 /// or just for it, if it isn't a child.
453 BiblioInfo const & masterBibInfo() const;
455 void fillWithBibKeys(BiblioInfo & keys) const;
457 void getLabelList(std::vector<docstring> &) const;
460 void changeLanguage(Language const * from, Language const * to);
463 bool isMultiLingual() const;
465 std::set<Language const *> getLanguages() const;
468 BufferParams & params();
469 BufferParams const & params() const;
471 /** The list of paragraphs.
472 This is a linked list of paragraph, this list holds the
473 whole contents of the document.
475 ParagraphList & paragraphs();
476 ParagraphList const & paragraphs() const;
478 /// LyX version control object.
480 LyXVC const & lyxvc() const;
482 /// Where to put temporary files.
483 std::string const temppath() const;
485 /// Used when typesetting to place errorboxes.
486 TexRow const & texrow() const;
490 ParIterator par_iterator_begin();
492 ParConstIterator par_iterator_begin() const;
494 ParIterator par_iterator_end();
496 ParConstIterator par_iterator_end() const;
498 // Position of the child buffer where it appears first in the master.
499 DocIterator firstChildPosition(Buffer const * child);
501 /** \returns true only when the file is fully loaded.
502 * Used to prevent the premature generation of previews
503 * and by the citation inset.
505 bool isFullyLoaded() const;
506 /// Set by buffer_funcs' newFile.
507 void setFullyLoaded(bool);
509 /// Update the LaTeX preview snippets associated with this buffer
510 void updatePreviews() const;
511 /// Remove any previewed LaTeX snippets associated with this buffer
512 void removePreviews() const;
514 /// Our main text (inside the top InsetText)
517 /// Our top InsetText
518 Inset & inset() const;
523 /// Collect macro definitions in paragraphs
524 void updateMacros() const;
525 /// Iterate through the whole buffer and try to resolve macros
526 void updateMacroInstances() const;
528 /// List macro names of this buffer, the parent and the children
529 void listMacroNames(MacroNameSet & macros) const;
530 /// Collect macros of the parent and its children in front of this buffer.
531 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
533 /// Return macro defined before pos (or in the master buffer)
534 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
535 /// Return macro defined anywhere in the buffer (or in the master buffer)
536 MacroData const * getMacro(docstring const & name, bool global = true) const;
537 /// Return macro defined before the inclusion of the child
538 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
540 /// Collect user macro names at loading time
541 typedef std::set<docstring> UserMacroSet;
542 UserMacroSet usermacros;
544 /// Replace the inset contents for insets which InsetCode is equal
545 /// to the passed \p inset_code.
546 void changeRefsIfUnique(docstring const & from, docstring const & to,
549 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
550 /// including preamble
551 void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
552 bool full_source) const;
554 /// Access to error list.
555 /// This method is used only for GUI visualisation of Buffer related
556 /// errors (like parsing or LateX compilation). This method is const
557 /// because modifying the returned ErrorList does not touch the document
559 ErrorList & errorList(std::string const & type) const;
562 /// This is useful only for screen visualisation of the Buffer. This
563 /// method is const because modifying this backend does not touch
564 /// the document contents.
565 TocBackend & tocBackend() const;
570 /// This function is called when the buffer is changed.
571 void changed(bool update_metrics) const;
573 void setChild(DocIterator const & dit, Buffer * child);
575 void updateTocItem(std::string const &, DocIterator const &) const;
576 /// This function is called when the buffer structure is changed.
577 void structureChanged() const;
578 /// This function is called when some parsing error shows up.
579 void errors(std::string const & err, bool from_master = false) const;
580 /// This function is called when the buffer busy status change.
581 void setBusy(bool on) const;
582 /// Update window titles of all users.
583 void updateTitles() const;
584 /// Reset autosave timers for all users.
585 void resetAutosaveTimers() const;
587 void message(docstring const & msg) const;
590 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
592 bool hasGuiDelegate() const;
596 /// return the format of the buffer on a string
597 std::string bufferFormat() const;
598 /// return the default output format of the current backend
599 std::string getDefaultOutputFormat() const;
602 bool doExport(std::string const & format, bool put_in_tempdir,
603 bool includeall, std::string & result_file) const;
605 bool doExport(std::string const & format, bool put_in_tempdir,
606 bool includeall = false) const;
608 bool preview(std::string const & format, bool includeall = false) const;
610 bool isExportable(std::string const & format) const;
612 std::vector<Format const *> exportableFormats(bool only_viewable) const;
614 bool isExportableFormat(std::string const & format) const;
615 /// mark the buffer as busy exporting something, or not
616 void setExportStatus(bool e) const;
618 bool isExporting() const;
621 typedef std::vector<std::pair<Inset *, ParIterator> > References;
622 References & references(docstring const & label);
623 References const & references(docstring const & label) const;
624 void clearReferenceCache() const;
625 void setInsetLabel(docstring const & label, InsetLabel const * il);
626 InsetLabel const * insetLabel(docstring const & label) const;
628 /// return a list of all used branches (also in children)
629 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
631 /// sets the buffer_ member for every inset in this buffer.
632 // FIXME This really shouldn't be needed, but at the moment it's not
633 // clear how to do it just for the individual pieces we need.
634 void setBuffersForInsets() const;
635 /// Updates screen labels and some other information associated with
636 /// insets and paragraphs. Actually, it's more like a general "recurse
637 /// through the Buffer" routine, that visits all the insets and paragraphs.
638 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
639 /// \param scope: whether to start with the master document or just
641 /// \param output: whether we are preparing for output.
642 void updateBuffer(UpdateScope scope, UpdateType utype) const;
644 void updateBuffer(ParIterator & parit, UpdateType utype) const;
646 /// Spellcheck starting from \p from.
647 /// \p from initial position, will then points to the next misspelled
649 /// \p to will points to the end of the next misspelled word.
650 /// \p word_lang will contain the found misspelled word.
651 /// \return progress if a new word was found.
652 int spellCheck(DocIterator & from, DocIterator & to,
653 WordLangTuple & word_lang, docstring_list & suggestions) const;
655 void checkChildBuffers();
659 std::vector<std::string> backends() const;
661 void getLanguages(std::set<Language const *> &) const;
662 /// Update the list of all bibfiles in use (including bibfiles
663 /// of loaded child documents).
664 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
665 /// Return the list with all bibfiles in use (including bibfiles
666 /// of loaded child documents).
667 support::FileNameList const &
668 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
670 void collectChildren(ListOfBuffers & children, bool grand_children) const;
673 /// Use the Pimpl idiom to hide the internals.
675 /// The pointer never changes although *pimpl_'s contents may.