Skip to content

Commit

Permalink
:w to trigger compile
Browse files Browse the repository at this point in the history
  • Loading branch information
dmadisetti committed May 6, 2023
1 parent 492a209 commit d3f621b
Show file tree
Hide file tree
Showing 5 changed files with 120 additions and 28 deletions.
12 changes: 7 additions & 5 deletions rplugin/python3/airlatex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from airlatex.util import logging_settings, init_logger, __version__




@pynvim.plugin
class AirLatex:
def __init__(self, nvim):
Expand Down Expand Up @@ -66,9 +64,7 @@ def openSidebar(self):
self.nvim.command("let user_input = input(\"No Password found for '%s' and user '%s'.\nType it in to store it in keyring: \")" % (DOMAIN, username))
self.nvim.command("call inputrestore()")
keyring.set_password("airlatex_"+DOMAIN, username, self.nvim.eval("user_input"))

password = keyring.get_password("airlatex_"+DOMAIN, username)

# connect
try:
self.session = AirLatexSession(DOMAIN, self.servername, self.sidebar, self.nvim, https=https)
Expand Down Expand Up @@ -110,8 +106,14 @@ def projectLeave(self, args):
# def projectEnter(self):
# plugin.updateProject()

@pynvim.function('AirLatex_Compile', sync=True)
def compile(self, args):
buffer = self.nvim.current.buffer
if buffer in DocumentBuffer.allBuffers:
DocumentBuffer.allBuffers[buffer].compile()

@pynvim.function('AirLatexToggle', sync=True)
def air_latex_toggle(self, args):
def toggle(self, args):
self.sidebar.toggle()

@pynvim.function('AirLatex_Close', sync=True)
Expand Down
4 changes: 4 additions & 0 deletions rplugin/python3/airlatex/documentbuffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def initDocumentBuffer(self):
# self.nvim.command("set updatetime=500")
# self.nvim.command("autocmd CursorMoved,CursorMovedI * :call AirLatex_update_pos()")
# self.nvim.command("autocmd CursorHold,CursorHoldI * :call AirLatex_update_pos()")
self.nvim.command("cmap <buffer> w call AirLatex_Compile()<CR>")
self.nvim.command("au CursorMoved <buffer> call AirLatex_WriteBuffer()")
self.nvim.command("au CursorMovedI <buffer> call AirLatex_WriteBuffer()")
self.nvim.command("command! -buffer -nargs=0 W call AirLatex_WriteBuffer()")
Expand All @@ -62,6 +63,9 @@ def writeLines(buffer,lines):
self.saved_buffer = buffer[:]
self.nvim.async_call(writeLines,self.buffer,lines)

def compile(self):
create_task(self.project_handler.compile())

def updateRemoteCursor(self, cursor):
self.log.debug("updateRemoteCursor")
# def updateRemoteCursor(cursor, nvim):
Expand Down
97 changes: 87 additions & 10 deletions rplugin/python3/airlatex/project_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,61 @@
# answer_mult : m[5]
# msg : m[5]

# Add a comment
# {
# "name": "applyOtUpdate",
# "args": [
# "63b827fbb79e82556f365193",
# {
# "doc": "63b827fbb79e82556f365193",
# "op": [
# {
# "c": "%% \n%% Copyright 2007-2020 Elsevier Ltd\n%% ",
# "p": 0,
# "t": "6455d082cb375f31bd000001"
# }
# ],
# "v": 7401,
# "hash": "1305509d3513152d16c710401bb195d08076659b",
# "meta": {
# "tc": "6455cef3ec3f52201f"
# }
# }
# ]
# }

# For compile rootDoc_id is main file
# {
# "rootDoc_id": "63b827fbb79e82556f365193",
# "draft": false,
# "check": "silent",
# "incrementalCompilesEnabled": true,
# "stopOnFirstError": false
# }

class AirLatexProject:

def __init__(self, url, project, used_id, sidebar, cookie=None, wait_for=15, validate_cert=True):
def __init__(self, url, project, csrf, used_id, sidebar, base_url,
httpHandler,
nvim,
cookie=None,
wait_for=15, validate_cert=True):
project["handler"] = self

self.sidebar = sidebar
self.ioloop = IOLoop()
self.used_id = used_id
self.project = project
self.url = url
self.project = project
self.csrf = csrf
self.used_id = used_id
self.sidebar = sidebar
self.base_url = base_url
self.httpHandler = httpHandler
self.nvim = nvim

self.cookie = cookie
self.wait_for = wait_for if str(wait_for).isnumeric() else None
self.validate_cert = validate_cert
self.cookie = cookie
self.url_base = url.split("/")[2]

self.ioloop = IOLoop()
self.command_counter = count(1)
self.ws = None
self.requests = {}
Expand Down Expand Up @@ -92,12 +133,43 @@ async def bufferDo(self, doc_id, command, data):
elif command == "updateRemoteCursor":
buf.updateRemoteCursor(data)

