def save_tab(self): """ Attempt to save the active tab, both the text and the scrollbar/cursor position. Return True if it succeeds, return False if it fails. """ if self.revisionactive: return True currenttab = self.tabbar.currentIndex() if self.textarea.document().isModified(): try: fname = join(self.root, self.tabbar.current_page_fname()) firstline, _ = read_file(fname).split('\n', 1) data = self.textarea.toPlainText() write_file(fname, firstline + '\n' + data) except Exception as e: print(str(e)) self.terminal.error('Something went wrong when saving! (Use q! to force)') return False cursorpos = self.textarea.textCursor().position() scrollpos = self.textarea.verticalScrollBar().sliderPosition() self.tabbar.set_page_position(currenttab, cursorpos, scrollpos) self.textarea.document().setModified(False) return True
def start_logging(self, arg): arg = arg.lower().strip() filepath = self.textarea.file_path if not filepath: self.error('Can\'t log an unnamed file! Save and try again (without offset)') return # Paths logdir, indexpath, relative_filepath = self.get_logpaths() index = get_index(indexpath) if not arg: if relative_filepath in index: self.print_('File is being logged.') else: self.print_('File is not being logged.') return if arg not in ('y','n'): self.error('Argument should be y/n! (use offset/no offset)') return if relative_filepath in index: self.error('File already logged!') return # Offsets if arg == 'y': offset = len(re.findall(r'\S+', read_file(self.textarea.file_path))) else: offset = 0 # Init logfname = generate_logfilename(logdir, relative_filepath) index[relative_filepath] = logfname write_file(join(logdir, logfname), str(offset) + '\n') write_json(indexpath, index) self.print_('Started logging file!')
def make_sure_metadir_exists(self, root): """ Create a directory with a stub page if none exist. """ if not os.path.exists(root): os.mkdir(root) for fname, title in self.defaultpages.items(): jsondata = generate_page_metadata(title) write_file(join(root, fname), jsondata + '\n')
def save_pages(path, name, pages): template = read_file(local_path('pagetemplate.html')) for n, page in enumerate(pages): controls = gen_controls(name, n, len(pages)) out = template.format(controls=controls, **page) fpath = os.path.join(path, name) if len(pages) > 1: fpath += ' - Page {:03}'.format(n + 1) fpath += '.html' write_file(fpath, out)
def save_pages(path, name, pages): template = read_file(local_path('pagetemplate.html')) for n, page in enumerate(pages): controls = gen_controls(name, n, len(pages)) out = template.format(controls=controls, **page) fpath = os.path.join(path, name) if len(pages) > 1: fpath += ' - Page {:03}'.format(n+1) fpath += '.html' write_file(fpath, out)
def add_to_recent_files(self, filename): listfname = self.get_path('recentfiles') length = self.get_setting('recent file list length') # This fixes both symlinks and relative paths realfname = os.path.realpath(filename) recentfiles = [realfname] if os.path.exists(listfname): oldrecentfiles = read_file(listfname).splitlines() recentfiles += [x for x in oldrecentfiles if x != realfname][:length-1] write_file(listfname, '\n'.join(recentfiles)) self.update_recent_files.emit()
def update_style(self, style): try: css = self.css_template.format(**style) indexcss = self.index_css_template.format(**style) except KeyError as e: print(e) #self.index_viewer.error('Invalid style config: key missing') return self.setStyleSheet(css) self.index_viewer.defaulttagcolor = style['index entry tag default background'] disclaimer = '/* AUTOGENERATED! NO POINT IN EDITING THIS */\n\n' write_file(join(self.configdir, '.index.css'), disclaimer + indexcss) self.index_viewer.css = indexcss self.index_viewer.refresh_view(keep_position=True)
def cmd_new_page(self, fname): f = join(self.root, fname) if os.path.exists(f): self.terminal.error('File already exists') return title = fixtitle(fname) try: newtab = self.tabbar.add_page(title, fname) except KeyError as e: self.terminal.error(e.args[0]) else: write_file(f, generate_page_metadata(title) + '\n') # Do this afterwards to have something to load into textarea self.set_tab_index(newtab)
def cmd_revision_control(self, arg): fname = self.current_page_path() firstline, _ = read_file(fname).split('\n', 1) jsondata = json.loads(firstline) if arg == '+': if self.revisionactive: self.terminal.error('Can\'t create new revision when viewing an old one') return saved = self.save_tab() if saved: # Do this again in case something got saved before _, data = read_file(fname).split('\n', 1) f = join(self.root, fname) rev = jsondata['revision'] shutil.copy2(f, f + '.rev{}'.format(rev)) jsondata['revision'] += 1 jsondata['revision created'] = datetime.now().isoformat() write_file(f, json.dumps(jsondata) + '\n' + data) self.terminal.print_('Revision increased to {}'.format(rev + 1)) # Show a certain revision elif arg.isdigit(): revfname = join(self.root, fname + '.rev{}'.format(arg)) if not os.path.exists(revfname): self.terminal.error('Revision {} not found'.format(arg)) return saved = self.save_tab() if not saved: return try: _, data = read_file(revfname).split('\n', 1) except Exception as e: print(str(e)) self.error('Something went wrong when loading the revision') else: self.textarea.setPlainText(data) self.textarea.document().setModified(False) self.revisionactive = True self.revisionnotice.setText('Showing revision {}. Changes will not be saved.'.format(arg)) self.revisionnotice.show() elif arg == '#': self.terminal.print_('Current revision: {}'.format(jsondata['revision'])) elif not arg: if not self.revisionactive: self.terminal.error('Already showing latest revision') else: currenttab = self.tabbar.currentIndex() self.set_tab_index(currenttab) else: self.terminal.error('Unknown argument: "{}"'.format(arg))
def cmd_rename_current_page(self, title): if not title.strip(): oldtitle = self.tabbar.pages[self.tabbar.currentIndex()][0] self.terminal.prompt('r {}'.format(oldtitle)) return try: self.tabbar.rename_page(title) except KeyError as e: self.terminal.error(e.args[0]) else: fname = self.current_page_path() firstline, data = read_file(fname).split('\n', 1) jsondata = json.loads(firstline) jsondata['title'] = title write_file(fname, json.dumps(jsondata) + '\n' + data)
def check_and_fix_page_metadata(jsondata, payload, fname): """ Make sure that the page's metadata has all required keys. Fix and add them if some of them are missing. """ fixed = False defaultvalues = generate_page_metadata(fixtitle(os.path.basename(fname)), asdict=True) # Special case if date exists and revision date doesn't: if 'revision created' not in jsondata and 'date' in jsondata: jsondata['revision created'] = jsondata['date'] fixed = True # Generic fix for key, value in defaultvalues.items(): if key not in jsondata: jsondata[key] = value fixed = True if fixed: write_file(fname, json.dumps(jsondata) + '\n' + payload) return jsondata
def load_pages(self, root): """ Read all pages from the specified directory and build a list of them. """ fnames = os.listdir(root) for f in fnames: if re.search(r'\.rev\d+$', f) is not None: continue if os.path.isdir(join(root, f)): continue firstline, data = read_file(join(root, f)).split('\n', 1) try: jsondata = json.loads(firstline) except ValueError: self.print_('Bad/no properties found on page {}, fixing...'.format(f)) title = fixtitle(f) jsondata = generate_page_metadata(title) write_file(join(root, f), '\n'.join([jsondata, firstline, data])) yield [title, f, 0, 0] else: fixedjsondata = check_and_fix_page_metadata(jsondata, data, join(root, f)) yield [fixedjsondata['title'], f, 0, 0]
def write_file(self, filename): write_file(filename, self.document().toPlainText())
format = 'html' elif ext == '.txt': format = 'rawtext' else: format = fallback else: format = fallback # Check to see if the markdown lib exists if format == 'markdown' and not markdown_available: format = fallback # Check if format is supported at all if format not in formats: format = fallback # Parse the shit if format == 'rawtext': body = html.escape(text).replace('\n', '<br>') return html_boilerplate.format(body='<pre>{}</pre>'.format(body), css=css) elif format == 'markdown': body = markdown.markdown(text) return html_boilerplate.format(body=body, css=css) elif format == 'html': return text if __name__ == '__main__': from libsyntyche.common import write_file fname = '/home/nycz/gitprojects/sapfo/README.md' text = read_file(fname) page = generate_page(text, fname, '', 'auto') write_file('/home/nycz/gitprojects/libsyntyche/test.html', page)
def dev_command(self, arg): write_file('dump.html', self.view.webview.page().mainFrame().toHtml())