OptiEditText + Code
Ready
Improving text with AI…
0 matches
OptiEdit

Free online text, Markdown and code editor

Write, format and edit files in your browser. Start a document, import a file or open a folder. No account required.

Documents stay on this device. AI Rewrite is optional and sends text only when you request it.

0 words•0 characters•1 line0 min read Stored locally
New from template
OptiEdit help

OptiEdit supports both everyday rich-text editing and advanced local-file/code workflows. Start with the action that matches what you want to edit.

New document

Create a browser document with rich formatting, autosave, tabs, Markdown mode, voice typing and DOCX/PDF export.

Open local file

Open text, Markdown, HTML, JSON, source files, Word DOCX and common images. Compatible browsers can save editable files directly back to disk.

Open folder workspace

Browse and edit real files in a selected folder. Workspace files are not copied into browser document storage.

AI Rewrite

Rewrite the current rich-text document. A successful rewrite is a single undoable change, so Undo restores the previous content. Document text is sent by POST to this website’s AI proxy, which forwards it to the enhancement service. Upstream requests may include text in server-side URLs and logs; avoid sending confidential information.

Rich-text editing

  • Use Copy to copy the entire active document in one tap; rich text also preserves formatting when the browser clipboard supports it.
  • Use the formatting toolbar for headings, fonts, colors, alignment, tables, code and other rich-text controls.
  • Use headings, fonts, sizes, bold, italic, underline, strike, lists, checklists, alignment, indentation, quotes, links, images and tables.
  • Use text and highlight color controls for emphasis.
  • Open Document outline to jump between headings in long documents.
  • Use HTML source mode when you need direct HTML editing.

Markdown & voice typing

  • Switch a rich-text document to Markdown editor / preview for source editing with a live rendered preview, then return to rich text when needed.
  • Markdown files open directly in Markdown mode and save as Markdown.
  • Use Dictate / Voice typing to insert speech at the current cursor position when supported by your browser.

Code and developer tools

  • Choose a code language to apply syntax highlighting to rich-text code blocks.
  • Use Tab / Shift+Tab for code indentation and the formatter for pasted code.
  • Folder and local source files open in the dedicated code editor with Find, Wrap and Copy controls.
  • JSON and XML/HTML formatting tools are available from the rich-text toolbar.

Documents, files and export

  • Source icons identify browser documents, linked disk files and folder workspace files.
  • Browser documents support rename, duplicate, delete, tabs, autosave and full-library backup.
  • Import TXT, Markdown, HTML, DOCX, common image formats and OptiEdit JSON backups.
  • Export editable documents as Microsoft Word DOCX, PDF, HTML, legacy Word-compatible DOC, Markdown, plain text or OptiEdit JSON. Images open in a safe preview instead of being decoded as text.

Keyboard shortcuts

  • Save: Ctrl/Cmd + S
  • New: Ctrl/Cmd + Alt + N
  • Find & replace: Ctrl/Cmd + F
  • Undo / Redo: Ctrl/Cmd + Z / Ctrl/Cmd + Shift + Z
  • HTML source mode: Ctrl/Cmd + Shift + H

Storage, privacy and offline use

Browser documents are stored locally using IndexedDB. Folder workspace files remain in the folder you selected. OptiEdit can work offline after its app resources have been cached. Document text is sent to the configured enhancement service only when you explicitly run AI Rewrite.

Open the complete Help & Feature Guide →
Install OptiEdit
About OptiEdit

OptiEdit is a free local-first rich text and code editor for the browser. It combines document editing, local files, folder workspaces, developer tools, import/export, offline PWA support and optional AI rewriting in one focused workspace.

Version 2.17.0

