summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorcathook <b01902109@csie.ntu.edu.tw>2014-11-13 06:31:23 +0800
committercathook <b01902109@csie.ntu.edu.tw>2014-11-13 06:31:23 +0800
commit5def33f09f4c622c5461f25af61101e98f20c676 (patch)
treeb38219b02e10f333cd7a394fa8f6a7bd3934710f
parentac3a29d665af506a41820d3157db3caa73108eac (diff)
downloadvim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.tar
vim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.tar.gz
vim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.tar.bz2
vim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.tar.lz
vim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.tar.xz
vim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.tar.zst
vim-shrvim-5def33f09f4c622c5461f25af61101e98f20c676.zip
加入中文處理
-rw-r--r--server/src/tcp_server.py7
-rw-r--r--vim/plugin/shared_vim.vim574
2 files changed, 301 insertions, 280 deletions
diff --git a/server/src/tcp_server.py b/server/src/tcp_server.py
index 9aaf8fe..28bf0fc 100644
--- a/server/src/tcp_server.py
+++ b/server/src/tcp_server.py
@@ -19,6 +19,7 @@ TIMEOUT = 5
class _JSON_TOKEN: # pylint:disable=W0232
"""Enumeration the Ttken strings for json object."""
+ BYE = 'bye' # Resets the user and do nothong.
CURSORS = 'cursors' # other users' cursor position
ERROR = 'error' # error string
IDENTITY = 'identity' # identity of myself
@@ -193,11 +194,13 @@ class _TCPConnectionHandler(threading.Thread):
identity = request[_JSON_TOKEN.IDENTITY]
if identity not in self._users_text_manager.get_users_info():
return None
- if request[_JSON_TOKEN.INIT]:
+ if request.get(_JSON_TOKEN.INIT) or request.get(_JSON_TOKEN.BYE, False):
self._users_text_manager.reset_user(identity)
request[_JSON_TOKEN.TEXT] = ''
- for mark in request[_JSON_TOKEN.CURSORS]:
+ for mark in request.get(_JSON_TOKEN.CURSORS, []):
request[_JSON_TOKEN.CURSORS][mark] = 0
+ if _JSON_TOKEN.BYE in request:
+ return None
else:
auth = self._users_text_manager.get_users_info()[identity].authority
if auth < AUTHORITY.READWRITE:
diff --git a/vim/plugin/shared_vim.vim b/vim/plugin/shared_vim.vim
index 943420c..920ec26 100644
--- a/vim/plugin/shared_vim.vim
+++ b/vim/plugin/shared_vim.vim
@@ -4,16 +4,6 @@ if !exists('g:shared_vim_force_to_use')
endif
-if !exists('g:shared_vim_timeout')
- let g:shared_vim_timeout = 5
-endif
-
-
-if !exists('g:shared_vim_num_groups')
- let g:shared_vim_num_groups = 5
-endif
-
-
""""""""""""""""""""" Functions supplies by this plugin. """""""""""""""""""""""
function! SharedVimConnect(server_name, port, identity)
let b:shared_vim_server_name = a:server_name
@@ -25,17 +15,17 @@ endfunction
function! SharedVimDisconnect()
+ let b:shared_vim_goal = 'disconnect'
+ call SharedVimMainFunc()
unlet! b:shared_vim_server_name
unlet! b:shared_vim_port
unlet! b:shared_vim_identity
unlet! b:shared_vim_init
- let b:shared_vim_todo = 'disconnect'
- call SharedVimMainFunc()
endfunction
function! SharedVimSync()
- let b:shared_vim_todo = 'sync'
+ let b:shared_vim_goal = 'sync'
call SharedVimMainFunc()
let b:shared_vim_init = 0
endfunction
@@ -43,7 +33,7 @@ endfunction
"""""""""""""""""""""""""""" Setup for this plugin """""""""""""""""""""""""""""
" Highlight for other users.
-for i in range(1, 5)
+for i in range(1, g:shared_vim_num_groups)
exec 'hi SharedVimNor' . i . ' ctermbg=darkyellow'
exec 'hi SharedVimIns' . i . ' ctermbg=darkred'
exec 'hi SharedVimVbk' . i . ' ctermbg=darkblue'
@@ -51,12 +41,19 @@ endfor
" Sync
-autocmd! CursorMoved * call SharedVimSync()
-autocmd! CursorMovedI * call SharedVimSync()
-autocmd! CursorHold * call SharedVimSync()
-autocmd! CursorHoldI * call SharedVimSync()
-autocmd! InsertEnter * call SharedVimSync()
-autocmd! InsertLeave * call SharedVimSync()
+function! SharedVimTrySync()
+ if exists('b:shared_vim_server_name')
+ call SharedVimSync()
+ endif
+endfunction
+
+" Auto commands
+autocmd! CursorMoved * call SharedVimTrySync()
+autocmd! CursorMovedI * call SharedVimTrySync()
+autocmd! CursorHold * call SharedVimTrySync()
+autocmd! CursorHoldI * call SharedVimTrySync()
+autocmd! InsertEnter * call SharedVimTrySync()
+autocmd! InsertLeave * call SharedVimTrySync()
"""""""""""""""""""""""""""""""" Main procedure """"""""""""""""""""""""""""""""
@@ -84,16 +81,21 @@ SharedVimPython << EOF
import bisect
import json
import re
+import six
import socket
+import sys
import vim
import zlib
-TIMEOUT = 5
+if sys.version_info[0] >= 3:
+ unicode = str
-NUM_GROUPS = 5
-NORMAL_CURSOR_GROUPS = ['SharedVimNor%d' % i for i in range(1, NUM_GROUPS + 1)]
-INSERT_CURSOR_GROUPS = ['SharedVimIns%d' % i for i in range(1, NUM_GROUPS + 1)]
-VISUAL_GROUPS = ['SharedVimVbk%d' % i for i in range(1, NUM_GROUPS + 1)]
+DEFAULT_NUM_GROUPS = 5 # Default number of groups.
+DEFAULT_TIMEOUT = 5 # Default timeout.
+
+class GOALS: # pylint:disable=W0232
+ SYNC = 'sync' # Sync.
+ DISCONNECT = 'disconnect' # Disconnect.
class CURSOR_MARK: # pylint:disable=W0232
"""Enumeration type of cursor marks."""
@@ -115,8 +117,30 @@ class MODE: # pylint:disable=W0232
LINE_VISUAL = 5 # line visual mode.
BLOCK_VISUAL = 6 # block visual mode.
-class _JSON_TOKEN: # pylint:disable=W0232
+class VARNAMES: # pylint: disable=W0232
+ """Enumeration types of variable name in vim."""
+ PREFIX = 'shared_vim_' # Shared prefix of the variable names.
+ IDENTITY = PREFIX + 'identity' # Identity of the user.
+ INIT = PREFIX + 'init' # Initial or not.
+ NUM_GROUPS = PREFIX + 'num_groups' # Number of groups.
+ SERVER_NAME = PREFIX + 'server_name' # Server name.
+ SERVER_PORT = PREFIX + 'port' # Server port.
+ TIMEOUT = PREFIX + 'timeout' # Timeout for TCPConnection.
+ GOAL = PREFIX + 'goal' # Goal of this python code.
+
+# Name of the normal cursor group.
+NORMAL_CURSOR_GROUP = lambda x: 'SharedVimNor%d' % x
+
+# Name of the insert cursor group.
+INSERT_CURSOR_GROUP = lambda x: 'InsertVimNor%d' % x
+
+# Name of the visual group.
+VISUAL_GROUP = lambda x: 'VisualVimNor%d' % x
+
+
+class JSON_TOKEN: # pylint:disable=W0232
"""Enumeration the Ttken strings for json object."""
+ BYE = 'bye' # Disconnects with the server.
CURSORS = 'cursors' # other users' cursor position
ERROR = 'error' # error string
IDENTITY = 'identity' # identity of myself
@@ -217,106 +241,134 @@ class JSONPackage(object):
return body_byte.decode(JSONPackage.ENCODING)
-class _VimVarInfo(object):
- """Gets/sets the variable in vim."""
- def __init__(self):
- """Constructor."""
- pass
-
- def __getattr__(self, variable_name):
+class VimVarInfo(object): # pylint: disable=W0232
+ """Gets/sets variables in vim."""
+ def __getitem__(self, variable_name):
"""Gets the specified vim variable.
Args:
- variable_name: Variable name.
+ variable_name: Name of the variable to get.
- Returns:
+ Return:
None if the value is not exists, otherwise the value.
"""
- if variable_name not in vim.current.buffer.vars:
- return None
- ret = vim.current.buffer.vars[variable_name]
- if isinstance(ret, bytes):
- return ret.decode(JSONPackage.ENCODING)
- return ret
+ return self.get(variable_name)
- def __setattr__(self, variable_name, value):
- """Sets the specifiec vim variable.
-
- Args:
- variable_name: Variable name.
- value: Value.
- """
- vim.current.buffer.vars[variable_name] = value
-
- def __getitem__(self, variable_name):
+ def get(self, variable_name, default_value=None):
"""Gets the specified vim variable.
Args:
- variable_name: Variable name.
+ variable_name: Name of the variable to get.
+ default_value: The default to return if the variable is not exist.
- Returns:
- None if the value is not exists, otherwise the value.
+ Return:
+ default_value if the value is not exists, otherwise the value.
"""
- return self.__getattr__(variable_name)
+ if variable_name not in vim.current.buffer.vars:
+ return default_value
+ return VimInfo.transform_to_py(vim.current.buffer.vars[variable_name])
def __setitem__(self, variable_name, value):
"""Sets the specifiec vim variable.
Args:
- variable_name: Variable name.
- value: Value.
+ variable_name: Name of the variable to set.
+ value: The new value.
"""
- self.__setattr__(variable_name, value)
+ vim.current.buffer.vars[variable_name] = VimInfo.transform_to_vim(value)
def __delitem__(self, variable_name):
- """Deletes the specified vim variable.
+ """Deletes the specifiec vim variable.
Args:
- variable_name: Variable name.
+ variable_name: Name of the variable to delete.
"""
del vim.current.buffer.vars[variable_name]
-class _VimCursorsInfo(object):
- """Gets/sets the cursor in vim.
-
- Attributes:
- _info: A instance of VimInfo.
- """
- def __init__(self, info):
- """Constructor.
-
- Args:
- info: An instance of VimInfo.
- """
- self._info = info
+class VimCursorsInfo(object): # pylint: disable=W0232
+ """Gets/sets the cursor position in vim."""
+ def __init__(self, *_):
+ """Constructor."""
+ self._text_num_sum = []
def __getitem__(self, mark):
- """Gets the cursor position.
+ """Gets the cursor position with specifying the mark.
Args:
- mark: Which cursor.
+ mark: Mark of the cursor to get.
Return:
Cursor position.
"""
pos = [int(x) for x in vim.eval('getpos("%s")' % mark)]
- return self._info.rc_to_num((pos[1] - 1, pos[2] - 1))
+ return self.rc_to_num((pos[1] - 1, pos[2] - 1))
def __setitem__(self, mark, value):
- """Sets the cursor position.
+ """Sets the cursor position with specifying the mark.
+
+ Args:
+ mark: Mark of the cursor to set.
+ """
+ row, col = self.num_to_rc(value)
+ mark = mark if mark != CURSOR_MARK.V else CURSOR_MARK.CURRENT
+ vim.eval('setpos("%s", [0, %d, %d, 0])' % (mark, row + 1, col + 1))
+
+ def rc_to_num(self, rc):
+ """Transforms row-column cursor position to bytes position.
+
+ Args:
+ rc: Row-column cursor position.
+
+ Return:
+ byte position.
+ """
+ base = self._text_num_sum[rc[0] - 1] if rc[0] > 0 else 0
+ line = VimInfo.transform_to_vim(VimInfo.lines[rc[0]])
+ return base + len(VimInfo.transform_to_py(line[ : rc[1]]))
+
+ def num_to_rc(self, num, rmin=0):
+ """Transforms byte position to row-column cursor position.
+
+ Args:
+ num: byte cursor position.
+
+ Return:
+ List of row-column position.
+ """
+ row = bisect.bisect_right(self._text_num_sum, num, lo=rmin)
+ col = num - (0 if row == 0 else self._text_num_sum[row - 1])
+ return (row, len(VimInfo.transform_to_vim(VimInfo.lines[row][ : col])))
+
+ def nums_to_rcs(self, nums):
+ """Transforms list of sorted byte positions.
+
+ Args:
+ nums: list of byte cursor positions.
+
+ Return:
+ List of row-column positions.
+ """
+ ret, last_r = [], 0
+ for num in nums:
+ my_rc = self.num_to_rc(num, rmin=last_r)
+ ret += [my_rc]
+ last_r = my_rc[0]
+ return ret
+
+ def update_text_lines(self):
+ """Updates the content lines.
Args:
- mark: Which cursor.
+ lines: List of content lines.
"""
- pos = self._info.num_to_rc(value)
- if mark == CURSOR_MARK.V:
- mark = CURSOR_MARK.CURRENT
- vim.eval('setpos("%s", [0, %d, %d, 0])' %
- (mark, pos[0] + 1, pos[1] + 1))
+ self._text_num_sum, pre = [], 0
+ for line in VimInfo.lines:
+ self._text_num_sum += [pre + len(line) + 1]
+ pre += len(line) + 1
-class _GroupInfo(object):
+class GroupInfo(object):
"""Higilights informations about a user group.
Attributes:
@@ -352,47 +404,65 @@ class _GroupInfo(object):
@property
def normal_cursor_positions(self):
+ """Gets the normal cursor positions."""
return self._normal_cursor_positions
@property
def insert_cursor_positions(self):
+ """Gets the insert cursor positions."""
return self._insert_cursor_positions
@property
def visual_positions(self):
+ """Gets the visual positions."""
return self._visual_positions
-class _VimHighlightInfo(object):
+class VimHighlightInfo(object):
"""Highlight informations about users.
Attributes:
- _info: A instance of VimInfo.
_groups: A list of instance of GroupInfo.
_username_to_group: A dict for mapping the username to the instance of
GroupInfo.
"""
- def __init__(self, info):
- """Constructor.
-
- Args:
- info: An instance of VimInfo.
- """
- self._info = info
- self._groups = [_GroupInfo() for unused_i in range(NUM_GROUPS)]
+ def __init__(self):
+ """Constructor."""
+ self._groups = None
self._username_to_group = {}
def __getitem__(self, name):
- """Gets the cursor position.
+ """Gets the group (a instance of GroupInfo) by nickname.
Args:
- name: User name.
+ name: Nick name.
Return:
- Cursor position.
+ The group in which the user is.
"""
return self._username_to_group[name]
+ def reset(self, nicknames):
+ """Reset the users.
+
+ Args:
+ nicknames: A list of nickname.
+ """
+ if self._groups is None:
+ self._groups = [GroupInfo() for _ in range(self.num_of_groups())]
+ self._username_to_group = {name : self._groups[self._get_group_id(name)]
+ for name in nicknames}
+
+ def render(self):
+ """Render the highlight to vim."""
+ for index in range(self.num_of_groups()):
+ VimInfo.match(NORMAL_CURSOR_GROUP(index), MATCH_PRI.NORMAL,
+ self._groups[index].normal_cursor_positions)
+ VimInfo.match(INSERT_CURSOR_GROUP(index), MATCH_PRI.INSERT,
+ self._groups[index].insert_cursor_positions)
+ VimInfo.match(VISUAL_GROUP(index), MATCH_PRI.VISUAL,
+ self._groups[index].visual_positions)
+
def _get_group_id(self, string):
"""Transform the gived string to a valid group index.
@@ -400,68 +470,62 @@ class _VimHighlightInfo(object):
string: The gived string.
Return:
- The index in range(0, NUM_GROUPS)
+ The index in [0, number of groups)
"""
x = 0
for c in string:
- x = (x * 23 + ord(c)) % NUM_GROUPS
+ x = (x * 23 + ord(c)) % self.num_of_groups()
return x
- def reset(self, usernames):
- """Reset the users.
-
- Args:
- usernames: A list of username.
- """
- self._username_to_group = {}
- for name in usernames:
- gid = self._get_group_id(name)
- self._username_to_group[name] = self._groups[gid]
-
- def render(self):
- """Render the highlight to vim."""
- for index in range(NUM_GROUPS):
- self._info.match(NORMAL_CURSOR_GROUPS[index], MATCH_PRI.NORMAL,
- self._groups[index].normal_cursor_positions)
- self._info.match(INSERT_CURSOR_GROUPS[index], MATCH_PRI.INSERT,
- self._groups[index].insert_cursor_positions)
- self._info.match(VISUAL_GROUPS[index], MATCH_PRI.VISUAL,
- self._groups[index].visual_positions)
+ @staticmethod
+ def num_of_groups():
+ """Gets the number of groups."""
+ return VimInfo.var.get(VARNAMES.NUM_GROUPS, DEFAULT_NUM_GROUPS)
-class VimInfo(object):
- """Gets/sets the information about vim.
+class VimInfoMeta(type):
+ """An interface for accessing the vim's vars, buffer, cursors, etc.
- Attributes:
- _cursor_info: An instance of _VimCursorInfo.
- _highlight_info: An instance of _VimHighlightInfo.
- _mode: Last mode.
- _text_num_sum: ...
- _var_info: An instance of VimVarInfo.
+ Static attributes:
+ var: An instance of VimVarInfo, for accessing the variables in vim.
+ cursors: An instance of VimCursorsInfo, for accessing the cursor
+ information in vim.
+ highlight: An instance of VimHighlightInfo, for accessing the
+ information about highlight in vim.
+ ENCODING: vim's encoding.
"""
- def __init__(self):
+ var = VimVarInfo()
+ cursors = VimCursorsInfo()
+ highlight = VimHighlightInfo()
+ ENCODING = vim.options['encoding']
+
+ def __init__(self, *args):
"""Constructor."""
- self._var_info = _VimVarInfo()
- self._cursor_info = _VimCursorsInfo(self)
- self._highlight_info = _VimHighlightInfo(self)
- self._text_num_sum = []
self._mode = None
- self._calc_text_num_sum(vim.current.buffer[:])
+
+ @property
+ def lines(self): # pylint: disable=R0201
+ """Gets list of lines in the buffer."""
+ return [VimInfo.transform_to_py(line)
+ for line in vim.current.buffer[:]]
+
+ @lines.setter
+ def lines(self, lines): # pylint: disable=R0201
+ """Sets the buffer by list of lines."""
+ vim.current.buffer[0 : len(vim.current.buffer)] = \
+ [VimInfo.transform_to_vim(line) for line in lines]
@property
def text(self):
"""Gets the buffer text."""
- return '\n'.join(vim.current.buffer[:])
+ return '\n'.join(self.lines)
@text.setter
- def text(self, value):
+ def text(self, text):
"""Sets the buffer text."""
- lines = re.split('\n', value)
- if not lines:
- lines = ['']
- buflen = len(vim.current.buffer)
- vim.current.buffer[0 : buflen] = lines
- self._calc_text_num_sum(lines)
+ lines = re.split('\n', text)
+ self.lines = lines if lines else ['']
+ VimInfo.cursors.update_text_lines()
@property
def mode(self):
@@ -499,17 +563,8 @@ class VimInfo(object):
vim.command('exe "norm! \\<esc>"')
self._mode = value
- @property
- def cursors(self):
- """Gets/sets the cursor information. Delegates to VimCursorInfo."""
- return self._cursor_info
-
- @property
- def highlight(self):
- """Gets/sets the highlight info. Delegates to VimHighlightInfo."""
- return self._highlight_info
-
- def match(self, group_name, priority, positions):
+ @staticmethod
+ def match(group_name, priority, positions):
"""Set the match informations.
Args:
@@ -517,86 +572,53 @@ class VimInfo(object):
priority: Priority for the vim function matchadd().
positions: List of row-column position.
"""
- last_id = self.var['shared_vim_' + group_name]
+ last_id = VimInfo.var[VARNAMES.PREFIX + group_name]
if last_id is not None and last_id > 0:
ret = vim.eval('matchdelete(%d)' % int(last_id))
- del self.var['shared_vim_' + group_name]
+ del VimInfo.var[VARNAMES.PREFIX + group_name]
if positions:
rcs = [(rc[0] + 1, rc[1] + 1) for rc in positions]
patterns = '\\|'.join(['\\%%%dl\\%%%dc' % rc for rc in rcs])
mid = int(vim.eval("matchadd('%s', '%s', %d)" %
(group_name, patterns, priority)))
if mid != -1:
- self.var['shared_vim_' + group_name] = mid
-
- @property
- def var(self):
- """Gets/sets the var information. Delegates to VimVarInfo."""
- return self._var_info
-
- def rowlen(self, row):
- """Gets the length of a specified row.
+ VimInfo.var[VARNAMES.PREFIX + group_name] = mid
- Args:
- row: The specified line row.
-
- Return:
- Length of that row.
- """
- prev = 0 if row == 0 else self._text_num_sum[row - 1]
- return self._text_num_sum[row] - prev - 1
-
- def num_to_rc(self, num, rmin=0):
- """Transforms byte position to row-column cursor position.
-
- Args:
- num: byte cursor position.
-
- Return:
- List of row-column position.
- """
- row = bisect.bisect_right(self._text_num_sum, num, lo=rmin)
- col = num - (0 if row == 0 else self._text_num_sum[row - 1])
- return (row, col)
+ @staticmethod
+ def transform_to_py(data):
+ """Transforms the data to python's data type if needs.
- def nums_to_rcs(self, nums):
- """Transforms list of sorted byte positions.
+ In python, we always use unicode(python2)/str(python3) instead of bytes.
Args:
- nums: list of byte cursor positions.
+ data: The data to be transform.
Return:
- List of row-column positions.
+ Data which are transformed.
"""
- ret = []
- last_r = 0
- for num in nums:
- my_rc = self.num_to_rc(num, rmin=last_r)
- ret += [my_rc]
- last_r = my_rc[0]
- return ret
+ return (data if not isinstance(data, bytes)
+ else data.decode(VimInfo.ENCODING))
- def rc_to_num(self, rc):
- """Transforms row-column cursor position to bytes position.
+ @staticmethod
+ def transform_to_vim(data):
+ """Transforms the data to vim's data type if needs.
Args:
- rc: Row-column cursor position.
+ data: The data to be transform.
Return:
- byte position.
+ Data which are transformed.
"""
- return rc[1] + (self._text_num_sum[rc[0] - 1] if rc[0] > 0 else 0)
+ return (data if not isinstance(data, unicode)
+ else data.encode(VimInfo.ENCODING))
- def _calc_text_num_sum(self, lines):
- """Calculates the sum bytes of each line.
- Args:
- lines: Lines of text.
- """
- self._text_num_sum, pre = [], 0
- for index in range(len(lines)):
- self._text_num_sum += [pre + len(lines[index]) + 1]
- pre += len(lines[index]) + 1
+class VimInfo(six.with_metaclass(VimInfoMeta, object)):
+ """An interface for accessing the vim's vars, buffer, cursors, etc."""
+ @staticmethod
+ def init():
+ """Initializes some settings."""
+ VimInfo.cursors.update_text_lines()
class TCPConnection(object):
@@ -612,7 +634,8 @@ class TCPConnection(object):
conn: TCP-connection.
"""
self._conn = conn
- self._conn.settimeout(TIMEOUT)
+ self._conn.settimeout(
+ VimInfo.var.get(VARNAMES.TIMEOUT, DEFAULT_TIMEOUT))
def send(self, data):
"""Sends the data until timeout or the socket closed.
@@ -655,16 +678,12 @@ class TCPClient(object):
Attributes:
_sock: Connection.
"""
- def __init__(self, vim_info):
- """Constructor, automatically connects to the server.
-
- Args:
- vim_info: An instane of VimInfo.
- """
+ def __init__(self):
+ """Constructor, automatically connects to the server."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect((vim_info.var.shared_vim_server_name,
- vim_info.var.shared_vim_port))
+ sock.connect((VimInfo.var[VARNAMES.SERVER_NAME],
+ VimInfo.var[VARNAMES.SERVER_PORT]))
self._sock = TCPConnection(sock)
except TypeError as e:
raise TCPClientError('Cannot connect to server: %r' % e)
@@ -691,73 +710,67 @@ class TCPClient(object):
self._sock.close()
-def get_my_info(vim_info):
+def get_my_info():
"""Gets my information for server.
- Args:
- vim_info: An instance of VimInfo.
-
Return:
The information for server.
"""
return {
- _JSON_TOKEN.IDENTITY : vim_info.var.shared_vim_identity,
- _JSON_TOKEN.INIT : vim_info.var.shared_vim_init,
- _JSON_TOKEN.MODE : vim_info.mode,
- _JSON_TOKEN.CURSORS : {
- CURSOR_MARK.CURRENT : vim_info.cursors[CURSOR_MARK.CURRENT],
- CURSOR_MARK.V : vim_info.cursors[CURSOR_MARK.V],
+ JSON_TOKEN.IDENTITY : VimInfo.var[VARNAMES.IDENTITY],
+ JSON_TOKEN.INIT : VimInfo.var[VARNAMES.INIT],
+ JSON_TOKEN.MODE : VimInfo.mode,
+ JSON_TOKEN.CURSORS : {
+ CURSOR_MARK.CURRENT : VimInfo.cursors[CURSOR_MARK.CURRENT],
+ CURSOR_MARK.V : VimInfo.cursors[CURSOR_MARK.V],
},
- _JSON_TOKEN.TEXT : vim_info.text,
+ JSON_TOKEN.TEXT : VimInfo.text,
}
-def set_my_info(vim_info, json_info):
+def set_my_info(json_info):
"""Sets my information gived by server.
Args:
- vim_info: An instance of VimInfo.
json_info: JSON information gived by server.
"""
- vim_info.text = json_info[_JSON_TOKEN.TEXT]
- mode = json_info[_JSON_TOKEN.MODE]
- vim_info.mode = mode
+ VimInfo.text = json_info[JSON_TOKEN.TEXT]
+ mode = json_info[JSON_TOKEN.MODE]
+ VimInfo.mode = mode
if mode in (MODE.VISUAL, MODE.BLOCK_VISUAL, MODE.LINE_VISUAL):
- old_mode, vim_info.mode = mode, MODE.NORMAL
- vim_info.cursors[CURSOR_MARK.V] = \
- json_info[_JSON_TOKEN.CURSORS][CURSOR_MARK.V]
- vim_info.mode = old_mode
- vim_info.cursors[CURSOR_MARK.CURRENT] = \
- json_info[_JSON_TOKEN.CURSORS][CURSOR_MARK.CURRENT]
+ old_mode, VimInfo.mode = mode, MODE.NORMAL
+ VimInfo.cursors[CURSOR_MARK.V] = \
+ json_info[JSON_TOKEN.CURSORS][CURSOR_MARK.V]
+ VimInfo.mode = old_mode
+ VimInfo.cursors[CURSOR_MARK.CURRENT] = \
+ json_info[JSON_TOKEN.CURSORS][CURSOR_MARK.CURRENT]
-def set_others_info(vim_info, json_info):
+def set_others_info(json_info):
"""Sets the informations about other user.
Args:
- vim_info: An instance of VimInfo.
json_info: JSON information gived by server.
"""
- users = json_info[_JSON_TOKEN.OTHERS]
- vim_info.highlight.reset([user[_JSON_TOKEN.NICKNAME] for user in users])
+ users = json_info[JSON_TOKEN.OTHERS]
+ VimInfo.highlight.reset([user[JSON_TOKEN.NICKNAME] for user in users])
for user in users:
- name, mode = user[_JSON_TOKEN.NICKNAME], user[_JSON_TOKEN.MODE]
- cursors = user[_JSON_TOKEN.CURSORS]
- curr_rc = vim_info.num_to_rc(cursors[CURSOR_MARK.CURRENT])
- vim_info.highlight[name].set_mode_cursor(mode, curr_rc)
+ name, mode = user[JSON_TOKEN.NICKNAME], user[JSON_TOKEN.MODE]
+ cursors = user[JSON_TOKEN.CURSORS]
+ curr_rc = VimInfo.cursors.num_to_rc(cursors[CURSOR_MARK.CURRENT])
+ VimInfo.highlight[name].set_mode_cursor(mode, curr_rc)
if mode in (MODE.VISUAL, MODE.LINE_VISUAL, MODE.BLOCK_VISUAL):
- last_rc = vim_info.num_to_rc(cursors[CURSOR_MARK.V])
+ last_rc = VimInfo.cursors.num_to_rc(cursors[CURSOR_MARK.V])
if last_rc[0] > curr_rc[0] or \
- (last_rc[0] == curr_rc[0] and last_rc[1] > curr_rc[1]):
+ (last_rc[0] == curr_rc[0] and last_rc[1] > curr_rc[1]):
last_rc, curr_rc = curr_rc, last_rc
- set_other_visual(vim_info, name, mode, last_rc, curr_rc)
- vim_info.highlight.render()
+ set_other_visual(VimInfo, name, mode, last_rc, curr_rc)
+ VimInfo.highlight.render()
-def set_other_visual(vim_info, name, mode, beg, end):
+def set_other_visual(name, mode, beg, end):
"""Sets the other user's visual block.
Args:
- vim_info: An instance of VimInfo.
name: Name of this user.
mode: Mode of this user.
beg: The first row-column position of the range.
@@ -766,47 +779,52 @@ def set_other_visual(vim_info, name, mode, beg, end):
if mode == MODE.VISUAL:
for row in range(beg[0], end[0] + 1):
first = 0 if row != beg[0] else beg[1]
- last = vim_info.rowlen(row) if row != end[0] else end[1]
+ last = len(VimInfo.lines[row]) if row != end[0] else end[1]
for col in range(first, last + 1):
- vim_info.highlight[name].add_visual((row, col))
+ VimInfo.highlight[name].add_visual((row, col))
elif mode == MODE.LINE_VISUAL:
for row in range(beg[0], end[0] + 1):
- for col in range(0, vim_info.rowlen(row)):
- vim_info.highlight[name].add_visual((row, col))
+ for col in range(0, len(VimInfo.lines[row])):
+ VimInfo.highlight[name].add_visual((row, col))
elif mode == MODE.BLOCK_VISUAL:
left, right = min([beg[1], end[1]]), max([beg[1], end[1]])
for row in range(beg[0], end[0] + 1):
for col in range(left, right + 1):
- vim_info.highlight[name].add_visual((row, col))
+ VimInfo.highlight[name].add_visual((row, col))
-def setup_default_value(info):
- """Setups the default from the gived vim_info.
-
- Args:
- vim_info: An instance of VimInfo.
- """
- TIMEOUT = info.var.shared_vim_timeout
- NUM_GROUPS = info.var.shared_vim_num_groups
+def sync():
+ """Sync with the server."""
+ conn = TCPClient()
+ response = conn.request(get_my_info())
+ conn.close()
+ if JSON_TOKEN.ERROR in response:
+ raise Exception(response[JSON_TOKEN.ERROR])
+ set_my_info(response)
+ set_others_info(response)
+
+
+def disconnect():
+ """Disconnects with the server."""
+ conn = TCPClient()
+ conn.request({JSON_TOKEN.BYE : True,
+ JSON_TOKEN.IDENTITY : VimInfo.var[VARNAMES.IDENTITY]})
+ conn.close()
+ print('bye')
def main():
+ VimInfo.init()
"""Main function."""
try:
- vim_info = VimInfo()
- setup_default_value(vim_info)
- conn = TCPClient(vim_info)
- response = conn.request(get_my_info(vim_info))
- conn.close()
- if _JSON_TOKEN.ERROR in response:
- raise Exception(response[_JSON_TOKEN.ERROR])
- set_my_info(vim_info, response)
- set_others_info(vim_info, response)
+ if VimInfo.var[VARNAMES.GOAL] == GOALS.SYNC:
+ sync()
+ elif VimInfo.var[VARNAMES.GOAL] == GOALS.DISCONNECT:
+ disconnect()
except TCPClientError as e:
print(e)
except Exception as e:
- import sys
- print('?? %r' % e)
+ print('[%r] %r' % (sys.exc_info()[2].tb_lineno, e))
main()
EOF