├── .gitignore ├── LICENSE ├── README.md ├── README_cn.md ├── demo.gif ├── doc └── vim-calc.txt └── plugin ├── calc.py └── vim-calc.vim /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # pipenv 86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 88 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 89 | # install all needed dependencies. 90 | #Pipfile.lock 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # Environments 99 | .env 100 | .venv 101 | env/ 102 | venv/ 103 | ENV/ 104 | env.bak/ 105 | venv.bak/ 106 | 107 | # Spyder project settings 108 | .spyderproject 109 | .spyproject 110 | 111 | # Rope project settings 112 | .ropeproject 113 | 114 | # mkdocs documentation 115 | /site 116 | 117 | # mypy 118 | .mypy_cache/ 119 | .dmypy.json 120 | dmypy.json 121 | 122 | # Pyre type checker 123 | .pyre/ 124 | 125 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 David Chen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## vim-calc: A Calculator in Vim 2 | 3 | [中文版](./README_cn.md) 4 | 5 | #### Introduction 6 | `vim-calc` is a fully functional calculator that you might feel missing in `Vim`. 7 | 8 | ![Demo](demo.gif) 9 | 10 | 11 | #### Usage 12 | Do **`:call Calc()`** inside vim to calculate the math equation in the current line (`vim-calc` will tell you if there's any error in terms of the equation within the current line) 13 | 14 | Or, if you want a key-binding, add this to your `vimrc`/`init.vim`: 15 | ```vim 16 | nnoremap a :call Calc() 17 | ``` 18 | 19 | Now, you can press `LEADER` and `a` to calculate! 20 | 21 | #### Installation 22 | Install `vim-calc` with [vim-plug](https://github.com/junegunn/vim-plug): 23 | ```vim 24 | Plug 'theniceboy/vim-calc' 25 | ``` 26 | 27 | #### Todos 28 | - [ ] Convert equation to `latex` form 29 | 30 | #### Contributing 31 | This plugin is **under development** so if you found a bug or have a suggestion, please **DO NOT HESITATE** to [file an issue](https://github.com/theniceboy/vim-calc/issues/new), submit a Pull Request, or email me! 32 | 33 | #### License 34 | MIT 35 | -------------------------------------------------------------------------------- /README_cn.md: -------------------------------------------------------------------------------- 1 | ## vim-calc: 一个在 Vim 中的计算器 2 | 3 | [English Ver.](./README.md) 4 | 5 | #### 介绍 6 | `vim-calc` 是一款在 `Vim` 下使用的计算器 7 | 8 | ![Demo](demo.gif) 9 | 10 | 11 | #### 使用 12 | 在 Vim 中执行 **`:call Calc()`** 来计算在当前行下的数学公式 (`vim-calc` 会将错误信息打印在状态栏下方) 13 | 14 | 或者, 如果你想绑定快捷键来计算数学公式的话, 将以下行加入到你的 `vimrc`/`init.vim`: 15 | ```vim 16 | nnoremap a :call Calc() 17 | ``` 18 | 19 | 现在, 你可以按下 `LEADER` 键和 `a` 键来计算 20 | 21 | #### 安装 22 | 用 [vim-plug](https://github.com/junegunn/vim-plug) 安装 `vim-calc`: 23 | ```vim 24 | Plug 'theniceboy/vim-calc' 25 | ``` 26 | 27 | #### Todos 28 | The part is temp part so i don't will translate it. 29 | 30 | - [ ] Convert equation to `latex` form 31 | 32 | #### 贡献 33 | 此插件正处于 **开发阶段**, 所以, 如果你发现了 BUG, 请不要犹豫地[创建 Issues](https://github.com/theniceboy/vim-calc/issues/new), 提交一个拉取请求, 或者给我发邮件! 34 | 35 | #### 协议 36 | MIT 37 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theniceboy/vim-calc/fdae42d412f5835e2c3341d87b0be85b51f1ecc5/demo.gif -------------------------------------------------------------------------------- /doc/vim-calc.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /plugin/calc.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | # s = input() 5 | # s = "(2+4)5^3" 6 | # s = "pi*((1-3)^4-15+((9-8)))" 7 | # s = "sqrt(8*sin(pi/6)+12)" 8 | # s = "(sqrt(4+6pi)+3)^4/5+ln 4-3" 9 | # s = "3.1415926/p" 10 | # s = "(ln e^3)4" 11 | s = sys.argv[1] 12 | s = s + '_' 13 | 14 | # s = "12+67*1235(345-34)^2/9 " 15 | # s = "1/2 " 16 | # s = "sin 12 + 5" 17 | 18 | s_len = 0 19 | s_start = 0 20 | s_end = 0 21 | s_should_end = False 22 | 23 | # __DEBUG_PAUSE = True 24 | # __DEBUG_OUTPUT = True 25 | 26 | __DEBUG_PAUSE = False 27 | __DEBUG_OUTPUT = False 28 | 29 | eID = 0 30 | 31 | 32 | class MathSum(object): 33 | def __init__(self): 34 | global eID 35 | self.id = eID 36 | eID += 1 37 | self.pairChar = "" 38 | self.children = [] 39 | self.result = 0 40 | self.origin = None 41 | self.power = None 42 | self.dividing = False 43 | 44 | 45 | class MathProduct(object): 46 | def __init__(self): 47 | global eID 48 | self.id = eID 49 | eID += 1 50 | self.modifier = 1 51 | self.children = [] 52 | self.origin = None 53 | self.power = None 54 | 55 | 56 | class MathElement(object): 57 | def __init__(self): 58 | global eID 59 | self.id = eID 60 | eID += 1 61 | self.contentString = "" 62 | self.contentNumber = 0 63 | self.origin = None 64 | self.power = None 65 | self.powerModifier = 1 66 | self.children = [] 67 | self.dividing = False 68 | 69 | def expandExp(root, indent): 70 | itemOriginID = -1 71 | if root.origin != None: 72 | itemOriginID = root.origin.id 73 | if type(root) == MathSum: 74 | print(' '*indent + "Sum (id: " + str(root.id) + "), isDividing =", root.dividing, ", type: " + root.pairChar + " origin: " + str(itemOriginID)) 75 | elif type(root) == MathProduct: 76 | print(' '*indent + "Product (id: " + str(root.id) + "), modifier: " + str(root.modifier) + " origin: " + str(itemOriginID)) 77 | elif type(root) == MathElement: 78 | print(' '*indent + "Element (id: " + str(root.id) + "): [ " + root.contentString + " ], isDividing =", root.dividing, " origin: " + str(itemOriginID)) 79 | if root.power != None: 80 | print(' '*indent + ", with Power {") 81 | expandExp(root.power, indent + 3) 82 | print(' '*indent + "}") 83 | for child in root.children: 84 | expandExp(child, indent + 3) 85 | 86 | 87 | ansStr = "" 88 | 89 | 90 | def printExp(root): 91 | global ansStr 92 | ansStr = "" 93 | _printExp(root) 94 | return ansStr 95 | 96 | def _printExp(root): 97 | global ansStr 98 | if type(root) == MathSum: 99 | isFirstItem = True 100 | for child in root.children: 101 | if isFirstItem: 102 | if child.modifier == -1: 103 | ansStr += "-" 104 | else: 105 | ansStr += "+" if child.modifier == 1 else "-" 106 | isFirstItem = False 107 | _printExp(child) 108 | if root.pairChar == "(": 109 | ansStr += ")" 110 | elif type(root) == MathProduct: 111 | isFirstItem = True 112 | for child in root.children: 113 | if isFirstItem == False: 114 | ansStr += "/" if child.dividing == 1 else "*" 115 | isFirstItem = False 116 | _printExp(child) 117 | elif type(root) == MathElement: 118 | if root.contentString == '(': 119 | ansStr += '(' 120 | _printExp(root.children[0]) 121 | ansStr += ')' 122 | else: 123 | ansStr += root.contentString 124 | if len(root.children) > 0: 125 | try: 126 | if root.children[0].contentString != "(": 127 | ansStr += " " 128 | except: 129 | ansStr += " " 130 | _printExp(root.children[0]) 131 | if root.power != None: 132 | ansStr += "^" 133 | _printExp(root.power) 134 | 135 | scientificNumbers = {'pi': math.pi, \ 136 | 'e' : math.e} 137 | def isScientific(loc): 138 | global s 139 | str = s[loc:loc+4].lower().ljust(4, '-') 140 | if str == 'sqrt': 141 | return (True, str, True) 142 | str = str[:-1] 143 | if str == 'sin' or \ 144 | str == 'cos' or \ 145 | str == 'tan' or \ 146 | str == 'log': 147 | return (True, str, True) 148 | str = str[:-1] 149 | if str == 'ln': 150 | return (True, str, True) 151 | if str == 'pi': 152 | return (True, str, False) 153 | str = str[:-1] 154 | if str == 'e': 155 | return (True, str, False) 156 | return (False, '', False) 157 | 158 | def convertMathString(): 159 | global s, s_len, s_start, s_end 160 | # print(s) 161 | s_len = len(s) 162 | # print(s_len) 163 | root = MathSum() 164 | buildSum(root, 0, "", 0) 165 | return root 166 | 167 | 168 | def buildSum(obj, startLoc, pairChar, level): 169 | global s, s_len, s_should_end 170 | loc = startLoc 171 | obj.pairChar = pairChar 172 | while not s_should_end: 173 | if __DEBUG_OUTPUT: 174 | print("level:", level, "summing, loc:", loc, s[loc]) 175 | if __DEBUG_PAUSE: 176 | _ = input() 177 | print("sum pause inputed") 178 | 179 | if s[loc] == '_': 180 | return loc 181 | elif s[loc] == ' ': 182 | loc += 1 183 | continue 184 | if loc > s_len - 1: 185 | break 186 | newProduct = MathProduct() 187 | newProduct.origin = obj 188 | obj.children.append(newProduct) 189 | 190 | if __DEBUG_OUTPUT: 191 | print("level:", level, "___add child, loc:", loc, obj.children) 192 | 193 | if s[loc] == '-': 194 | newProduct.modifier = -1 195 | loc += 1 196 | elif s[loc] == '+': 197 | loc += 1 198 | 199 | if __DEBUG_OUTPUT: 200 | print("level:", level, "loc:", loc, "will_build_product") 201 | 202 | loc = buildProduct(newProduct, loc, level+1) 203 | 204 | if s[loc] == pairChar: 205 | loc = loc + 1 206 | if __DEBUG_OUTPUT: 207 | print("level:", level, "End of Sum", "loc:", loc) 208 | return loc 209 | 210 | if pairChar == 'oneProductAllowed': 211 | break 212 | 213 | return loc 214 | 215 | 216 | def buildProduct(obj, startLoc, level): 217 | global s, s_len, s_should_end, errors 218 | loc = startLoc 219 | isDividing = False 220 | while not s_should_end: 221 | if __DEBUG_OUTPUT: 222 | print("level:", level, "producting, loc:", loc, s[loc]) 223 | if __DEBUG_PAUSE: 224 | _ = input() 225 | print("product pause inputed") 226 | if s[loc] == '_': 227 | return loc 228 | if s[loc] == ' ': 229 | loc += 1 230 | continue 231 | if loc >= s_len: 232 | break 233 | elif s[loc] == '+' or s[loc] == '-': 234 | break 235 | elif s[loc].isnumeric() or s[loc] == '.': 236 | newElement = MathElement() 237 | newElement.origin = obj 238 | newElement.dividing = isDividing 239 | obj.children.append(newElement) 240 | loc = buildElement(newElement, loc, level+1) 241 | elif s[loc].isalpha(): 242 | scientific = isScientific(loc) 243 | if scientific[0]: 244 | newElement = MathElement() 245 | newElement.origin = obj 246 | newElement.dividing = isDividing 247 | obj.children.append(newElement) 248 | loc = buildElement(newElement, loc, level=level+1) 249 | else: 250 | errors.append("Unrecognized symbol at location " + str(loc)) 251 | s_should_end = True 252 | elif s[loc] == '*': 253 | isDividing = False 254 | loc += 1 255 | elif s[loc] == '/': 256 | isDividing = True 257 | loc += 1 258 | elif s[loc] == '(': 259 | newElement = MathElement() 260 | newElement.origin = obj 261 | newElement.dividing = isDividing 262 | obj.children.append(newElement) 263 | loc = buildElement(newElement, loc, level=level+1) 264 | elif s[loc] == ')': 265 | if __DEBUG_OUTPUT: 266 | print("level:", level, "end of sum", "loc:", loc) 267 | return loc 268 | else: 269 | errors.append("Unrecognized symbol at location " + str(loc)) 270 | s_should_end = True 271 | 272 | return loc 273 | 274 | 275 | def buildElement(obj, startLoc, level): 276 | global s, s_len, s_should_end, errors 277 | loc = startLoc 278 | isElement = False 279 | scientific = isScientific(loc) 280 | if __DEBUG_OUTPUT: 281 | print("level:", level, "building element, loc:", loc, s[loc], "science:", scientific) 282 | if __DEBUG_PAUSE: 283 | _ = input() 284 | print("element pause inputed") 285 | if s[loc] == '(': 286 | obj.contentString = '(' 287 | newSum = MathSum() 288 | newSum.origin = obj 289 | obj.children.append(newSum) 290 | loc = buildSum(newSum, loc+1, ')', level=level+1) 291 | elif s[loc].isnumeric(): 292 | hasDot = False 293 | while s[loc].isnumeric() or s[loc] == '.': 294 | if s[loc] == '.': 295 | if hasDot: 296 | errors.append("Multiple dots in one number at location " + str(loc)) 297 | s_should_end = True 298 | else: 299 | hasDot = True 300 | loc += 1 301 | if loc >= s_len: 302 | break 303 | obj.contentString = s[startLoc:loc] 304 | obj.contentNumber = float(obj.contentString) 305 | elif scientific[0]: 306 | loc += len(scientific[1]) 307 | obj.contentString = scientific[1] 308 | if scientific[2]: 309 | if s[loc] == '(': 310 | newElement = MathElement() 311 | newElement.origin = obj 312 | obj.children.append(newElement) 313 | loc = buildElement(newElement, loc, level=level+1) 314 | else: 315 | newProduct = MathProduct() 316 | newProduct.origin = obj 317 | obj.children.append(newProduct) 318 | loc = buildProduct(newProduct, loc, level=level+1) 319 | else: 320 | obj.contentNumber = scientificNumbers[scientific[1]] 321 | else: 322 | errors.append("Missing math element at location: " + str(loc)) 323 | s_should_end = False 324 | 325 | if s[loc] == '_': 326 | return loc 327 | if s[loc] == '^': 328 | loc += 1 329 | powerModifier = 1 330 | if s[loc] == '-': 331 | powerModifier = -1 332 | loc += 1 333 | newElement = MathElement() 334 | newElement.origin = obj 335 | obj.power = newElement 336 | obj.powerModifier = powerModifier 337 | loc = buildElement(newElement, loc, level=level+1) 338 | 339 | return loc 340 | 341 | 342 | errors = [] 343 | def calcRoot (root): 344 | # print(root.id, root) 345 | # _ = input() 346 | global errors 347 | if type(root) == MathSum: 348 | ans = 0 349 | for child in root.children: 350 | ans = ans + child.modifier * calcRoot(child) 351 | return ans 352 | elif type(root) == MathProduct: 353 | ans = None 354 | for child in root.children: 355 | if ans == None: 356 | ans = calcRoot(child) 357 | else: 358 | if child.dividing: 359 | dv = calcRoot(child) 360 | if dv == 0: 361 | errors.append("Dividing 0 at id=" + str(root.id)) 362 | return 1 363 | else: 364 | ans = ans / dv 365 | else: 366 | ans = ans * calcRoot(child) 367 | return ans 368 | elif type(root) == MathElement: 369 | ans = root.contentNumber 370 | child_ans = 0 371 | rootstr = root.contentString 372 | if len(root.children) > 0: 373 | child_ans = calcRoot(root.children[0]) 374 | if rootstr == '(': 375 | ans = child_ans 376 | if rootstr == 'sin': 377 | ans = math.sin(child_ans) 378 | elif rootstr == 'cos': 379 | ans = math.cos(child_ans) 380 | elif rootstr == 'tan': 381 | ans = math.tan(child_ans) 382 | elif rootstr == 'ln': 383 | ans = math.log(child_ans) 384 | # elif rootstr == 'log2': 385 | # ans = math.log2(child_ans) 386 | elif rootstr == 'log': 387 | ans = math.log10(child_ans) 388 | elif rootstr == 'sqrt': 389 | ans = math.sqrt(child_ans) 390 | if root.power != None: 391 | return ans ** calcRoot(root.power) 392 | return ans 393 | 394 | 395 | # mathString = input().strip() 396 | expRoot = convertMathString() 397 | 398 | # print(printExp(expRoot)) 399 | # expandExp(expRoot, 0) 400 | 401 | if len(errors) > 0: 402 | print(0, '\\', errors[0]) 403 | else: 404 | ans = calcRoot(expRoot) 405 | if len(errors) > 0: 406 | print(0, '\\', errors[0]) 407 | else: 408 | printExp(expRoot) 409 | print(1, '\\', ans, '\\', ansStr) 410 | # print(errors) 411 | # printExp(expRoot) 412 | 413 | -------------------------------------------------------------------------------- /plugin/vim-calc.vim: -------------------------------------------------------------------------------- 1 | let s:path = fnamemodify(resolve(expand(':p')), ':h') . '/calc.py' 2 | function Calc() 3 | let s = getline(".") 4 | let calc_str = "python3 " . s:path . " \"" . s . "\"" 5 | let result_str = trim(system(calc_str)) 6 | let result_array = split(result_str, '\') 7 | let result = "" 8 | let done = 0 9 | let i = 0 10 | while !done 11 | let result_array[i] = trim(result_array[i]) 12 | let i += 1 13 | if i >= len(result_array) 14 | break 15 | endif 16 | endwhile 17 | if result_array[0] == "0" 18 | echom "Error: " . result_array[1] 19 | elseif result_array[0] == "1" 20 | echom result_array[2] . " = " . result_array[1] 21 | else 22 | echom "Script Error, contact the developer... or just figure it out!" 23 | endif 24 | endfunc 25 | 26 | 27 | --------------------------------------------------------------------------------