`}; } return {type:'text/markdown;charset=utf-8',data:md}; } const html=$('.ql-editor').innerHTML; const text=this.quill.getText().replace(/\n$/,''); if(name.endsWith('.docx')) return {type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document',data:this.createDocxBlob(html,$('#docTitle').value)}; if(name.endsWith('.md')||name.endsWith('.markdown')) return {type:'text/markdown;charset=utf-8',data:window.TurndownService?new window.TurndownService({headingStyle:'atx',codeBlockStyle:'fenced'}).turndown(html):text}; if(name.endsWith('.html')||name.endsWith('.htm')){ const title=this.escapeHtml($('#docTitle').value); return {type:'text/html;charset=utf-8',data:`${title}${html}`}; } if(name.endsWith('.json')) return {type:'application/json;charset=utf-8',data:text}; if(name.endsWith('.xml')) return {type:'application/xml;charset=utf-8',data:text}; if(name.endsWith('.css')) return {type:'text/css;charset=utf-8',data:text}; if(/\.(?:js|mjs|cjs)$/.test(name)) return {type:'text/javascript;charset=utf-8',data:text}; return {type:'text/plain;charset=utf-8',data:text}; }, async writeTextToHandle(handle,text,userInitiated=false){const ok=await this.ensureWritePermission(handle,userInitiated);if(!ok)return false;try{const w=await handle.createWritable();await w.write(String(text??''));await w.close();return true}catch(e){this.toast('Save failed: '+e.message,'error');return false}}, async ensureWritePermission(handle,requestPermission=false){try{if(!handle.queryPermission)return true;let p=await handle.queryPermission({mode:'readwrite'});if(p==='granted')return true;if(requestPermission&&handle.requestPermission)p=await handle.requestPermission({mode:'readwrite'});return p==='granted'}catch{return false}}, async writeCurrentToHandle(handle,{requestPermission=false,quiet=false}={}){if(!handle)return false;const allowed=await this.ensureWritePermission(handle,requestPermission);if(!allowed){if(!quiet)this.toast('Permission is required to write to the local file','error');return false}try{const payload=this.localFileData(handle);const writable=await handle.createWritable();await writable.write(payload.data instanceof Blob?payload.data:new Blob([payload.data],{type:payload.type}));await writable.close();this.updateLocalFileState(false);if(!quiet)this.toast('Saved to '+(handle.name||'local file'));return true}catch(e){if(!quiet)this.toast('Local file save failed: '+(e.message||e),'error');return false}}, async saveToLocalFile(){this.closeMenus();let handle=await this.loadLocalHandle(this.currentId);if(!handle)return this.saveAsLocalFile();await this.save(false,true)}, async saveAsLocalFile(){this.closeMenus();if(!this.currentId)return;if(!this.fileSystemSupported()){ this.toast('Direct Save As is unavailable in this browser. Downloading a copy instead.'); if(this.editorMode==='markdown')return this.exportType('md'); if(this.editorMode==='code'){ const f=this.files.get(this.currentId),filename=this.safeName(f?.fileName||f?.title||'document.txt'); return this.download(filename.includes('.')?filename:filename+'.txt','text/plain;charset=utf-8',this.currentTextContent()); } return this.exportType('html'); }try{if(await this.save()===false)return;const existing=this.localHandles.get(this.currentId);const ext=this.editorMode==='markdown'?'.md':(this.editorMode==='code'?'.txt':'.html');const suggested=existing?.name||this.safeName($('#docTitle').value||'document')+ext;const handle=await window.showSaveFilePicker({suggestedName:suggested,types:this.localSavePickerTypes()});const written=await this.writeCurrentToHandle(handle,{requestPermission:true});if(!written)return;await this.persistLocalHandle(this.currentId,handle);this.updateLocalFileState();this.renderFiles();this.renderTabs()}catch(e){if(e?.name!=='AbortError')this.toast('Could not save local file: '+(e.message||e),'error')}}, updateStats(){if(!this.quill)return;if(this.editorMode==='image'){$('#wordStat').textContent='Image';$('#charStat').textContent='Preview';$('#lineStat').textContent='Read-only';$('#readStat').textContent='';return}const source=['code','markdown'].includes(this.editorMode),text=source?this.currentTextContent():this.quill.getText().replace(/\n$/,'');const words=(text.match(/\S+/g)||[]).length,lines=text?text.split(/\n/).length:1;$('#wordStat').textContent=`${words} word${words===1?'':'s'}`;$('#charStat').textContent=`${text.length} character${text.length===1?'':'s'}`;$('#lineStat').textContent=`${lines} line${lines===1?'':'s'}`;$('#readStat').textContent=this.editorMode==='markdown'?'Markdown':(this.editorMode==='code'?(this.currentCodeLanguage||'Plain text'):`${Math.ceil(words/220)||0} min read`)}, async importFiles(fileList){ const files=[...fileList];if(!files.length)return;let added=0,updated=0,failed=0; for(const file of files){try{ const ext=(file.name.split('.').pop()||'').toLowerCase(); if(ext==='json'){ const raw=await file.text();let parsed=null; try{parsed=JSON.parse(raw)}catch{ /* Invalid JSON should remain editable as source. */ } const looksLikeDoc=parsed&&typeof parsed==='object'&&( Array.isArray(parsed.ops)||(typeof parsed.id==='string'&&'content' in parsed)|| (!Array.isArray(parsed)&&Object.keys(parsed).length>0&&Object.values(parsed).every(v=>v&&typeof v==='object'&&'content' in v)) ); if(looksLikeDoc){const result=await this.importJSON(file);added+=result.added;updated+=result.updated} else {await this.createImported(file.name,raw,'code');added++} } else if(this.isImageFile(file.name,file.type)){await this.createImportedImage(file);added++} else if(ext==='docx'){if(!window.mammoth)throw new Error('DOCX library not loaded');const buf=await file.arrayBuffer();const r=await window.mammoth.convertToHtml({arrayBuffer:buf});await this.createImported(file.name.replace(/\.docx$/i,''),r.value,'html');added++} else{const text=await file.text();if(ext==='md'||ext==='markdown')await this.createImported(file.name,text,'markdown'); else if(ext==='html'||ext==='htm')await this.createImported(file.name.replace(/\.html?$/i,''),text,'html'); else if(/^(css|js|mjs|cjs|jsx|ts|tsx|xml|json|py|java|c|h|cpp|cc|cs|go|php|rb|sh|bash|sql|rs|yml|yaml|vue|scss|less|sass)$/.test(ext))await this.createImported(file.name,text,'code'); else await this.createImported(file.name.replace(/\.txt$/i,''),text,'text');added++} }catch(err){console.error(file.name,err);failed++}} $('#fileImport').value='';this.renderFiles();this.toast(`Import complete: ${added} added${updated?`, ${updated} updated`:''}${failed?`, ${failed} failed`:''}`+(failed?'':'') ,failed?'error':'success'); }, async importJSON(file){ if(await this.save()===false)return{added:0,updated:0}; const data=JSON.parse(await file.text());let docs=[]; if(data&&Array.isArray(data.ops)) docs=[{id:this.makeId(),title:file.name.replace(/\.json$/i,''),content:data,modified:Date.now()}]; else if(data&&data.id&&('content'in data))docs=[data]; else if(data&&typeof data==='object')docs=Object.values(data).filter(x=>x&&typeof x==='object'&&('content'in x||'title'in x)); if(!docs.length)throw new Error('No compatible OptiEdit documents found in JSON');let added=0,updated=0,last=null; for(const raw of docs){const d=this.normalizeDoc(raw);const existing=this.files.get(d.id);if(existing){if((d.modified||0)>=(existing.modified||0)){this.files.set(d.id,d);await DB.put('documents',d);updated++;last=d}}else{this.files.set(d.id,d);await DB.put('documents',d);added++;last=d}} if(last)await this.openDoc(last.id,false);return{added,updated}; }, async createImported(title,content,mode){if(await this.save()===false)throw new Error('Save the current document before importing another file');const id=this.makeId();if(mode==='code'){const d={id,title:title||'Imported source file',fileName:title||'file.txt',content:String(content??''),modified:Date.now(),editorMode:'code',language:this.codeLanguageForFile(title)};this.files.set(id,d);await DB.put('documents',d);await this.openDoc(id,false);return d}if(mode==='markdown'){const d={id,title:title||'Imported.md',content:String(content??''),modified:Date.now(),editorMode:'markdown',language:'markdown'};this.files.set(id,d);await DB.put('documents',d);await this.openDoc(id,false);return d}const d={id,title:title||'Imported Document',content:'',modified:Date.now(),editorMode:'rich'};this.files.set(id,d);await DB.put('documents',d);await this.openDoc(id,false);if(mode==='html'){this.quill.setText('', 'silent');this.quill.clipboard.dangerouslyPasteHTML(0,content,'silent')}else this.quill.setText(content,'silent');this.quill.history?.clear?.();this.markDirty();await this.save(true);this.renderTabs();this.updateOutline();this.scheduleSyntaxRefresh(45);this.updateLocalFileState();return d}, async createImportedImage(file){if(await this.save()===false)throw new Error('Save the current document before importing an image');const id=this.makeId(),d={id,title:file.name||'Image',fileName:file.name||'image',content:file,modified:Date.now(),editorMode:'image',imageType:file.type||''};this.files.set(id,d);await DB.put('documents',d);await this.openDoc(id,false);return d}, blobToDataURL(blob){return new Promise((resolve,reject)=>{try{const r=new FileReader();r.onload=()=>resolve(String(r.result||''));r.onerror=()=>reject(r.error||new Error('Could not read binary data'));r.readAsDataURL(blob)}catch(e){reject(e)}})}, async serializableDocument(f){const copy={...f};delete copy.handle;if(copy.content instanceof Blob)copy.content=await this.blobToDataURL(copy.content);return copy}, exportFontCSS(){return '.ql-font-arial{font-family:Arial,Helvetica,sans-serif}.ql-font-helvetica{font-family:Helvetica,Arial,sans-serif}.ql-font-times-new-roman{font-family:"Times New Roman",Times,serif}.ql-font-georgia{font-family:Georgia,"Times New Roman",serif}.ql-font-verdana{font-family:Verdana,Geneva,sans-serif}.ql-font-tahoma{font-family:Tahoma,Verdana,sans-serif}.ql-font-trebuchet-ms{font-family:"Trebuchet MS",Arial,sans-serif}.ql-font-segoe-ui{font-family:"Segoe UI",Arial,sans-serif}.ql-font-calibri{font-family:Calibri,"Segoe UI",Arial,sans-serif}.ql-font-cambria{font-family:Cambria,Georgia,serif}.ql-font-courier-new{font-family:"Courier New",Courier,monospace}.ql-font-serif{font-family:Georgia,"Times New Roman",serif}.ql-font-monospace{font-family:monospace}'}, createDocxBlob(html,title='Document'){ if(!window.htmlDocx?.asBlob) throw new Error('DOCX export library did not load'); const safeTitle=this.escapeHtml(title); const css='body{font-family:Arial,sans-serif;line-height:1.55}img{max-width:100%}table{border-collapse:collapse;width:100%}td,th{border:1px solid #bbb;padding:7px}'+this.exportFontCSS(); const doc=`${safeTitle}${html}`; return window.htmlDocx.asBlob(doc,{margins:{top:1080,right:1080,bottom:1080,left:1080}}); }, async exportType(type){this.closeMenus();if(type==='backup')return this.exportBackup();if(!this.currentId||!this.files.has(this.currentId))return this.toast('Open a document first','error');if(await this.save()===false)return this.toast('Save the current document before exporting','error');const f=this.files.get(this.currentId);const name=this.safeName(this.fileTitle(f.title||'document'));if(f.editorMode==='image'){if(type==='json'){const out=await this.serializableDocument(f);return this.download(`${name}.json`,'application/json;charset=utf-8',JSON.stringify(out,null,2))}return this.toast('Image preview keeps the original image unchanged; use the source file directly','error')}const markdown=f.editorMode==='markdown',code=f.editorMode==='code';const md=markdown?this.currentTextContent():null;const html=markdown?this.markdownHtml(md):(code?'
'+this.escapeHtml(this.currentTextContent())+'
':$('.ql-editor').innerHTML);const text=(code||markdown)?this.currentTextContent():this.quill.getText().replace(/\n$/,''); if(type==='pdf')return this.exportPDF(name,html,f.title); if(type==='html')return this.download(`${name}.html`,'text/html;charset=utf-8',`${this.escapeHtml(f.title)}

