]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Embedding: saving inzip name to .lyx file so that embedded files can always be found...
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19
20 #include <set>
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BufferParams;
28 class EmbeddedFileList;
29 class DocIterator;
30 class ErrorItem;
31 class ErrorList;
32 class FuncRequest;
33 class Inset;
34 class Font;
35 class Format;
36 class Lexer;
37 class LyXRC;
38 class Text;
39 class LyXVC;
40 class LaTeXFeatures;
41 class Language;
42 class MacroData;
43 class OutputParams;
44 class Paragraph;
45 class ParConstIterator;
46 class ParIterator;
47 class ParagraphList;
48 class TeXErrors;
49 class TexRow;
50 class TocBackend;
51 class Undo;
52
53 namespace frontend {
54 class GuiBufferDelegate;
55 class WorkAreaManager;
56 }
57
58 namespace support {
59 class FileName;
60 }
61
62 /** The buffer object.
63  * This is the buffer object. It contains all the informations about
64  * a document loaded into LyX.
65  * The buffer object owns the Text (wrapped in an InsetText), which
66  * contains the individual paragraphs of the document.
67  *
68  *
69  * I am not sure if the class is complete or
70  * minimal, probably not.
71  * \author Lars Gullik Bjønnes
72  */
73 class Buffer {
74 public:
75         /// What type of log will \c getLogName() return?
76         enum LogType {
77                 latexlog, ///< LaTeX log
78                 buildlog  ///< Literate build log
79         };
80
81         /// Result of \c readFile()
82         enum ReadStatus {
83                 failure, ///< The file could not be read
84                 success, ///< The file could not be read
85                 wrongversion ///< The version of the file does not match ours
86         };
87
88
89         /// Method to check if a file is externally modified, used by 
90         /// isExternallyModified()
91         /**
92          * timestamp is fast but inaccurate. For example, the granularity
93          * of timestamp on a FAT filesystem is 2 second. Also, various operations
94          * may touch the timestamp of a file even when its content is unchanged.
95          *
96          * checksum is accurate but slow, which can be a problem when it is 
97          * frequently used, or used for a large file on a slow (network) file
98          * system.
99          *
100          * FIXME: replace this method with support/FileMonitor.
101          */
102         enum CheckMethod {
103                 checksum_method,  ///< Use file checksum
104                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
105         };
106         
107         /** Constructor
108             \param file
109             \param b  optional \c false by default
110         */
111         explicit Buffer(std::string const & file, bool b = false);
112
113         /// Destructor
114         ~Buffer();
115
116         /** High-level interface to buffer functionality.
117             This function parses a command string and executes it
118         */
119         bool dispatch(std::string const & command, bool * result = 0);
120
121         /// Maybe we know the function already by number...
122         bool dispatch(FuncRequest const & func, bool * result = 0);
123
124         /// Load the autosaved file.
125         void loadAutoSaveFile();
126
127         /// read a new document from a string
128         bool readString(std::string const &);
129         /// load a new file
130         bool readFile(support::FileName const & filename);
131
132         /// read the header, returns number of unknown tokens
133         int readHeader(Lexer & lex);
134
135         /** Reads a file without header.
136             \param par if != 0 insert the file.
137             \return \c false if file is not completely read.
138         */
139         bool readDocument(Lexer &);
140
141         ///
142         void insertStringAsLines(ParagraphList & plist,
143                 pit_type &, pos_type &,
144                 Font const &, docstring const &, bool);
145         ///
146         ParIterator getParFromID(int id) const;
147         /// do we have a paragraph with this id?
148         bool hasParWithID(int id) const;
149
150         ///
151         frontend::WorkAreaManager & workAreaManager() const;
152
153         /** Save file.
154             Takes care of auto-save files and backup file if requested.
155             Returns \c true if the save is successful, \c false otherwise.
156         */
157         bool save() const;
158
159         /// Write document to stream. Returns \c false if unsuccesful.
160         bool write(std::ostream &) const;
161         /// Write file. Returns \c false if unsuccesful.
162         bool writeFile(support::FileName const &) const;
163
164   /// Loads LyX file \c filename into buffer, *  and \return success 
165         bool loadLyXFile(support::FileName const & s);
166
167         /// Fill in the ErrorList with the TeXErrors
168         void bufferErrors(TeXErrors const &, ErrorList &) const;
169
170         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
171         bool makeLaTeXFile(support::FileName const & filename,
172                            std::string const & original_path,
173                            OutputParams const &,
174                            bool output_preamble = true,
175                            bool output_body = true) const;
176         /** Export the buffer to LaTeX.
177             If \p os is a file stream, and params().inputenc is "auto" or
178             "default", and the buffer contains text in different languages
179             with more than one encoding, then this method will change the
180             encoding associated to \p os. Therefore you must not call this
181             method with a string stream if the output is supposed to go to a
182             file. \code
183             odocfstream ofs;
184             ofs.open("test.tex");
185             writeLaTeXSource(ofs, ...);
186             ofs.close();
187             \endcode is NOT equivalent to \code
188             odocstringstream oss;
189             writeLaTeXSource(oss, ...);
190             odocfstream ofs;
191             ofs.open("test.tex");
192             ofs << oss.str();
193             ofs.close();
194             \endcode
195          */
196         void writeLaTeXSource(odocstream & os,
197                            std::string const & original_path,
198                            OutputParams const &,
199                            bool output_preamble = true,
200                            bool output_body = true) const;
201         ///
202         void makeDocBookFile(support::FileName const & filename,
203                              OutputParams const & runparams_in,
204                              bool only_body = false) const;
205         ///
206         void writeDocBookSource(odocstream & os, std::string const & filename,
207                              OutputParams const & runparams_in,
208                              bool only_body = false) const;
209         /// returns the main language for the buffer (document)
210         Language const * language() const;
211         /// get l10n translated to the buffers language
212         docstring const B_(std::string const & l10n) const;
213
214         ///
215         int runChktex();
216         /// return true if the main lyx file does not need saving
217         bool isClean() const;
218         ///
219         bool isBakClean() const;
220         ///
221         bool isDepClean(std::string const & name) const;
222
223         /// whether or not disk file has been externally modified
224         bool isExternallyModified(CheckMethod method) const;
225
226         /// save timestamp and checksum of the given file.
227         void saveCheckSum(support::FileName const & file) const;
228
229         /// mark the main lyx file as not needing saving
230         void markClean() const;
231
232         ///
233         void markBakClean() const;
234
235         ///
236         void markDepClean(std::string const & name);
237
238         ///
239         void setUnnamed(bool flag = true);
240
241         ///
242         bool isUnnamed() const;
243
244         /// Mark this buffer as dirty.
245         void markDirty();
246
247         /// Returns the buffer's filename. It is always an absolute path.
248         support::FileName fileName() const;
249
250         /// Returns the buffer's filename. It is always an absolute path.
251         std::string absFileName() const;
252
253         /// Returns the the path where the buffer lives.
254         /// It is always an absolute path.
255         std::string filePath() const;
256
257         /** A transformed version of the file name, adequate for LaTeX.
258             \param no_path optional if \c true then the path is stripped.
259         */
260         std::string latexName(bool no_path = true) const;
261
262         /// Get thee name and type of the log.
263         std::string logName(LogType * type = 0) const;
264
265         /// Change name of buffer. Updates "read-only" flag.
266         void setFileName(std::string const & newfile);
267
268         /// Set document's parent Buffer.
269         void setParent(Buffer const *);
270         Buffer const * parent();
271
272         /** Get the document's master (or \c this if this is not a
273             child document)
274          */
275         Buffer const * masterBuffer() const;
276
277         /// Is buffer read-only?
278         bool isReadonly() const;
279
280         /// Set buffer read-only flag
281         void setReadonly(bool flag = true);
282
283         /// returns \c true if the buffer contains a LaTeX document
284         bool isLatex() const;
285         /// returns \c true if the buffer contains a DocBook document
286         bool isDocBook() const;
287         /// returns \c true if the buffer contains a Wed document
288         bool isLiterate() const;
289
290         /** Validate a buffer for LaTeX.
291             This validates the buffer, and returns a struct for use by
292             #makeLaTeX# and others. Its main use is to figure out what
293             commands and packages need to be included in the LaTeX file.
294             It (should) also check that the needed constructs are there
295             (i.e. that the \refs points to coresponding \labels). It
296             should perhaps inset "error" insets to help the user correct
297             obvious mistakes.
298         */
299         void validate(LaTeXFeatures &) const;
300
301         /// Update the cache with all bibfiles in use (including bibfiles
302         /// of loaded child documents).
303         void updateBibfilesCache() const;
304         /// Return the cache with all bibfiles in use (including bibfiles
305         /// of loaded child documents).
306         EmbeddedFileList const & getBibfilesCache() const;
307         ///
308         void getLabelList(std::vector<docstring> &) const;
309
310         ///
311         void changeLanguage(Language const * from, Language const * to);
312
313         ///
314         bool isMultiLingual() const;
315
316         ///
317         BufferParams & params();
318         BufferParams const & params() const;
319
320         /** The list of paragraphs.
321             This is a linked list of paragraph, this list holds the
322             whole contents of the document.
323          */
324         ParagraphList & paragraphs();
325         ParagraphList const & paragraphs() const;
326
327         /// LyX version control object.
328         LyXVC & lyxvc();
329         LyXVC const & lyxvc() const;
330
331         /// Where to put temporary files.
332         std::string const temppath() const;
333
334         /// Used when typesetting to place errorboxes.
335         TexRow const & texrow() const;
336
337         ///
338         ParIterator par_iterator_begin();
339         ///
340         ParConstIterator par_iterator_begin() const;
341         ///
342         ParIterator par_iterator_end();
343         ///
344         ParConstIterator par_iterator_end() const;
345
346         /** \returns true only when the file is fully loaded.
347          *  Used to prevent the premature generation of previews
348          *  and by the citation inset.
349          */
350         bool isFullyLoaded() const;
351         /// Set by buffer_funcs' newFile.
352         void setFullyLoaded(bool);
353
354         /// Our main text (inside the top InsetText)
355         Text & text() const;
356
357         /// Our top InsetText
358         Inset & inset() const;
359
360         //
361         // Macro handling
362         //
363         /// Collect macro definitions in paragraphs
364         void updateMacros() const;
365         /// Iterate through the whole buffer and try to resolve macros
366         void updateMacroInstances() const;
367
368         typedef std::set<docstring> MacroNameSet;
369         /// List macro names of this buffer. the parent and the children
370         void listMacroNames(MacroNameSet & macros) const;
371         /// Write out all macros somewhere defined in the parent,
372         /// its parents and its children, which are visible at the beginning 
373         /// of this buffer
374         void writeParentMacros(odocstream & os) const;
375
376         /// Return macro defined before pos (or in the master buffer)
377         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
378         /// Return macro defined anywhere in the buffer (or in the master buffer)
379         MacroData const * getMacro(docstring const & name, bool global = true) const;
380         /// Return macro defined before the inclusion of the child
381         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
382
383         /// Replace the inset contents for insets which InsetCode is equal
384         /// to the passed \p inset_code.
385         void changeRefsIfUnique(docstring const & from, docstring const & to,
386                 InsetCode code);
387
388         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
389         /// including preamble
390         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
391                 bool full_source);
392
393         /// Access to error list.
394         /// This method is used only for GUI visualisation of Buffer related
395         /// errors (like parsing or LateX compilation). This method is const
396         /// because modifying the returned ErrorList does not touch the document
397         /// contents.
398         ErrorList & errorList(std::string const & type) const;
399
400         /// The Toc backend.
401         /// This is useful only for screen visualisation of the Buffer. This
402         /// method is const because modifying this backend does not touch
403         /// the document contents.
404         TocBackend & tocBackend() const;
405         
406         //@{
407         EmbeddedFileList & embeddedFiles();
408         EmbeddedFileList const & embeddedFiles() const;
409         bool embedded() const;
410         //@}
411
412         Undo & undo();
413        
414         /// This function is called when the buffer is changed.
415         void changed() const;
416         /// This function is called when the buffer structure is changed.
417         void structureChanged() const;
418         /// This function is called when some parsing error shows up.
419         void errors(std::string const & err) const;
420         /// This function is called when the buffer busy status change.
421         void setBusy(bool on) const;
422         /// This function is called when the buffer readonly status change.
423         void setReadOnly(bool on) const;
424         /// Update window titles of all users.
425         void updateTitles() const;
426         /// Reset autosave timers for all users.
427         void resetAutosaveTimers() const;
428         ///
429         void message(docstring const & msg) const;
430
431         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
432
433         ///
434         void autoSave() const;
435         ///
436         void loadChildDocuments() const;
437         ///
438         void resetChildDocuments(bool close_them) const;
439
440         /// return the format of the buffer on a string
441         std::string bufferFormat() const;
442
443         ///
444         bool doExport(std::string const & format, bool put_in_tempdir,
445                 std::string & result_file) const;
446         ///
447         bool doExport(std::string const & format, bool put_in_tempdir) const;
448         ///
449         bool preview(std::string const & format) const;
450         ///
451         bool isExportable(std::string const & format) const;
452         ///
453         std::vector<Format const *> exportableFormats(bool only_viewable) const;
454
455 private:
456         /// search for macro in local (buffer) table or in children
457         MacroData const * getBufferMacro(docstring const & name,
458                                          DocIterator const & pos) const;
459         /** Update macro table in the whole text inset
460             \param it at the start of the text inset)
461         */
462         void updateInsetMacros(DocIterator & it, 
463                                DocIterator & scope) const;
464         /** Update macro table for paragraphs until \c lastpit
465             \param it in some text inset
466             \param lastpit last processed paragraph
467         */
468         void updateEnvironmentMacros(DocIterator & it, 
469                                      pit_type lastpit, 
470                                      DocIterator & scope) const;
471         /** Update macro table for one paragraph block with 
472             same layout and depth, until \c lastpit
473             \param it in some text inset
474             \param lastpit last processed paragraph
475         */
476         void updateBlockMacros(DocIterator & it, 
477                                DocIterator & scope) const;
478
479         /// 
480         bool readFileHelper(support::FileName const & s);
481         ///
482         std::vector<std::string> backends() const;
483         /** Inserts a file into a document
484             \return \c false if method fails.
485         */
486         ReadStatus readFile(Lexer &, support::FileName const & filename,
487                             bool fromString = false);
488
489         /// Use the Pimpl idiom to hide the internals.
490         class Impl;
491         /// The pointer never changes although *pimpl_'s contents may.
492         Impl * const d;
493
494         frontend::GuiBufferDelegate * gui_;
495 };
496
497
498 } // namespace lyx
499
500 #endif