├── .github └── workflows │ ├── Test.yml │ └── codeql-analysis.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md └── cot /.github/workflows/Test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | name: Lint Python code 8 | runs-on: macOS-latest 9 | strategy: 10 | matrix: 11 | python-version: ['3.x'] 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Set up Python ${{ matrix.python-version }} 15 | uses: actions/setup-python@v2 16 | with: 17 | python-version: ${{ matrix.python-version }} 18 | - name: Install modules 19 | run: | 20 | pip install pycodestyle 21 | - name: Lint 22 | run: | 23 | pycodestyle cot 24 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ develop, master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ develop ] 20 | schedule: 21 | - cron: '29 15 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'python' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v2 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v1 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 52 | 53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 54 | # If this step fails, then you should remove it and run the build manually (see below) 55 | - name: Autobuild 56 | uses: github/codeql-action/autobuild@v1 57 | 58 | # ℹ️ Command-line programs to run using the OS shell. 59 | # 📚 https://git.io/JvXDl 60 | 61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 62 | # and modify them (or add more) to build your code if your project 63 | # uses a compiled language 64 | 65 | #- run: | 66 | # make bootstrap 67 | # make release 68 | 69 | - name: Perform CodeQL Analysis 70 | uses: github/codeql-action/analyze@v1 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # macOS 2 | .DS_Store 3 | 4 | # Swift Package Manager 5 | .build 6 | .swiftpm 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | Change Log 3 | ========================== 4 | 5 | 2.12.0 6 | -------------------------- 7 | 8 | - Enable opening directories. 9 | 10 | 11 | 2.11.0 12 | -------------------------- 13 | 14 | - Ignore piped text if a file to open is specified. 15 | 16 | 17 | 2.10.0 18 | -------------------------- 19 | 20 | - Add `--syntax` (`-s`) option to set desired syntax to the documents just opened. 21 | 22 | 23 | 2.9.2 24 | -------------------------- 25 | 26 | - Invoke `python3` instead of `python` to run `cot` command itself. 27 | 28 | 29 | 2.9.1 30 | -------------------------- 31 | 32 | - Let `cot` script use any Python in the system. 33 | 34 | 35 | 2.9.0 36 | -------------------------- 37 | 38 | - Now cot command requres CotEditor 4.1.0 or later. 39 | - Fix to work also with Python 3. 40 | 41 | 42 | 2.8.0 43 | -------------------------- 44 | 45 | - Enable reading large piped text. 46 | 47 | 48 | 2.7.4 49 | -------------------------- 50 | 51 | - Fix an issue where stack trace displayed when using `--wait` option with some clients other than Terminal.app. 52 | - Fix an issue where `--column` could misplace the insertion point when a negative number was given. 53 | 54 | 55 | 2.7.0 56 | -------------------------- 57 | 58 | - Change `--column` count from 0-based to 1-based. 59 | - Fix an issue where the last empty line was ignoed when specifying the cursor position with `--line` option. 60 | - Improve error message when failed. 61 | 62 | 63 | 2.6.2 64 | -------------------------- 65 | 66 | - Fix an issue where `cot` command failed to open paths or stdin containing backslash character. 67 | 68 | 69 | 2.6.1 70 | -------------------------- 71 | 72 | - Fix an issue where `cot` command failed if the client application is non-scriptable. 73 | 74 | 75 | 2.6.0 76 | -------------------------- 77 | 78 | - Bring the window that called `cot` to the front after `--wait`. 79 | 80 | 81 | 2.5.3 82 | -------------------------- 83 | 84 | - Avoid creating an extra blank document if `cot` command creates new document. 85 | - Fix an issue where launching application with `--background` option didn't make CotEditor visible. 86 | 87 | 88 | 2.5.2 89 | -------------------------- 90 | 91 | - Fix a possible hang under some specific environments. 92 | 93 | 94 | 2.5.1 95 | -------------------------- 96 | 97 | - Fix an issue where file(s) cannot be opened if the default Python is Python 3. 98 | 99 | 100 | 2.5.0 101 | -------------------------- 102 | 103 | - Enable using wildcard for file path argument. 104 | 105 | 106 | 2.4.1 107 | -------------------------- 108 | 109 | - Fix an issue where creating new blank file could fail. 110 | 111 | 112 | 2.4.0 113 | -------------------------- 114 | 115 | - Create a new file if a non-existent file path is passed in with `--new` option. 116 | 117 | 118 | 2.3.1 119 | -------------------------- 120 | 121 | - Fix an issue where `--line` option didn't work under specific environments. 122 | - Fix an issue where command could failed if the default Python is Python3. 123 | - Fix an issue where `--line` and `--column` options didn't move cursor to the desired location if file has blank lines at the end. 124 | 125 | 126 | 2.3.0 127 | -------------------------- 128 | 129 | - Add `--wait` (`-w`) option to wait until a newly opened window closes. 130 | - Optimize command performance. 131 | - Fix an issue where command cannot open file whose path includes non-ascii character. 132 | 133 | 134 | 2.2.1 135 | -------------------------- 136 | 137 | - Open symbolic link target rather than the link itself. 138 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | `cot` command-line tool 3 | ============================= 4 | 5 | > [!IMPORTANT] 6 | > This repository is no more maintained. The `cot` command file has been moved to the [CotEditor repository](https://github.com/coteditor/CotEditor) since CotEditor 5.0.2. 7 | 8 | 9 | [![Test Status](https://github.com/coteditor/cot/workflows/Test/badge.svg)](https://github.com/coteditor/cot/actions) 10 | 11 | The command-line helper tool for [CotEditor](https://coteditor.com). 12 | 13 | 14 | License 15 | ----------------------------- 16 | © 2015-2024 1024jp. 17 | 18 | The source code is distributed under the terms of the __Apache License, Version 2.0__. See the [LICENSE](LICENSE) for details. 19 | -------------------------------------------------------------------------------- /cot: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | cot 4 | 5 | CotEditor 6 | https://coteditor.com 7 | 8 | Created by 1024jp on 2015-08-12. 9 | 10 | ------------------------------------------------------------------------------ 11 | 12 | © 2015-2024 1024jp 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | https://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | 26 | """ 27 | 28 | import argparse 29 | import errno 30 | import os 31 | import sys 32 | import time 33 | from subprocess import Popen, PIPE, CalledProcessError 34 | 35 | 36 | # meta data 37 | __version__ = '2.10.0' 38 | __description__ = 'command-line utility for CotEditor.' 39 | 40 | 41 | # constants 42 | APPLICATION_NAME = 'CotEditor' 43 | WAIT_INTERVAL = 1.0 44 | 45 | 46 | # MARK: Style 47 | 48 | class Style: 49 | """Style string for stdout/stderr. 50 | """ 51 | 52 | @staticmethod 53 | def bold(string): 54 | return '\033[1m' + string + '\033[0m' 55 | 56 | @staticmethod 57 | def warning(string): 58 | return '\033[31;1m' + string + '\033[0m' 59 | 60 | 61 | # MARK: Bundle 62 | 63 | def bundle_path(): 64 | """Return application path if this script is bundled in an application. 65 | 66 | Returns: 67 | path (str): Path to .app directory or None if not found. 68 | """ 69 | path = os.path.realpath(__file__) 70 | 71 | # find '.app' extension 72 | while path != '/': 73 | path = os.path.dirname(path) 74 | _, extension = os.path.splitext(path) 75 | if extension == '.app': 76 | return path 77 | 78 | return None 79 | 80 | 81 | # MARK: OSA Script 82 | 83 | def run_osascript(script, is_async=False): 84 | """Run osascript. 85 | 86 | Args: 87 | script (str): Osascript. 88 | is_async (bool): If need to wait for finish. 89 | Returns: 90 | result (str): Return value of the script. 91 | """ 92 | if is_async: 93 | script = 'ignoring application responses\n' + script + '\nend ignoring' 94 | 95 | p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE) 96 | stdout, stderr = p.communicate(script.encode('utf-8')) 97 | 98 | if p.returncode: 99 | raise CalledProcessError(p.returncode, script, stderr.decode('utf-8')) 100 | 101 | result = stdout.decode('utf-8') 102 | 103 | # strip the last line ending 104 | # -> Don't use `rstrip` since it removes multiple line endings. 105 | if result.endswith('\n'): 106 | result = result[:-1] 107 | 108 | return result 109 | 110 | 111 | class ScriptableApplication(object): 112 | """OSA-Scriptable macOS application object. 113 | """ 114 | 115 | def __init__(self, name): 116 | self.name = name 117 | 118 | def tell(self, script, is_async=False): 119 | """Tell OSA command to the application. 120 | 121 | Args: 122 | script (str): OSA command 123 | is_async (bool): If need to wait for finish. 124 | Returns: 125 | result (str): Return value of the script. 126 | """ 127 | script = 'tell app "{}" to {}'.format(self.name, script) 128 | try: 129 | return run_osascript(script, is_async) 130 | except CalledProcessError as error: 131 | self._attempt_recovery(error) 132 | raise error 133 | 134 | def launch(self, background=False): 135 | """Launch application. 136 | 137 | Args: 138 | background (bool): Open in background? 139 | """ 140 | if background: 141 | self.tell('launch') 142 | else: 143 | self.tell('activate') 144 | 145 | def open(self, path): 146 | """Open given file path in the application. 147 | 148 | Args: 149 | path (str): Path to file. 150 | """ 151 | path = path.replace('\\', '\\\\').replace('"', '\\"') 152 | self.tell('open POSIX file "{}"'.format(path), is_async=True) 153 | # -> Opening a file that is already opened in the application takes 154 | # somehow extremely long time. So, we don't wait. 155 | 156 | def tell_document(self, script, index=1): 157 | """Tell OSA command to a document of the application. 158 | 159 | Args: 160 | script (str): OSA command 161 | index (int): Index number of the document to handle (1-based). 162 | Returns: 163 | result (str): Return value of the script. 164 | """ 165 | return self.tell('tell document {} to {}'.format(index, script)) 166 | 167 | def window_id(self, index=1): 168 | """Get window identifier. 169 | 170 | Args: 171 | index (int): Index number of the window to get id (1-based). 172 | Returns: 173 | window_id (str): Identifier of document's window opened. 174 | """ 175 | try: 176 | return self.tell('id of window {}'.format(index)) 177 | except CalledProcessError: 178 | pass 179 | return None 180 | 181 | def window_exists(self, window_id): 182 | """Check if window exists. 183 | 184 | Args: 185 | window_id (str): identifier of window to check existence. 186 | Returns: 187 | result (bool): Window exists? 188 | """ 189 | script = '(first window whose id is {}) is visible'.format(window_id) 190 | result = None 191 | try: 192 | result = self.tell(script) 193 | except CalledProcessError: 194 | pass 195 | return result == 'true' 196 | 197 | def _attempt_recovery(self, error): 198 | """Attempt recovery from CalledProcessError. 199 | 200 | Args: 201 | error (CalledProcessError): Error via osascript. 202 | """ 203 | if '(-1743)' in error.output: 204 | # show recovery suggestion for authorization error with 205 | # Apple events in Mojave (and later) 206 | sys.stderr.write( 207 | Style.warning('Error') + ': ' 208 | 'User authorization required. ' 209 | 'To authorize cot command, select ' + 210 | Style.bold(self.name) + ' under your client application, ' 211 | 'such as Terminal, in ' + 212 | Style.bold('System Preferences') + ' > ' + 213 | Style.bold('Security & Privacy') + ' > ' + 214 | Style.bold('Privacy') + ' > ' + 215 | Style.bold('Automation') + '.\n' 216 | ) 217 | sys.exit(error.returncode) 218 | 219 | 220 | # MARK: Args Parse 221 | 222 | def parse_args(): 223 | """Parse command line arguments. 224 | 225 | Returns: 226 | Parsed args object. 227 | """ 228 | # create parser instance 229 | parser = argparse.ArgumentParser(description=__description__) 230 | 231 | # set positional argument 232 | parser.add_argument('files', 233 | type=str, 234 | metavar='FILE', 235 | nargs='*', # allow wildcard 236 | help="path to file to open" 237 | ) 238 | 239 | # set optional arguments 240 | parser.add_argument('-v', '--version', 241 | action='version', 242 | version=__version__ 243 | ) 244 | parser.add_argument('-w', '--wait', 245 | action='store_true', 246 | default=False, 247 | help="wait for opened file to be closed" 248 | ) 249 | parser.add_argument('-g', '--background', 250 | action='store_true', 251 | default=False, 252 | help="do not bring the application to the foreground" 253 | ) 254 | parser.add_argument('-n', '--new', 255 | action='store_true', 256 | default=False, 257 | help="create a new blank document" 258 | ) 259 | parser.add_argument('-s', '--syntax', 260 | type=str, 261 | help="set specific syntax to opened document" 262 | ) 263 | parser.add_argument('-l', '--line', 264 | type=int, 265 | help="jump to specific line in opened document" 266 | ) 267 | parser.add_argument('-c', '--column', 268 | type=int, 269 | help="jump to specific column in opened document" 270 | ) 271 | 272 | args = parser.parse_args() 273 | 274 | # create a flag specifying if create a new blank window or file 275 | args.new_window = args.new and not args.files 276 | 277 | # check file existence and create if needed 278 | if args.files: 279 | # strip symlink 280 | args.files = list(map(os.path.realpath, args.files)) 281 | # skip file check if file is directory 282 | if not args.new and os.path.isdir(args.files[0]): 283 | return args 284 | 285 | open_mode = 'r' 286 | if args.new and not os.path.exists(args.files[0]): 287 | open_mode = 'w' # overwrite mode to create new file 288 | # create directory if not exists yet 289 | filepath = args.files[0] 290 | dirpath = os.path.dirname(filepath) 291 | if dirpath: 292 | try: 293 | os.makedirs(dirpath) 294 | except OSError as err: # guard against race condition 295 | if err.errno != errno.EEXIST: 296 | parser.error("argument FILE: {}".format(err)) 297 | # check readability or create new one 298 | for path in args.files: 299 | try: 300 | open(path, open_mode).close() 301 | except IOError as err: 302 | parser.error("argument FILE: {}".format(err)) 303 | 304 | return args 305 | 306 | 307 | # MARK: - Main 308 | 309 | def main(args, stdin): 310 | # store the client app and window 311 | client = None 312 | client_window_id = None 313 | if args.wait: 314 | system = ScriptableApplication('System Events') 315 | client_name = system.tell('get path of application file of application' 316 | ' processes whose frontmost is true') 317 | 318 | client = ScriptableApplication(client_name) 319 | client_window_id = client.window_id() 320 | 321 | # find the app to call 322 | app_identifier = bundle_path() or APPLICATION_NAME 323 | app = ScriptableApplication(app_identifier) 324 | 325 | # create document (before launching app explicitly) 326 | # -> to avoid creating extra blank document 327 | document_count = 0 328 | if args.files: 329 | # open files 330 | for path in args.files: 331 | app.open(path) 332 | document_count = len(args.files) 333 | 334 | elif stdin: 335 | # new document with piped text 336 | sanitized_stdin = stdin.replace('\\', '\\\\').replace('"', '\\"') 337 | app.tell('make new document') 338 | app.tell_document('set contents to "{}"'.format(sanitized_stdin)) 339 | app.tell_document('set range of selection to {0, 0}') 340 | document_count = 1 341 | 342 | elif args.new_window: 343 | # new blank document 344 | app.tell('make new document') 345 | document_count = 1 346 | 347 | # launch 348 | app.launch(background=args.background) 349 | 350 | # set syntax 351 | if args.syntax is not None and document_count > 0: 352 | for index in range(document_count): 353 | app.tell_document('set coloring style to "{}"'.format(args.syntax), 354 | index + 1) 355 | 356 | if app.tell('number of documents') == '0': 357 | return 358 | 359 | # jump to location 360 | if args.line is not None or args.column is not None: 361 | app.tell_document('jump to line {} column {}'.format( 362 | args.line or 1, args.column or 0)) 363 | 364 | # wait for window close 365 | if args.wait and (len(args.files) == 1 or stdin or args.new_window): 366 | window_id = app.window_id() 367 | while app.window_exists(window_id): 368 | time.sleep(WAIT_INTERVAL) 369 | 370 | # raise client window to the front 371 | if client_window_id: 372 | client.tell('set index of window id {} to 1'.format( 373 | client_window_id)) 374 | try: 375 | client.tell('activate') 376 | except Exception: 377 | pass 378 | 379 | 380 | if __name__ == "__main__": 381 | # parse arguments 382 | args = parse_args() 383 | 384 | # read piped text if exists 385 | if args.files or sys.stdin.isatty(): 386 | stdin = None 387 | else: 388 | stdin = ''.join(sys.stdin) 389 | 390 | main(args, stdin) 391 | --------------------------------------------------------------------------------