${this.escapeHtml(f.title)}

${html}`); if(type==='docx'){try{return this.download(`${name}.docx`,'application/vnd.openxmlformats-officedocument.wordprocessingml.document',this.createDocxBlob(`

${this.escapeHtml(f.title)}

${html}`,f.title))}catch(e){return this.toast('DOCX export failed: '+(e.message||e),'error')}} if(type==='doc')return this.download(`${name}.doc`,'application/msword;charset=utf-8',`${this.escapeHtml(f.title)}

${this.escapeHtml(f.title)}

${html}`); if(type==='txt')return this.download(`${name}.txt`,'text/plain;charset=utf-8',text); if(type==='md'){const out=markdown?md:(window.TurndownService?new window.TurndownService({headingStyle:'atx',codeBlockStyle:'fenced'}).turndown(html):text);return this.download(`${name}.md`,'text/markdown;charset=utf-8',out)} if(type==='json')return this.download(`${name}.json`,'application/json;charset=utf-8',JSON.stringify(f,null,2)); }, async exportBackup(){if(await this.save()===false)return this.toast('Save the current document before creating a backup','error');const obj={};for(const f of [...this.files.values()].filter(f=>!f.workspace))obj[f.id]=await this.serializableDocument(f);this.download(`OptiEdit_Docs_${new Date().toISOString().slice(0,10)}.json`,'application/json;charset=utf-8',JSON.stringify(obj,null,2));this.toast('Backup downloaded')}, exportPDF(name,html,title){ const wrap=document.createElement('div');wrap.style.cssText='font-family:Arial,sans-serif;color:#111;line-height:1.55;padding:8mm 5mm';wrap.innerHTML=`