async def compile(self):
# TODO
# POST https://www.overleaf.com/project/61e630765fd4be0925750c79/compile?enable_pdf_caching=true
self.log.debug(f"Compiling. {str(self.project)}")
compile_url = f"{self.base_url}/project/{self.project['id']}/compile?enable_pdf_caching=true"
post = lambda: self.httpHandler.post(compile_url, headers={
'Cookie': self.cookie,
'x-csrf-token': self.csrf,
'content-type': 'application/json'
},
json={
"rootDoc_id": self.project["rootDoc_id"],
"draft": False,
"check": "silent",
"incrementalCompilesEnabled": True,
"stopOnFirstError": False
})
import requests
logger = self.log
response = (await self.nvim.loop.run_in_executor(None, post))

try:
data = response.json()
if data["status"] != "success":
raise Exception("Not success. Something failed.")
logger.debug("Compiled.")
except Exception as e:
logger.debug("\nResponse Content:")
logger.debug(f"{response.content}\n---\n{e}")


async def updateRemoteCursor(self, cursors):
for cursor in cursors:
if "row" in cursor and "column" in cursor and "doc_id" in cursor:
await self.bufferDo(cursor["doc_id"], "updateRemoteCursor", cursor)

async def updateCursor(self,doc, pos):
async def updateCursor(self, doc, pos):
event = Event()
await self.send("update",{
"name":"clientTracking.updatePosition",
Expand Down Expand Up @@ -214,7 +286,7 @@ async def joinDocument(self, buffer):
# register document op-buffer
self.documents[doc["_id"]]["ops_buffer"] = []

# regester for document-watching
# register for document-watching
await self.send("cmd",{
"name":"joinDoc",
"args": [
Expand Down Expand Up @@ -373,7 +445,12 @@ async def run(self):

# answer to our request
elif code == "7":
await self.sidebarMsg("Error: Unauthorized. My guess is that your session cookies are outdated or not loaded. Typically reloading '%s/project' using the browser you used for login should reload the cookies." % self.url_base)
await self.sidebarMsg("Error: Unauthorized. My guess is that"
" your session cookies are outdated or"
" not loaded. Typically reloading"
" '%s/project' using the browser you"
" used for login should reload the"
" cookies." % self.base_url)

# unknown message
else:
Expand Down
18 changes: 14 additions & 4 deletions rplugin/python3/airlatex/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,21 @@ async def connectProject(self, project):

anim_status = create_task(self._makeStatusAnimation("Connecting to Project"))

get = lambda: self.httpHandler.get(f"{self.url}/project/{project['id']}", allow_redirects=False)
projectPage = (await self.nvim.loop.run_in_executor(None, get))
csrf = re.search('content="([^"]*)"',
re.search('<meta\s[^>]*name="ol-csrfToken"[^>]*>', projectPage.text)[0])[1]

# start connection
anim_status.cancel()
cookie_str = "; ".join(name + "=" + value for name, value in self.httpHandler.cookies.get_dict().items())
airlatexproject = AirLatexProject(await self._getWebSocketURL(), project, self.user_id, self.sidebar, cookie=cookie_str, wait_for=self.wait_for, validate_cert=self.httpHandler.verify)
# Side bar set command in document
airlatexproject = AirLatexProject(await self._getWebSocketURL(),
project, csrf, self.user_id,
self.sidebar, self.url,
self.httpHandler,
self.nvim,
cookie=cookie_str,
wait_for=self.wait_for,
validate_cert=self.httpHandler.verify)
create_task(airlatexproject.start())



17 changes: 8 additions & 9 deletions rplugin/python3/airlatex/sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def initSidebarBuffer(self):
self.nvim.command("nnoremap <silent> <buffer> k <up> <bar> :call AirLatex_SidebarRefresh() <enter> <bar> <right>")
self.nvim.command("nnoremap <silent> <buffer> <down> <down> <bar> :call AirLatex_SidebarRefresh() <enter> <bar> <right>")
self.nvim.command("nnoremap <silent> <buffer> j <down> <bar> :call AirLatex_SidebarRefresh() <enter> <bar> <right>")
self.nvim.command("nnoremap <silent> <enter> :call AirLatex_ProjectEnter() <enter>")
self.nvim.command("nnoremap <silent> <buffer> <enter> :call AirLatex_ProjectEnter() <enter>")
self.nvim.command("autocmd VimLeavePre <buffer> :call AirLatex_Close()")
self.nvim.command("nnoremap <silent> <buffer> d :call AirLatex_ProjectLeave() <enter>")
self.nvim.command("nnoremap <silent> <buffer> D :call AirLatex_ProjectLeave() <enter>")
Expand Down Expand Up @@ -266,6 +266,13 @@ def hide(self):
# Return to the original buffer
self.nvim.command('buffer ' + current_buffer.name)

@pynvimCatchException
def compile(self):
if self.visible:
self.hide()
else:
self.show()

@pynvimCatchException
def toggle(self):
if self.visible:
Expand Down Expand Up @@ -350,11 +357,3 @@ def cursorAction(self, key="enter"):
elif self.cursorPos[-1]["type"] == "file":
documentbuffer = DocumentBuffer(self.cursorPos, self.nvim)
create_task(self.cursorPos[0]["handler"].joinDocument(documentbuffer))








0 comments on commit d3f621b

Please sign in to comment.