${this.escapeHtml(title)}

${html}`; if(window.html2pdf){html2pdf().set({margin:[12,12,12,12],filename:`${name}.pdf`,image:{type:'jpeg',quality:.96},html2canvas:{scale:2,useCORS:true,backgroundColor:'#ffffff'},jsPDF:{unit:'mm',format:'a4',orientation:'portrait'},pagebreak:{mode:['css','legacy']}}).from(wrap).save().then(()=>this.toast('PDF exported')).catch(()=>this.printDoc())} else{this.toast('PDF library unavailable. Opening print dialog instead.','error');this.printDoc()} }, printDoc(){if(!this.currentId||!this.files.has(this.currentId))return this.toast('Open a document first','error');const f=this.files.get(this.currentId);if(f.editorMode==='image'){const src=$('#imagePreview').src;if(!src)return this.toast('Image is not available','error');const w=open('','_blank');if(!w)return this.toast('Pop-up blocked','error');w.document.write(`${this.escapeHtml(f.title)}`);w.document.close();return setTimeout(()=>w.print(),250)}const w=window.open('','_blank');if(!w)return this.toast('Pop-up blocked','error');try{w.opener=null}catch{}const body=f.editorMode==='markdown'?this.markdownHtml(this.currentTextContent()):(f.editorMode==='code'?'
'+this.escapeHtml(this.currentTextContent())+'
':$('.ql-editor').innerHTML);w.document.write(`${this.escapeHtml(f.title)}

${this.escapeHtml(f.title)}

${body}`);w.document.close();setTimeout(()=>w.print(),200)}, download(filename,type,data){const blob=data instanceof Blob?data:new Blob([data],{type});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=filename;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(a.href),1000)}, safeName(s){return(s||'document').replace(/[\\/:*?"<>|]+/g,'-').replace(/\s+/g,' ').trim().slice(0,90)||'document'}, escapeHtml(s){return String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]))}, toggleMenu(menu,anchor){ this.closeMenus(menu); const was=menu.classList.contains('open'); if(was){menu.classList.remove('open');return} menu.classList.add('open'); menu.scrollTop=0; if(innerWidth>700){ const r=anchor.getBoundingClientRect(),w=menu.offsetWidth,h=menu.offsetHeight; menu.style.left=Math.min(innerWidth-w-8,Math.max(8,r.right-w))+'px'; menu.style.top=Math.max(8,Math.min(r.bottom+7,innerHeight-h-8))+'px'; }else{ menu.style.left='';menu.style.top=''; } }, closeMenus(except=null){$$('.menu.open').forEach(m=>{if(m!==except)m.classList.remove('open')})}, openDialog(id){this.closeMenus();const d=$('#'+id);if(!d.open)d.showModal()}, async installApp(){this.closeMenus();if(this.installPrompt){this.installPrompt.prompt();const r=await this.installPrompt.userChoice;if(r.outcome==='accepted')this.installPrompt=null;return}const ios=/iphone|ipad|ipod/i.test(navigator.userAgent);$('#installInstructions').innerHTML=ios?'

On iPhone or iPad, open OptiEdit in Safari, tap the Share button, then choose Add to Home Screen.

':'

In Chrome or Edge on desktop, install OptiEdit from the browser menu. The installed app can register for supported text/source files, so macOS Finder can offer Open With → OptiEdit. If OptiEdit was installed before file handling was added, reinstalling the PWA may be required for macOS to refresh the file associations.

';this.openDialog('installDialog')}, registerSW(){if('serviceWorker'in navigator&&location.protocol!=='file:')navigator.serviceWorker.register('./sw.js').catch(e=>console.warn('SW',e))}, handleLaunchParams(){const p=new URLSearchParams(location.search);if(p.get('new')==='1'){history.replaceState(null,'',location.pathname);this.newDoc()}if(p.get('files')==='1'){history.replaceState(null,'',location.pathname);this.toggleSidebar(true)}}, toast(msg,type='success'){const t=document.createElement('div');t.className='toast'+(type==='error'?' error':'');t.textContent=msg;$('#toastStack').appendChild(t);setTimeout(()=>t.remove(),type==='error'?8500:3300)} }; window.addEventListener('DOMContentLoaded',()=>app.init());