Compare commits

...

210 Commits

Author SHA1 Message Date
Zachary Yedidia
0283c01432 Record events in cursor 2020-08-09 16:42:03 -04:00
Zachary Yedidia
bbd6f559ab Allow configuration for info/term bindings
This commit exposes the separate infopane bindings to configuration
from the user. This also adds support for separate bindings in the
terminal emulator view. Default bindings are provided, but can also
be rebound in bindings.json.
2020-08-09 16:42:03 -04:00
Zachary Yedidia
2363a4019b Separate bindings for buffers and command bar
This commit separates actions in the command bar from actions in
a normal buffer, and implements what is needed to allow rebinding,
although an interface for command bar keybindings is not yet exposed
to the user.
2020-08-09 16:42:03 -04:00
Zachary Yedidia
d33c28eeb8 Preliminary support for key sequences
This commit adds support for binding key sequences such as
"<Ctrl-x><Ctrl-c>". This commit does not solve the problem
of global bindings yet, and therefore the command bar doesn't
work properly in this commit.
2020-08-09 16:42:03 -04:00
Zachary Yedidia
5ff8b3791d Basic implementation of KeyTree 2020-08-09 16:42:03 -04:00
Zachary Yedidia
6c53407e6d Improve internal keyevent names 2020-08-09 16:42:03 -04:00
Robin Voetter
626b08e991 Improve Zig syntax definitions (#1814)
* Improve Zig syntax definitions

* Remove duplicate definition of constant.number

* Make undefined a constant
2020-08-05 19:39:03 -04:00
Jakob Nybo Nissen
697751d5f6 Allow Julia multiline strings and comments (#1813) 2020-08-05 19:38:29 -04:00
Zachary Yedidia
dd54a64746 Initialize t.release to true 2020-08-04 18:41:14 -04:00
Dmitry Maluka
6e43af31cb Fix non-working split resize with mouse drag (#1811)
Fix the 2nd part of #1773: resize via mouse drag doesn't work if the
split on the left contains other splits, i.e. is not a leaf node.

The problem is that only leaf nodes have unique id. For non-leaf nodes
ID() returns 0. So we shouldn't search the node by id.
So replace GetMouseSplitID() with GetMouseSplitNode().
2020-08-04 18:37:19 -04:00
Dmitry Maluka
a4cc5a4146 Fix erased vertical dividing line (#1810)
Fix the 1st part of #1773: the dividing line between vertical splits
is not displayed if the split on the left contains other splits, i.e.
is not a leaf node.
2020-08-04 18:33:16 -04:00
Morten Linderud
9a3fb52b42 Support reproducible builds (#1802)
* Makefile: Ensure we strip out embedded paths

To reproduce binaries undeterministic values needs to be removed. By
default Go embeds several module paths into the binaries, which prevents
people from reproducing said distributed binary.

The distributed binary from micro contains the full home path of the
current builder of the binary. -trimpath removes these paths from the
binary.

    $ strings micro | grep "/home/zyedidia" | wc -l
    868

This also helps other distributions providing reproducible versions of
micro down the line.

Signed-off-by: Morten Linderud <morten@linderud.pw>

* build-date: Ensure build time adheres to SOURCE_DATE_EPOCH

Embedding undeterministic values into binaries prevents reproduction of
the binaries. The reproducible builds projects defines
`SOURCE_DATE_EPOCH` to allow deterministic insertion of build times.

This patch ensures `build-date` checks the environment variable before
building with the local time.

    $ SOURCE_DATE_EPOCH=123123 go run tools/build-date.go
    January 02, 1970
    $ go run tools/build-date.go
    July 31, 2020

    $ make build-quick && ./micro --version
    [...]
    Compiled on July 31, 2020
    $ SOURCE_DATE_EPOCH=123123 make build-quick && ./micro --version
    [...]
    Compiled on January 02, 1970

https://reproducible-builds.org/specs/source-date-epoch/

Signed-off-by: Morten Linderud <morten@linderud.pw>
2020-08-01 20:26:39 -04:00
Zachary Yedidia
cfb8d4a6b5 Merge 2020-08-01 20:18:41 -04:00
Zachary Yedidia
b507cd26f4 Exit gracefully when SIGTERM is received
Ref #779
2020-08-01 20:18:07 -04:00
Zachary Yedidia
ce46b8e9a1 Solus install instruction 2020-07-30 21:53:30 -04:00
Zachary Yedidia
95ec55fbbf Check error in terminal emulator 2020-07-27 17:43:55 -04:00
Zachary Yedidia
015e7c7b83 Don't update internal plugins
Ref #1792
2020-07-22 15:40:40 -04:00
Ryan Westlund
1f27f51f9a Add syntax support for Renpy (#1789) 2020-07-22 15:26:37 -04:00
Zachary Yedidia
ab1d74dc79 Tidy go mod 2020-07-22 15:23:13 -04:00
Zachary Yedidia
2b1ebd5fb7 Merge 2020-07-19 19:08:00 -04:00
Zachary Yedidia
b521e47d0b Update tcell 2020-07-19 19:07:52 -04:00
Ryan Westlund
1343955b05 Add comment support for OCaml (#1776) 2020-07-15 14:13:44 -04:00
franekjel
1a89d2095d Support for multiple modifiers in colorschemes (#1772)
* Support for multiple modifiers (eg. "bold italic")

* Test for multiple modifiers (bold + italic + underline)
2020-07-14 17:58:03 -04:00
Zachary Yedidia
781a2dd826 Add flake8 linter, postinit and preinit
Closes #1768
2020-07-13 13:28:26 -04:00
Zachary Yedidia
a45591a24d Read paste option in screen init
Fixes #1767
2020-07-10 12:26:15 -04:00
Zachary Yedidia
a52dbb2142 Fix swift linting problem 2020-07-09 18:08:14 -04:00
Zachary Yedidia
41a27cc58a Update linter to include eslint
Ref #1766
2020-07-09 18:04:40 -04:00
Zachary Yedidia
3d387732c4 Update linter documentation
Ref #1766
2020-07-09 17:58:42 -04:00
Zachary Yedidia
04f281bf1d Name svg micro.svg in tarballs
Ref #1765
2020-07-09 13:29:48 -04:00
Zachary Yedidia
2caff00ce1 Add micro icon and desktop file to release zips
Closes #1765
2020-07-09 13:26:12 -04:00
Ján Priner
ddc887f6e4 Highlight multicharacter escape sequences in C and C++ string literals (#1761) 2020-07-08 00:17:48 -04:00
Ján Priner
51444765f4 Update micro.desktop (#1759) 2020-07-06 17:55:13 -04:00
Zachary Yedidia
767918d2d1 fix 2020-07-06 17:32:41 +00:00
Zachary Yedidia
984b6d4e6a Rename deb file in scripts 2020-07-06 17:30:49 +00:00
Zachary Yedidia
4184bc19e0 Improve deb package 2020-07-06 17:25:30 +00:00
Zachary Yedidia
0d81e68f86 Chmod 2020-07-06 03:21:13 +00:00
Zachary Yedidia
8316bce6eb Update script 2020-07-06 03:19:47 +00:00
Zachary Yedidia
f1318f28ea Merge 2020-07-06 03:14:06 +00:00
Zachary Yedidia
0283155305 Improve packaging
Slight improvements to the man page, and the man page is now
provided in prebuilt binary tarballs. Also a .deb file is now
provided as an asset along with prebuilt binary tarballs.
2020-07-06 03:13:02 +00:00
Zachary Yedidia
cd0a9b6a60 Update nightly release scripts 2020-07-05 17:12:06 -04:00
Zachary Yedidia
621e4e9e4d Slight performance improvement 2020-07-05 15:54:00 -04:00
Zachary Yedidia
806525c3da Improve comment plugin
When commenting a selection, the plugin won't just toggle each
line individually but will only uncomment the block if it is all
comments.

The comment plugin also now takes into account any number of spaces
between the comment character and the text. For example '//comment' will
be uncommented properly, as well as '//      comment'.

Fixes #1758
2020-07-05 15:48:49 -04:00
Zachary Yedidia
102ae04a16 Improve multicursor clipboard
Ref #1721
2020-07-05 01:12:35 -04:00
Zachary Yedidia
037c3c993f Add clipboard support for multicursors
Fixes #1721
2020-07-04 21:26:36 -04:00
Zachary Yedidia
d8596919a6 Fix reading clipboard internally for OSC52 2020-07-04 20:54:27 -04:00
Zachary Yedidia
cf86f6848f Don't set fastdirty base if modified 2020-07-04 20:09:44 -04:00
Zachary Yedidia
aeb5563df0 Update runtime 2020-07-04 20:06:37 -04:00
Zachary Yedidia
a3eacb785f Merge 2020-07-04 20:01:02 -04:00
Zachary Yedidia
f143418267 Add support for copy-paste via OSC 52
Ref #1754
2020-07-04 20:00:39 -04:00
Jim Tittsler
9003462e76 Fix README ToC link (#1757) 2020-07-04 19:47:10 -04:00
Zachary Yedidia
67355337b3 Fix escape not exiting prompt 2020-07-03 22:12:58 -04:00
Zachary Yedidia
32c8517a90 Rebind escape to clear info and deselect 2020-07-03 21:02:16 -04:00
Zachary Yedidia
b793e9bb92 Use tcell's CanDisplay instead of Go's IsPrint
Fixes #1755
2020-07-02 17:57:50 -04:00
Zachary Yedidia
977290d77b Improve php string highlighting
Fixes #1753
2020-07-01 23:38:47 -04:00
Zachary Yedidia
2c4035aa65 Update clipboard verification
Ref #1752
2020-07-01 01:24:06 -04:00
Utkarsh Gupta
b748d0c383 Drop unnecessary Ftoa and FtoaWithDigits function (#1751)
Fixes: #1749

Signed-off-by: Utkarsh Gupta <utkarsh@debian.org>
2020-06-30 13:19:27 -04:00
Zachary Yedidia
b8fbbf5c83 Only lock event handling 2020-06-28 16:34:01 -04:00
Zachary Yedidia
253281ae5e Add a lock for plugins to use if using async code
Ref #1539
2020-06-28 16:29:32 -04:00
Zachary Yedidia
f5c6f66c8f Fix path escaping on Windows
Windows does not allow ':' in a path, but for some reason previous
versions still worked, except the file for storing buffer info
(which had a ':' in the name) was not viewable except by opening
it with micro.

Ref #1736
2020-06-27 17:59:28 -04:00
Zachary Yedidia
3da0415ef1 Merge 2020-06-27 17:55:39 -04:00
Zachary Yedidia
be4d186a46 Close file properly in clean and update makefile 2020-06-27 17:55:01 -04:00
Ryan Westlund
e946d9eddf Improve Haskell syntax highlighting (#1745) 2020-06-26 17:53:43 -04:00
Zachary Yedidia
60846f549c Update plugin documentation 2020-06-24 17:24:45 -04:00
Zachary Yedidia
5f62f550f3 Add more functions to customize status bar
Adds `status.lines`, `status.vcol`, `status.bytes`, `status.size`,
and exposes some functions from go-humanize to plugins.

Ref #1727
2020-06-24 17:19:42 -04:00
Zachary Yedidia
db1df05017 Support month and day names in crontab syntax
Ref #1739
2020-06-24 16:33:22 -04:00
Zachary Yedidia
05cbc310f3 Use boundaries in cron syntax rules
Fixes #1739
2020-06-24 16:00:56 -04:00
Zachary Yedidia
3ddb2ee316 Add Search function to BufPane 2020-06-23 18:47:42 -04:00
Zachary Yedidia
a749786830 Update readme
Ref #1741
2020-06-23 17:37:58 -04:00
Zachary Yedidia
687e4bdc25 Don't delete user settings if a parse error occurs 2020-06-23 17:29:20 -04:00
Zachary Yedidia
37c754c7c7 Treat CRLF as LF when inserting text
In effect, pasting text with \r\n will remove the \r character and
delegate whether or not the file will be saved with CRLF or LF line
endings to the `fileformat` option.

Ref #1742
2020-06-23 17:17:22 -04:00
Zachary Yedidia
9cc7c9be2d Fix backup call in test 2020-06-22 18:20:01 -04:00
Zachary Yedidia
a8332fd316 Improve backup system
This commit introduces several improvements to the backup system.

* Backups are made every 8 seconds for buffers that have been modified
  since the last backup.

* The `permbackup` option allows users to specify that backups should
  be kept permanently.

* `The backupdir` option allows users to store backups in a custom
   directory.

Fixes #1641
Fixes #1536
Ref #1539 (removes possibility of race condition for backups)
2020-06-22 17:54:56 -04:00
Zachary Yedidia
c5136820c4 Don't use make in travis script 2020-06-20 20:39:20 -04:00
Zachary Yedidia
349fbb698c Upgrade travis to go 1.13.x 2020-06-20 20:29:58 -04:00
Zachary Yedidia
a1d863251f Upgrade Travis Go to 1.12.x
Fixes Travis Windows build problem because go modules are enabled
by default in 1.12.x and don't need an environment variable to be
set.
2020-06-20 20:22:31 -04:00
Zachary Yedidia
42cc50106e Include windows for travis 2020-06-20 20:12:15 -04:00
Zachary Yedidia
4d13308624 Persist plugin options correctly 2020-06-20 20:07:33 -04:00
Zachary Yedidia
d0b75bc09f Add simulation screen tests 2020-06-20 18:24:12 -04:00
Zachary Yedidia
a9ca57af6e Improve message in micro -clean
Ref #1736
2020-06-20 13:44:52 -04:00
Zachary Yedidia
bcc35c9f8c Fix backspace on Windows
Fixes #1735
2020-06-20 13:22:01 -04:00
Zachary Yedidia
fb258dd57a Clean default settings in micro -clean 2020-06-18 17:22:21 -04:00
Zachary Yedidia
891b117a33 Bind Ctrl-/ (CtrlUnderscore) in comment plugin 2020-06-18 17:18:34 -04:00
Zachary Yedidia
f5dc0a51ba Fix issue with search and replace at the end of a range 2020-06-18 16:38:10 -04:00
Zachary Yedidia
8cbe7fa92b Update tcell version 2020-06-17 23:24:53 -04:00
Zachary Yedidia
a584ff36de Merge 2020-06-17 23:14:03 -04:00
Zachary Yedidia
f5405cee18 Improve keybinding label consistency
The old notation (for example `CtrlG`) causes confusion when combined
with new notation needed for alt (`Alt-g`) due to Alt being case
sensitive. Previously both formats were supported, but the documentation
and defaults used a combination. This commit only uses the new notation
for consistency.

Ref #1470
2020-06-17 23:11:50 -04:00
Zachary Yedidia
3516c8a9a6 Start replacement search at cursor location
Fixes #1731
2020-06-17 22:43:22 -04:00
Matthias
c19dce87e4 Fix typo in defaultkeys (#1730) 2020-06-17 13:35:59 -04:00
Zachary Yedidia
2adba18159 Don't move nightly tag 2020-06-17 00:48:17 +00:00
Zachary Yedidia
f9f2ef02ac Edit nightly release instead of replacing 2020-06-16 20:33:59 -04:00
Zachary Yedidia
0976eb3e51 Cross compile binaries in release scripts 2020-06-16 19:55:12 -04:00
Zachary Yedidia
ac2d1491ff Use hub for creating releases 2020-06-16 19:55:12 -04:00
Hugo Locurcio
5bfc892a74 Add support for dozens more languages to the comment plugin (#1729) 2020-06-16 00:49:07 -04:00
Ryan Westlund
1793b6268b Add comment support for Haskell (#1728) 2020-06-15 16:11:51 -04:00
Zachary Yedidia
9b62aa4170 Merge branch 'p-e-w-faster-runewidth' 2020-06-13 17:00:03 -04:00
Zachary Yedidia
6fef5d6232 Merge branch 'faster-runewidth' of https://github.com/p-e-w/micro into p-e-w-faster-runewidth 2020-06-13 16:59:52 -04:00
Zachary Yedidia
fe19b13b3b Update go-shellquote for windows 2020-06-13 16:58:20 -04:00
Philipp Emanuel Weidmann
6559b116c0 Make determining rune width faster 2020-06-13 08:59:17 +05:30
Zachary Yedidia
ca976a8a3c Update runtime build script
Ref #1687
2020-06-12 20:54:37 -04:00
Zachary Yedidia
cfc595e80e Fix MoveLines on last line of buffer
Fixes #1723
Fixes #1724
2020-06-12 15:16:27 -04:00
Zachary Yedidia
fde4b92b9f More consistent key labels in docs 2020-06-12 14:41:57 -04:00
Zachary Yedidia
b8ec7b320a Add note for macOS terminals in docs 2020-06-12 14:20:26 -04:00
Zachary Yedidia
1786165d8b Merge branch 'master' of https://github.com/zyedidia/micro 2020-06-12 14:16:53 -04:00
Zachary Yedidia
0322e91933 Update readme 2020-06-12 14:16:47 -04:00
Ján Priner
b2261fc225 Add latex support in comment plugin (#1725) 2020-06-12 12:58:51 -04:00
Philipp Emanuel Weidmann
5ce26cca71 Make determining whether a code point represents a combining mark faster (#1719) 2020-06-12 00:10:00 -04:00
Zachary Yedidia
efb38b8636 Merge branch 'settings-config'
With these changes, settings.json should only contain options that
have been modified from their default values. Micro will actively
options that are set to default values from the settings.json file.
To see a full list of settings and their defaults, see the "options"
documentation, as well as `micro -options`.
2020-06-09 16:34:37 -04:00
Zachary Yedidia
0654db334a Show key name in raw pane 2020-06-09 15:57:52 -04:00
Zachary Yedidia
660d345880 Don't apply cli options to settings.json 2020-06-08 22:19:15 -04:00
Dmitry Maluka
1f58eecf3c Lower priority of cursorline and colorcolumn highlighting (#1697)
Fixes #1665
2020-06-08 16:15:54 -04:00
Zachary Yedidia
ae05ff1811 settings.json only contains modified settings
If a setting has a default value it will not be listed in settings.json.
2020-06-08 15:33:38 -04:00
Zachary Yedidia
43924646f6 Merge 2020-06-08 13:55:24 -04:00
Zachary Yedidia
79ee757757 Only start autocompletion for alphanumerics
Ref #1712
2020-06-08 13:54:31 -04:00
Ryan Westlund
006165230d python.yaml: add async as a keyword (#1713)
await is already a keyword, but async is not.
2020-06-08 13:45:05 -04:00
Zachary Yedidia
ead07e0b60 Expose ConfigDir and Tabs to plugins
Access with `micro.ConfigDir` (constant value) and `micro.Tabs()`.
2020-06-07 18:21:46 -04:00
Zachary Yedidia
140662f1ec Verify that all settings have correct type
This prevents crashes that occur when the user has put the wrong
type for a setting manually in the settings.json file.
2020-06-07 17:31:16 -04:00
Zachary Yedidia
44c1929f9d Fix mouse support in command bar 2020-06-07 15:46:12 -04:00
Zachary Yedidia
397fe634d7 Update tcell to fix escape sequence bug 2020-06-07 15:22:17 -04:00
Zachary Yedidia
2e3d08580e Merge 2020-06-06 15:56:36 -04:00
Zachary Yedidia
466889f540 Fix fileformat for newly created files
Fixes #1575
2020-06-06 15:56:13 -04:00
Dmitry Maluka
63900cb395 Fix highlighting at the end of line (#1705)
Fixes #1664
2020-06-04 23:32:31 -04:00
Chloe Kudryavtsev
07860b8973 Add mksh to the set of supported shells (#1703) 2020-06-03 13:30:42 -04:00
Zachary Yedidia
b473fe458d Merge 2020-06-03 00:27:51 -04:00
Zachary Yedidia
8cf56bfc56 Up arrow on first line brings to start
Fixes #1701
2020-06-03 00:27:24 -04:00
Sijmen J. Mulder
51050811eb Add pkgsrc instruction to readme (#1699) 2020-06-02 16:49:18 -04:00
Zachary Yedidia
14cd3cdbf8 Update readme 2020-06-01 00:17:52 -04:00
Zachary Yedidia
51ab8f9914 Unicode replacement char for non-displayable chars 2020-05-30 18:11:52 -04:00
Zachary Yedidia
afeb07a024 More fixes for parsecursor
Fixes #1695
Fixes #1696
2020-05-30 12:23:29 -04:00
Zachary Yedidia
3fc9a8ad9e Fix handling of +LINE:COL syntax
Fixes #1685
2020-05-29 22:48:23 -04:00
Zachary Yedidia
b05d3a5193 Slightly improve performance for very long lines 2020-05-29 15:31:13 -04:00
Zachary Yedidia
ffc922a7c5 Only perform save callback if save was successful
Fixes #1684
2020-05-29 15:02:38 -04:00
Zachary Yedidia
eeab114ed5 Add parsecursor option for file:line:col syntax
This option is disabled by default, and when enabled causes micro
to parse `:line:col` as a location for the cursor rather than
as part of the filename.

Closes #1650
Closes #1685
2020-05-29 14:55:24 -04:00
Zachary Yedidia
8bd7e5807c Always use current pane for keybinding actions
Fixes #1677
2020-05-29 14:38:29 -04:00
Andrew Clarke
9b59e07b47 Use "goto -1" to move cursor to end of document. (#1691) 2020-05-29 13:29:09 -04:00
Colin Hughes
00edf0207f Added hybrid line numbers (#1690)
* Added hybrid line numbers

* Changed rulerhybrid to relativeruler, modified documentation accordingly.

* Reverted go.mod and go.sum
I don't know how they got changed but they are good now.

Co-authored-by: Colin Hughes <semilin@pop-os.localdomain>
2020-05-28 22:24:09 -04:00
Zachary Yedidia
a95b17a4e7 Update readme 2020-05-28 18:39:17 -04:00
Zachary Yedidia
8956448fca UpdateRules after save is successful 2020-05-28 13:06:29 -04:00
Zachary Yedidia
a915cf9283 Fix '> save' command 2020-05-28 13:02:09 -04:00
Zachary Yedidia
dd10869eca Update readme 2020-05-28 11:59:31 -04:00
Peder B. Sundt
4356c7e434 Tweak railscast colorscheme to better reflect original (#1297) 2020-05-28 11:50:35 -04:00
axxx007xxxz
2e770ce9ce README: Add Fedora install instructions (#1671) 2020-05-28 11:49:18 -04:00
pyfisch
381e1b639d Rewrite TOML syntax file (#1681) 2020-05-26 14:10:27 -04:00
Shinichi TAMURA
cc09712d14 set bash-fc file's syntax as shell (#1679)
* set bash-fc file's syntax as shell

* remove dups from shell file matcher
2020-05-24 23:50:30 -04:00
Dmitry Maluka
c5b0c2d41f Fix dropped redraw events (#1675)
If screen.Redraw() is called very quickly after a key or mouse event,
it may send the redraw event while micro is not waiting for it but
still processing the key or mouse event. Since drawChan is non-buffered
and at the same time non-blocking, this redraw event will be simply lost,
so the screen content will not be up-to-date.
2020-05-23 14:59:23 -04:00
Zachary Yedidia
bd43a44194 Merge branch 'master' of https://github.com/zyedidia/micro 2020-05-21 14:36:34 -04:00
Zachary Yedidia
bfe68b1626 Allow divider customization with divchars option
Adds the `divchars` and `divreverse` options to customize divider
styles.
2020-05-21 14:35:54 -04:00
Zachary Yedidia
0064b8268f Improve unicode line array test 2020-05-20 19:53:54 -04:00
Zachary Yedidia
9a22d93ea2 Expose CharacterCount to plugins 2020-05-20 18:04:00 -04:00
Zachary Yedidia
5c8a2332d9 Use unicode.Mark for combining unicode range 2020-05-20 18:01:10 -04:00
Zachary Yedidia
ff0683d6d0 Final touches for combining character support 2020-05-20 17:00:56 -04:00
Zachary Yedidia
79c0ea17ad Use CharacterCount over RuneCount 2020-05-20 16:47:08 -04:00
Zachary Yedidia
bdff221870 Use DecodeCharacter over DecodeRune 2020-05-20 16:43:12 -04:00
Zachary Yedidia
65be5efd83 Merge branch 'p-e-w-buffer-benchmarks' 2020-05-20 15:29:02 -04:00
Zachary Yedidia
a491dd1c52 Merge branch 'buffer-benchmarks' of https://github.com/p-e-w/micro into p-e-w-buffer-benchmarks 2020-05-20 15:28:36 -04:00
Zachary Yedidia
d7ab44253f Update tcell and support italics in colorschemes
Closes #1640
2020-05-17 12:48:34 -04:00
Zachary Yedidia
0a6720498f Merge branch 'master' of https://github.com/zyedidia/micro 2020-05-17 12:23:21 -04:00
dmaluka
a150eef6f9 Fix end line number in HighlightMatches (#1662)
There is a bit of mess in the usage of HighlightMatches: in some places
we assume that it updates lines from startline to endline inclusive,
in other places we assume it's non-inclusive.
This fix makes it always inclusive.

In particular, it fixes a bug: when we open a file which has no
newline at the end, the last line isn't highlighted.
2020-05-17 16:05:34 -04:00
Zachary Yedidia
c46257222c Add support for FindLiteral
Use the FindLiteral action to use Find without regex support.

Fixes #1661
2020-05-17 12:22:33 -04:00
jsyedidia
299af4a3db Update hlint to 3.0 syntax (#1659) 2020-05-16 13:06:55 -04:00
Jeff Warner
d0f7ecf9ca Adds command "tabmove ±n", for better tab management (#1636)
* Adds command "tabmove ±n", for better tab management

* Added tabmove to help:commands

* Replace uses of util.Min, util.Max with util.Clamp

Browsing code and discovered `util.Clamp`, ideal for this section of my code

* oops, missed an arg

* Typo, again
2020-05-14 21:51:49 -04:00
dmaluka
fb35e0312a Fix unbind of a rune (#1649)
Fix problem with non-working unbind of a rune key.
E.g. after the following commands:

bind "n" "FindNext"
unbind "n"

Observed result: "n" key still triggers FindNext action
Expected result: "n" key inserts "n" rune
2020-05-14 21:50:28 -04:00
Zachary Yedidia
30395b1f67 Remove outdated c++ highlighter
Fixes #1652
2020-05-14 21:37:19 -04:00
Zachary Yedidia
ddf70953fe Support snake case autocompletion
Fixes #1655
2020-05-14 21:34:17 -04:00
Zachary Yedidia
55e97596d3 Fix movelinesup when selection is not complete 2020-05-07 19:39:17 -04:00
Zachary Yedidia
66dc48ce9b Improve readme 2020-05-04 22:21:46 -04:00
Zachary Yedidia
c490a94700 Update makefile 2020-05-04 10:34:16 -04:00
Zachary Yedidia
eff89a98a7 Fix v2 import path for go mod 2020-05-04 10:16:15 -04:00
Zachary Yedidia
221d8f462a Merge branch 'jwarner112-jwarner112-copyline' 2020-04-30 00:54:11 -04:00
Zachary Yedidia
7a23878250 gofmt 2020-04-30 00:54:02 -04:00
Jeff Warner
5d3e4fc3d9 Adds CopyLine action, the new default action for CtrlC if cursor has no selection 2020-04-29 21:06:54 -07:00
Indiana Kernick
f52fbfa1f0 Add .inl as a C++ file extension (#1630) 2020-04-29 20:01:59 -04:00
Zachary Yedidia
d60626c64b Merge 2020-04-25 17:01:20 -04:00
Zachary Yedidia
aaac0b1e6f Better actions error message 2020-04-25 17:01:16 -04:00
Some person
0f984131fb Update coffeescript.yaml (#1571)
* Update coffeescript.yaml

We need much much more modern coffeescript standards, the current one has broken `0x123456` (hex) and single quotes, and doesn't support multiline comments. This PR aims to fix that. I'm no regexp expert, I just based this off JS', so tell me if I did anything wrong.

* Update coffeescript.yaml
2020-04-22 23:12:56 -04:00
Zachary Yedidia
eb7189dcdb Make cursor follow selections
Fixes #1624
2020-04-21 09:33:21 -04:00
Zachary Yedidia
74523d28c5 Merge 2020-04-20 23:13:10 -04:00
Zachary Yedidia
f894f0a26e Update clipboard version 2020-04-20 23:13:01 -04:00
2pac
a067ce1f41 implemented circular tab movement (#1619)
Co-authored-by: 2pac <tarasyarema@pm.me>
2020-04-17 13:42:48 -04:00
Zachary Yedidia
f59468642d Update runtime 2020-04-10 17:27:57 -04:00
Zachary Yedidia
85e85b7ccc Merge 2020-04-10 17:27:34 -04:00
Zachary Yedidia
8f5888e7bf Use StartCol in colorcolumn calculation
Fixes #1615
2020-04-10 17:27:11 -04:00
Ján Jančár
f0da73bae2 Add StartOfTextToggle and SelectToStartOfTextToggle actions. (#1612)
These actions reintroduce the behavior of micro where the Home key
toggles between the start of text (first) and the start of the line.
The same applies for the variant with selection. This commit also
sets these bindings as the defaults.
2020-04-10 17:21:02 -04:00
Zachary Yedidia
d92deacf99 Ensure mouse release before focus change
Fixes #1613
2020-04-10 15:58:43 -04:00
trrbl
ffd7b5c770 Support csharp-script syntax. (#1425)
```
#!/usr/bin/env dotnet-script
// Set Runtime
#! "netcoreapp3.0"
// Imports
#load "myAssembly.dll"
#r "nuget:CliWrap,2.5.0"
```
This syntax file basically imports the `csharp` rules and adds it's custom pre-processors.
2020-04-10 13:57:36 -04:00
Ján Jančár
bd8c0d25c8 Add sagemath syntax highlight based on python3. (#1227) 2020-04-09 12:20:48 -04:00
Ján Jančár
052a36b896 Fix docs regarding "Home" key and "StartOfText" and "StartOfLine". (#1611) 2020-04-07 12:58:30 -04:00
jsyedidia
a76bf02f5f Add Haskell linter hlint to linter plugin (#1610) 2020-04-05 14:05:01 -04:00
Nikita Bobko
92f4cb7ef7 Clarify regex for git commit --verbose (#1606) 2020-04-05 14:04:36 -04:00
Zachary Yedidia
1cf9537340 Fix python3 syntax file and make python3 default
The python3 syntax had "filename" instead of "filetype"
as the header. This commit also makes standard py extensions
use the python3 highlighting and requires .py2 or a python2
env to use python2 highlighting because python3 is the standard
python now.

Fixes #1592
2020-03-24 11:42:23 -04:00
Zachary Yedidia
60c8c81da3 Relocate during replace
Fixes #1587
2020-03-24 11:33:52 -04:00
Zachary Yedidia
c76a973877 Merge 2020-03-24 11:17:12 -04:00
Zachary Yedidia
6def99ce24 Clarify replace message if replacing in selection 2020-03-24 11:14:54 -04:00
Koki Fushimi
26930ca81f Better Julia syntax. (#1567)
* Fix regex syntax and change to match one or more spaces.

* Add constant `nothing` and `missing`.

* Add Inf and NaN to constant numbers.
2020-03-24 10:59:48 -04:00
Hugo Locurcio
cd379cd838 Clarify the Find operation being regex-enabled (#1561)
This makes it more obvious that the Find option accepts regular
expressions as input.

See discussion in #1560.
2020-03-24 10:59:40 -04:00
allanderek
ee157f6503 Add elm as a default comment type in the comment plugin. (#1586) 2020-03-24 10:56:50 -04:00
Zachary Yedidia
48ca19873f Better ordering for reading syntax files
Ref #1580
2020-03-24 10:52:15 -04:00
Zachary Yedidia
fee5528309 Fix term emulator crash if invalid exec given
Ref #1583
2020-03-24 10:22:10 -04:00
Zachary Yedidia
671a188802 Support +LINE:COL flag syntax for cursor pos
Closes #1566
2020-03-24 10:10:44 -04:00
Zachary Yedidia
18d540583b Don't clear infobar if not enabled
Fixes #1584
2020-03-17 14:21:36 -04:00
Zachary Yedidia
943ea15fa3 Fix linter c++ entry
Fixes #1578
2020-03-14 15:40:05 -04:00
Cafe Duke
2ef57977d7 Add color schemes dukeubuntu-tc, dukedark-tc and dukelight-tc (#1547)
* Duke ubuntu, dark and light color schemes

* Duke color schemes: Change bgcolor for line number and cursor line

Co-authored-by: Raghunandan.Seshadri <raghubs81@gmail.com>
Co-authored-by: Raghunandan Seshadri <raghunandan.seshadri@oracle.com>
2020-03-07 22:07:43 -05:00
Zachary Yedidia
527750b68d Copy selection to primary on mouse release
Fixes #1558
2020-03-05 16:00:40 -05:00
Zachary Yedidia
629efe5eb7 Add JumpLine action back
You can bind to "command-edit:goto ", but binding to the action
"JumpLine" will have the same effect now.

Fixes #1550
2020-03-02 20:09:19 -05:00
Andrew Havens
a19cd2e6d0 Add support for Fastlane and Cocoapods file syntax highlighting (#1544) 2020-03-02 20:03:28 -05:00
Philipp Emanuel Weidmann
d038d3040f Add more sophisticated buffer benchmark system 2020-03-01 13:20:10 +05:30
Zachary Yedidia
9e8d76f2fa If stdout is a pipe, output to the pipe
If you run micro as `micro | cat` for example, micro will disallow
you from saving the file, and when you quit the buffer, the contents
will be sent to the pipe. This allows one to use micro as part of
an interactive unix pipeline.

Closes #1524
2020-02-27 12:39:19 -05:00
Zachary Yedidia
8a9a14562f Use bytes.Buffer for LineArray.Bytes 2020-02-27 11:27:00 -05:00
Zachary Yedidia
a6f5dee45c Fix custom syntax files not highlighting
Fixes #1530
2020-02-27 00:58:52 -05:00
Zachary Yedidia
b12886b066 Improve buffer test 2020-02-25 23:59:27 -05:00
Zachary Yedidia
56f5b475eb Improve buffer test 2020-02-25 23:21:50 -05:00
122 changed files with 5221 additions and 2412 deletions

1
.gitignore vendored
View File

@@ -11,6 +11,7 @@ todo.txt
test.txt
log.txt
*.old
benchmark_results*
tools/build-version
tools/build-date
tools/info-plist

View File

@@ -1,9 +1,11 @@
language: go
go:
- "1.11.x"
- "1.13.x"
os:
- linux
- osx
- windows
script:
- env GO111MODULE=on make build
- env GO111MODULE=on make test
- go build ./cmd/micro
- go test ./internal/...
- go test ./cmd/...

View File

@@ -6,28 +6,29 @@ HASH = $(shell git rev-parse --short HEAD)
DATE = $(shell GOOS=$(shell go env GOHOSTOS) GOARCH=$(shell go env GOHOSTARCH) \
go run tools/build-date.go)
ADDITIONAL_GO_LINKER_FLAGS = $(shell GOOS=$(shell go env GOHOSTOS) \
GOARCH=$(shell go env GOHOSTARCH))
GOARCH=$(shell go env GOHOSTARCH) \
go run tools/info-plist.go "$(VERSION)")
GOBIN ?= $(shell go env GOPATH)/bin
GOVARS = -X github.com/zyedidia/micro/internal/util.Version=$(VERSION) -X github.com/zyedidia/micro/internal/util.CommitHash=$(HASH) -X 'github.com/zyedidia/micro/internal/util.CompileDate=$(DATE)'
DEBUGVAR = -X github.com/zyedidia/micro/internal/util.Debug=ON
GOVARS = -X github.com/zyedidia/micro/v2/internal/util.Version=$(VERSION) -X github.com/zyedidia/micro/v2/internal/util.CommitHash=$(HASH) -X 'github.com/zyedidia/micro/v2/internal/util.CompileDate=$(DATE)'
DEBUGVAR = -X github.com/zyedidia/micro/v2/internal/util.Debug=ON
VSCODE_TESTS_BASE_URL = 'https://raw.githubusercontent.com/microsoft/vscode/e6a45f4242ebddb7aa9a229f85555e8a3bd987e2/src/vs/editor/test/common/model/'
# Builds micro after checking dependencies but without updating the runtime
build:
go build -ldflags "-s -w $(GOVARS) $(ADDITIONAL_GO_LINKER_FLAGS)" ./cmd/micro
go build -trimpath -ldflags "-s -w $(GOVARS) $(ADDITIONAL_GO_LINKER_FLAGS)" ./cmd/micro
build-dbg:
go build -ldflags "-s -w $(ADDITIONAL_GO_LINKER_FLAGS) $(DEBUGVAR)" ./cmd/micro
go build -trimpath -ldflags "-s -w $(ADDITIONAL_GO_LINKER_FLAGS) $(DEBUGVAR)" ./cmd/micro
build-tags: fetch-tags
go build -ldflags "-s -w $(GOVARS) $(ADDITIONAL_GO_LINKER_FLAGS)" ./cmd/micro
go build -trimpath -ldflags "-s -w $(GOVARS) $(ADDITIONAL_GO_LINKER_FLAGS)" ./cmd/micro
# Builds micro after building the runtime and checking dependencies
build-all: runtime build
# Builds micro without checking for dependencies
build-quick:
go build -ldflags "-s -w $(GOVARS) $(ADDITIONAL_GO_LINKER_FLAGS)" ./cmd/micro
go build -trimpath -ldflags "-s -w $(GOVARS) $(ADDITIONAL_GO_LINKER_FLAGS)" ./cmd/micro
# Same as 'build' but installs to $GOBIN afterward
install:
@@ -46,6 +47,7 @@ fetch-tags:
# Builds the runtime
runtime:
git submodule update --init
rm -f runtime/syntax/*.hdr
go run runtime/syntax/make_headers.go runtime/syntax
go build -o tools/bindata ./tools/go-bindata
tools/bindata -pkg config -nomemcopy -nometadata -o runtime.go runtime/...
@@ -63,9 +65,24 @@ testgen:
test:
go test ./internal/...
go test ./cmd/...
bench:
go test -bench=. ./internal/...
for i in 1 2 3; do \
go test -bench=. ./internal/...; \
done > benchmark_results
benchstat benchmark_results
bench-baseline:
for i in 1 2 3; do \
go test -bench=. ./internal/...; \
done > benchmark_results_baseline
bench-compare:
for i in 1 2 3; do \
go test -bench=. ./internal/...; \
done > benchmark_results
benchstat -alpha 0.15 benchmark_results_baseline benchmark_results
clean:
rm -f micro

View File

@@ -32,7 +32,7 @@ You can also check out the website for Micro at https://micro-editor.github.io.
- [macOS terminal](#macos-terminal)
- [Linux clipboard support](#linux-clipboard-support)
- [Colors and syntax highlighting](#colors-and-syntax-highlighting)
- [Plan9, Cygwin, Mingw](#plan9-cygwin-mingw)
- [Cygwin, Mingw, Plan9](#cygwin-mingw-plan9)
- [Usage](#usage)
- [Documentation and Help](#documentation-and-help)
- [Contributing](#contributing)
@@ -44,7 +44,7 @@ You can also check out the website for Micro at https://micro-editor.github.io.
- Easy to use and install.
- No dependencies or external files are needed — just the binary you can download further down the page.
- Multiple cursors.
- Common keybindings (<kbd>Ctrl+S</kbd>, <kbd>Ctrl+C</kbd>, <kbd>Ctrl+V</kbd>, <kbd>Ctrl+Z</kbd>, …).
- Common keybindings (<kbd>Ctrl-s</kbd>, <kbd>Ctrl-c</kbd>, <kbd>Ctrl-v</kbd>, <kbd>Ctrl-z</kbd>, …).
- Keybindings can be rebound to your liking.
- Sane defaults.
- You shouldn't have to configure much out of the box (and it is extremely easy to configure).
@@ -53,13 +53,13 @@ You can also check out the website for Micro at https://micro-editor.github.io.
- Extremely good mouse support.
- This means mouse dragging to create a selection, double click to select by word, and triple click to select by line.
- Cross-platform (it should work on all the platforms Go runs on).
- Note that while Windows is supported Mingw/Cygwin is not (see below)
- Note that while Windows is supported Mingw/Cygwin is not (see below).
- Plugin system (plugins are written in Lua).
- micro has a built-in plugin manager to automatically install, remove, and update plugins.
- Built-in diff gutter
- Simple autocompletion
- Built-in diff gutter.
- Simple autocompletion.
- Persistent undo.
- Automatic linting and error notifications
- Automatic linting and error notifications.
- Syntax highlighting for over [130 languages](runtime/syntax).
- Color scheme support.
- By default, micro comes with 16, 256, and true color themes.
@@ -76,17 +76,17 @@ To install micro, you can download a [prebuilt binary](https://github.com/zyedid
If you want more information about ways to install micro, see this [wiki page](https://github.com/zyedidia/micro/wiki/Installing-Micro).
Use `micro -version` to get the version information after installing. It is only guaranteed that you are installing the most recent
stable version if you install from the prebuilt binaries, Homebrew, or Snap.
A desktop entry file and man page can be found in the [assets/packaging](https://github.com/zyedidia/micro/tree/master/assets/packaging) directory.
### Prebuilt binaries
All you need to install micro is one file, the binary itself. It's as simple as that!
Download the binary from the [releases](https://github.com/zyedidia/micro/releases) page.
On that page you'll see the nightly release, which contains binaries for micro which are built every night,
and you'll see all the stable releases with the corresponding binaries.
Running `micro -version` will give you the version information.
### Installation script
There is a script which can install micro for you by downloading the latest prebuilt binary. You can find it at <https://getmic.ro>.
@@ -97,7 +97,9 @@ You can easily install micro by running
curl https://getmic.ro | bash
```
The script will install the micro binary to the current directory. See its [GitHub repository](https://github.com/benweissmann/getmic.ro) for more information.
The script will place the micro binary in the current directory. From there, you can move it to a directory on your path of your choosing (e.g. `sudo mv micro /usr/bin`). See its [GitHub repository](https://github.com/benweissmann/getmic.ro) for more information.
To uninstall micro, simply remove the binary, and the configuration directory at `~/.config/micro`.
### Package managers
@@ -107,29 +109,36 @@ You can install micro using Homebrew on Mac:
brew install micro
```
**Note for Mac:** All micro keybindings use the control or alt (option) key, not the command
key. By default, macOS terminals do not forward alt key events. To fix this, please see
the section on [macOS terminals](https://github.com/zyedidia/micro#macos-terminal) further below.
On Linux, you can install micro through [snap](https://snapcraft.io/docs/core/install)
```
snap install micro --classic
```
On Debian `unstable | testing | buster-backports` and Ubuntu `focal` (20.04), micro is available
via `apt`:
**Note for Linux:** for interfacing with the local system clipboard, `xclip` or `xsel`
must be installed. Please see the section on [Linux clipboard support](https://github.com/zyedidia/micro#linux-clipboard-support)
further below.
```
sudo apt install micro
```
Micro is also available through other package managers on Linux such as apt, dnf, AUR, Nix, and package managers
for other operating systems. These packages are not guaranteed to be up-to-date.
Micro is also available through other package managers on Linux such as AUR, Nix, and package managers
for other operating systems:
* Windows: [Chocolatey](https://chocolatey.org) and [Scoop](https://github.com/lukesampson/scoop)
* `choco install micro`
* `scoop install micro`
* OpenBSD: Available in the ports tree and also available as a binary package
* `pkd_add -v micro`
* Arch Linux, CRUX, Termux for Android
* See details in the [wiki page](https://github.com/zyedidia/micro/wiki/Installing-Micro)
* Linux: Available in distro-specific package managers.
* `apt install micro` (Ubuntu 20.04 `focal`, and Debian `unstable | testing | buster-backports`). At the moment, this package (2.0.1-1) is outdated and has a known bug where debug mode is enabled.
* `dnf install micro` (Fedora).
* `yay -S micro` (Arch Linux).
* `eopkg install micro` (Solus).
* See [wiki](https://github.com/zyedidia/micro/wiki/Installing-Micro) for details about CRUX, Termux.
* Windows: [Chocolatey](https://chocolatey.org) and [Scoop](https://github.com/lukesampson/scoop).
* `choco install micro`.
* `scoop install micro`.
* OpenBSD: Available in the ports tree and also available as a binary package.
* `pkd_add -v micro`.
* NetBSD, macOS, Linux, Illumos, etc. with [pkgsrc](http://www.pkgsrc.org/)-current:
* `pkg_add micro`
### Building from source
@@ -165,7 +174,7 @@ CGO_ENABLED=0 make build
### macOS terminal
If you are using macOS, you should consider using [iTerm2](http://iterm2.com/) instead of the default terminal (Terminal.app). The iTerm2 terminal has much better mouse support as well as better handling of key events. For best keybinding behavior, choose `xterm defaults` under `Preferences->Profiles->Keys->Load Preset`. The newest versions also support true color.
If you are using macOS, you should consider using [iTerm2](http://iterm2.com/) instead of the default terminal (Terminal.app). The iTerm2 terminal has much better mouse support as well as better handling of key events. For best keybinding behavior, choose `xterm defaults` under `Preferences->Profiles->Keys->Presets...`, and select `Esc+` for `Left Option Key` in the same menu. The newest versions also support true color.
If you still insist on using the default Mac terminal, be sure to set `Use Option key as Meta key` under
`Preferences->Profiles->Keyboard` to use <kbd>option</kbd> as <kbd>alt</kbd>.
@@ -183,7 +192,7 @@ If you don't have these commands, micro will use an internal clipboard for copy
If you open micro and it doesn't seem like syntax highlighting is working, this is probably because
you are using a terminal which does not support 256 color mode. Try changing the color scheme to `simple`
by pressing <kbd>Ctrl+E</kbd> in micro and typing `set colorscheme simple`.
by pressing <kbd>Ctrl-e</kbd> in micro and typing `set colorscheme simple`.
If you are using the default Ubuntu terminal, to enable 256 make sure your `TERM` variable is set
to `xterm-256color`.
@@ -224,7 +233,7 @@ click to enable line selection.
## Documentation and Help
micro has a built-in help system which you can access by pressing <kbd>Ctrl+E</kbd> and typing `help`. Additionally, you can
micro has a built-in help system which you can access by pressing <kbd>Ctrl-e</kbd> and typing `help`. Additionally, you can
view the help files here:
- [main help](https://github.com/zyedidia/micro/tree/master/runtime/help/help.md)
@@ -245,3 +254,5 @@ You can use the [GitHub issue tracker](https://github.com/zyedidia/micro/issues)
to report bugs, ask questions, or suggest new features.
For a more informal setting to discuss the editor, you can join the [Gitter chat](https://gitter.im/zyedidia/micro).
Sometimes I am unresponsive, and I apologize! If that happens, please ping me.

View File

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 18.1.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="Layer_1"
x="0px"
y="0px"
viewBox="0 0 103.2 103.2"
enable-background="new 0 0 960 560"
xml:space="preserve"
inkscape:version="0.91 r13725"
sodipodi:docname="micro-logo-notext.svg"
width="103.2"
height="103.2"><metadata
id="metadata9"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs7" /><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="733"
inkscape:window-height="480"
id="namedview5"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:zoom="0.28541667"
inkscape:cx="302"
inkscape:cy="-4"
inkscape:window-x="1699"
inkscape:window-y="277"
inkscape:window-maximized="0"
inkscape:current-layer="Layer_1" /><path
d="M 51.6,0 C 23.1,0 0,23.1 0,51.6 c 0,28.5 23.1,51.6 51.6,51.6 28.5,0 51.6,-23.1 51.6,-51.6 C 103.2,23.1 80.1,0 51.6,0 Z m 24.5,58.6 c -0.5,2 -1.3,3.6 -2.4,4.9 -1,1.3 -2,2.1 -3.1,2.5 -1.1,0.4 -2.2,0.6 -3.4,0.6 -1.2,0 -2.2,-0.2 -3,-0.7 C 63.4,65.5 62.8,64.8 62.3,64 61.8,63.2 61.5,62.2 61.3,61.1 61.1,60 61,58.8 61,57.5 c 0,-0.5 0,-1 0.1,-1.7 0.1,-0.7 0.2,-1.6 0.3,-1.6 l -0.2,0 c -1.6,4 -3.8,6.9 -6.6,9.2 -2.8,2.3 -5.9,3.4 -9.3,3.4 -2.3,0 -4.2,-0.9 -5.5,-2.6 -1.4,-1.7 -2.1,-4.3 -2.1,-7.7 0,-0.5 0,-1 0.1,-1.6 0.1,-0.5 0.1,-0.7 0.2,-1.7 l -0.7,0 c -0.9,2 -1.7,4.8 -2.3,7.3 -0.6,2.5 -1.1,4.8 -1.4,6.9 -0.4,2.1 -0.6,4 -0.8,5.6 -0.2,1.6 -0.3,2.7 -0.4,3.3 0.1,0.5 0.2,1 0.3,1.6 0.2,0.6 0.3,1.2 0.5,1.7 0.2,0.5 0.3,1.1 0.4,1.6 0.1,0.5 0.2,0.9 0.2,1.2 0,1.4 -0.3,2.5 -0.9,3.2 -0.6,0.7 -1.3,1.1 -2,1.1 -0.9,0 -1.7,-0.3 -2.3,-0.8 -0.7,-0.6 -1,-1.5 -1,-2.7 0,-1.7 0.3,-3.9 0.9,-6.5 0.6,-2.6 1.5,-5.9 2.6,-9.8 0.6,-1.8 1.1,-3.6 1.7,-5.4 0.6,-1.8 1.1,-3.5 1.6,-5 0.5,-1.5 0.9,-2.9 1.3,-4.1 0.4,-1.2 0.6,-2.1 0.7,-2.8 0.1,-0.3 0.2,-1 0.3,-2 0.1,-1 0.2,-2.1 0.4,-3.4 0.2,-1.3 0.3,-2.7 0.5,-4.1 0.2,-1.5 0.4,-2.8 0.5,-4 0.2,-0.9 0.3,-1.9 0.5,-3 0.2,-1.1 0.5,-2.2 0.9,-3.1 0.4,-1 1,-1.8 1.7,-2.5 0.7,-0.7 1.6,-1 2.7,-1 1.2,0 2,0.4 2.4,1.1 0.4,0.7 0.6,1.6 0.5,2.6 -0.1,1 -0.2,2.1 -0.5,3.2 -0.3,1.1 -0.6,2.1 -0.9,2.9 -0.8,2.5 -1.6,4.8 -2.5,6.7 -0.9,1.9 -1.7,4 -2.4,6.2 -0.6,1.5 -0.8,2.9 -0.8,4.1 0,2.2 0.7,3.8 2,5 1.4,1.2 3,1.7 4.9,1.7 1.5,0 3,-0.5 4.4,-1.6 1.4,-1.1 2.7,-2.4 3.9,-3.9 1.2,-1.5 2.2,-3.1 3,-4.9 0.8,-1.7 1.4,-3.3 1.8,-4.6 0.1,-0.2 0.2,-0.6 0.3,-1.4 0.2,-0.8 0.3,-1.7 0.5,-2.7 0.2,-1 0.4,-2 0.6,-3.1 0.2,-1.1 0.4,-2 0.5,-2.7 0.2,-0.8 0.3,-1.6 0.5,-2.6 0.2,-1 0.5,-1.9 0.9,-2.8 0.4,-0.9 1,-1.6 1.6,-2.2 0.7,-0.6 1.5,-0.9 2.6,-0.9 1.3,0 2.1,0.4 2.6,1.1 0.4,0.7 0.6,1.6 0.6,2.6 -0.1,1 -0.2,2 -0.5,3 -0.3,1 -0.5,1.8 -0.7,2.4 -0.8,2.5 -1.6,4.7 -2.4,6.7 -0.8,2 -1.5,3.8 -2.2,5.2 -0.6,1.5 -1.1,2.6 -1.5,3.5 -0.4,0.9 -0.6,1.5 -0.6,1.8 0,2.6 0.6,4.5 1.7,5.6 1.1,1.1 2.3,1.7 3.6,1.7 2.2,0 3.9,-0.7 5.2,-2 1.3,-1.4 2.3,-3.9 2.9,-6.9 l 0.8,0 c 0.2,2.9 -0.1,5.3 -0.6,7.3 z"
id="path3"
inkscape:connector-curvature="0"
style="fill:#2e3192" /></svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -14,6 +14,8 @@ of modern terminals. It comes as one single, batteries-included, static binary w
As the name indicates, micro aims to be somewhat of a successor to the nano editor by being easy to install and use in a pinch, but micro also aims to be
enjoyable to use full time, whether you work in the terminal because you prefer it (like me), or because you need to (over ssh).
Use Ctrl-q to quit, Ctrl-s to save, and Ctrl-g to open the in-editor help menu.
.SH OPTIONS
.PP
\-clean
@@ -51,7 +53,7 @@ Enable debug mode (enables logging to ./log.txt)
Show the version number and information
.RE
Micro's plugin's can be managed at the command line with the following commands.
Micro's plugins can be managed at the command line with the following commands.
.RS 4
.PP
@@ -119,5 +121,5 @@ and to report any newly encountered bugs you may find. We strive to correct
bugs as swiftly as possible.
.SH COPYRIGHT
Copyright \(co 2020 Zachary Yedidia, et al.
See /usr/share/doc/micro/LICENSE and /usr/share/doc/micro/AUTHORS for more information.
Copyright \(co 2020 Zachary Yedidia, et al. MIT license.
See \fBhttps://github.com/zyedidia/micro\fP for details.

View File

@@ -6,10 +6,10 @@ Comment=Edit text files in a terminal
Icon=micro
Type=Application
Categories=terminal;TextEditor;
Categories=Utility;TextEditor;Development;
Keywords=text;editor;syntax;terminal;
Exec=micro %U
Exec=micro %F
StartupNotify=false
Terminal=true
MimeType=text/plain;text/x-chdr;text/x-csrc;text/x-c++hdr;text/x-c++src;text/x-java;text/x-dsrc;text/x-pascal;text/x-perl;text/x-python;application/x-php;application/x-httpd-php3;application/x-httpd-php4;application/x-httpd-php5;application/xml;text/html;text/css;text/x-sql;text/x-diff;

View File

@@ -10,8 +10,8 @@ import (
"sort"
"strings"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
)
func shouldContinue() bool {
@@ -41,6 +41,9 @@ func CleanConfig() {
return
}
fmt.Println("Cleaning default settings")
config.WriteSettings(filepath.Join(config.ConfigDir, "settings.json"))
// detect unused options
var unusedOptions []string
defaultSettings := config.DefaultAllSettings()
@@ -94,14 +97,13 @@ func CleanConfig() {
file, e := os.Open(fname)
if e == nil {
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&buffer)
if err != nil && f.Name() != "history" {
badFiles = append(badFiles, fname)
}
file.Close()
}
}
@@ -111,15 +113,21 @@ func CleanConfig() {
fmt.Printf("Removing badly formatted files in %s\n", filepath.Join(config.ConfigDir, "buffers"))
if shouldContinue() {
removed := 0
for _, f := range badFiles {
err := os.Remove(f)
if err != nil {
fmt.Println(err)
continue
}
removed++
}
fmt.Println("Removed badly formatted files")
if removed == 0 {
fmt.Println("Failed to remove files")
} else {
fmt.Printf("Removed %d badly formatted files\n", removed)
}
fmt.Print("\n\n")
}
}

View File

@@ -4,7 +4,7 @@ import (
"log"
"os"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/util"
)
// NullWriter simply sends writes into the void

View File

@@ -6,14 +6,14 @@ import (
lua "github.com/yuin/gopher-lua"
luar "layeh.com/gopher-luar"
"github.com/zyedidia/micro/internal/action"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/display"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/action"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
)
func init() {
@@ -53,6 +53,10 @@ func luaImportMicro() *lua.LTable {
ulua.L.SetField(pkg, "CurTab", luar.New(ulua.L, func() *action.Tab {
return action.MainTab()
}))
ulua.L.SetField(pkg, "Tabs", luar.New(ulua.L, func() *action.TabList {
return action.Tabs
}))
ulua.L.SetField(pkg, "Lock", luar.New(ulua.L, ulua.Lock))
return pkg
}
@@ -83,6 +87,7 @@ func luaImportMicroConfig() *lua.LTable {
ulua.L.SetField(pkg, "GetGlobalOption", luar.New(ulua.L, config.GetGlobalOption))
ulua.L.SetField(pkg, "SetGlobalOption", luar.New(ulua.L, action.SetGlobalOption))
ulua.L.SetField(pkg, "SetGlobalOptionNative", luar.New(ulua.L, action.SetGlobalOptionNative))
ulua.L.SetField(pkg, "ConfigDir", luar.New(ulua.L, config.ConfigDir))
return pkg
}
@@ -141,6 +146,7 @@ func luaImportMicroUtil() *lua.LTable {
ulua.L.SetField(pkg, "GetLeadingWhitespace", luar.New(ulua.L, util.LuaGetLeadingWhitespace))
ulua.L.SetField(pkg, "IsWordChar", luar.New(ulua.L, util.LuaIsWordChar))
ulua.L.SetField(pkg, "String", luar.New(ulua.L, util.String))
ulua.L.SetField(pkg, "CharacterCountInString", luar.New(ulua.L, util.CharacterCountInString))
ulua.L.SetField(pkg, "RuneStr", luar.New(ulua.L, func(r rune) string {
return string(r)
}))

View File

@@ -5,25 +5,30 @@ import (
"fmt"
"io/ioutil"
"os"
"os/signal"
"regexp"
"runtime"
"sort"
"strconv"
"syscall"
"time"
"github.com/go-errors/errors"
isatty "github.com/mattn/go-isatty"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/internal/action"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/action"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
)
var (
// Event channel
events chan tcell.Event
autosave chan bool
// Command line flags
@@ -43,7 +48,8 @@ func InitFlags() {
fmt.Println(" \tCleans the configuration directory")
fmt.Println("-config-dir dir")
fmt.Println(" \tSpecify a custom location for the configuration directory")
fmt.Println("[FILE]:LINE:COL")
fmt.Println("[FILE]:LINE:COL (if the `parsecursor` option is enabled)")
fmt.Println("+LINE:COL")
fmt.Println(" \tSpecify a line and column to start the cursor at when opening a buffer")
fmt.Println("-options")
fmt.Println(" \tShow all option help")
@@ -129,7 +135,7 @@ func DoPluginFlags() {
// LoadInput determines which files should be loaded into buffers
// based on the input stored in flag.Args()
func LoadInput() []*buffer.Buffer {
func LoadInput(args []string) []*buffer.Buffer {
// There are a number of ways micro should start given its input
// 1. If it is given a files in flag.Args(), it should open those
@@ -144,14 +150,47 @@ func LoadInput() []*buffer.Buffer {
var filename string
var input []byte
var err error
args := flag.Args()
buffers := make([]*buffer.Buffer, 0, len(args))
if len(args) > 0 {
btype := buffer.BTDefault
if !isatty.IsTerminal(os.Stdout.Fd()) {
btype = buffer.BTStdout
}
files := make([]string, 0, len(args))
flagStartPos := buffer.Loc{-1, -1}
flagr := regexp.MustCompile(`^\+(\d+)(?::(\d+))?$`)
for _, a := range args {
match := flagr.FindStringSubmatch(a)
if len(match) == 3 && match[2] != "" {
line, err := strconv.Atoi(match[1])
if err != nil {
screen.TermMessage(err)
continue
}
col, err := strconv.Atoi(match[2])
if err != nil {
screen.TermMessage(err)
continue
}
flagStartPos = buffer.Loc{col - 1, line - 1}
} else if len(match) == 3 && match[2] == "" {
line, err := strconv.Atoi(match[1])
if err != nil {
screen.TermMessage(err)
continue
}
flagStartPos = buffer.Loc{0, line - 1}
} else {
files = append(files, a)
}
}
if len(files) > 0 {
// Option 1
// We go through each file and load it
for i := 0; i < len(args); i++ {
buf, err := buffer.NewBufferFromFile(args[i], buffer.BTDefault)
for i := 0; i < len(files); i++ {
buf, err := buffer.NewBufferFromFileAtLoc(files[i], btype, flagStartPos)
if err != nil {
screen.TermMessage(err)
continue
@@ -168,17 +207,22 @@ func LoadInput() []*buffer.Buffer {
screen.TermMessage("Error reading from stdin: ", err)
input = []byte{}
}
buffers = append(buffers, buffer.NewBufferFromString(string(input), filename, buffer.BTDefault))
buffers = append(buffers, buffer.NewBufferFromStringAtLoc(string(input), filename, btype, flagStartPos))
} else {
// Option 3, just open an empty buffer
buffers = append(buffers, buffer.NewBufferFromString(string(input), filename, buffer.BTDefault))
buffers = append(buffers, buffer.NewBufferFromStringAtLoc(string(input), filename, btype, flagStartPos))
}
return buffers
}
func main() {
defer os.Exit(0)
defer func() {
if util.Stdout.Len() > 0 {
fmt.Fprint(os.Stdout, util.Stdout.String())
}
os.Exit(0)
}()
// runtime.SetCPUProfileRate(400)
// f, _ := os.Create("micro.prof")
@@ -201,7 +245,10 @@ func main() {
if err != nil {
screen.TermMessage(err)
}
config.InitGlobalSettings()
err = config.InitGlobalSettings()
if err != nil {
screen.TermMessage(err)
}
// flag options
for k, v := range optionFlags {
@@ -217,15 +264,36 @@ func main() {
DoPluginFlags()
screen.Init()
err = screen.Init()
if err != nil {
fmt.Println(err)
fmt.Println("Fatal: Micro could not initialize a Screen.")
os.Exit(1)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Kill, syscall.SIGTERM)
go func() {
<-c
if screen.Screen != nil {
screen.Screen.Fini()
}
os.Exit(0)
}()
m := clipboard.SetMethod(config.GetGlobalOption("clipboard").(string))
clipErr := clipboard.Initialize(m)
defer func() {
if err := recover(); err != nil {
screen.Screen.Fini()
if screen.Screen != nil {
screen.Screen.Fini()
}
fmt.Println("Micro encountered an error:", err)
// backup all open buffers
for _, b := range buffer.OpenBuffers {
b.Backup(false)
b.Backup()
}
// Print the stack trace too
fmt.Print(errors.Wrap(err, 2).ErrorStack())
@@ -246,7 +314,13 @@ func main() {
screen.TermMessage(err)
}
b := LoadInput()
err = config.RunPluginFn("preinit")
if err != nil {
screen.TermMessage(err)
}
args := flag.Args()
b := LoadInput(args)
if len(b) == 0 {
// No buffers to open
@@ -262,7 +336,16 @@ func main() {
screen.TermMessage(err)
}
events = make(chan tcell.Event)
err = config.RunPluginFn("postinit")
if err != nil {
screen.TermMessage(err)
}
if clipErr != nil {
action.InfoBar.Error(clipErr, " or change 'clipboard' option")
}
screen.Events = make(chan tcell.Event)
// Here is the event loop which runs in a separate thread
go func() {
@@ -271,7 +354,7 @@ func main() {
e := screen.Screen.PollEvent()
screen.Unlock()
if e != nil {
events <- e
screen.Events <- e
}
}
}()
@@ -284,7 +367,7 @@ func main() {
// wait for initial resize event
select {
case event := <-events:
case event := <-screen.Events:
action.Tabs.HandleEvent(event)
case <-time.After(10 * time.Millisecond):
// time out after 10ms
@@ -327,19 +410,28 @@ func DoEvent() {
select {
case f := <-shell.Jobs:
// If a new job has finished while running in the background we should execute the callback
ulua.Lock.Lock()
f.Function(f.Output, f.Args)
ulua.Lock.Unlock()
case <-config.Autosave:
ulua.Lock.Lock()
for _, b := range buffer.OpenBuffers {
b.Save()
}
ulua.Lock.Unlock()
case <-shell.CloseTerms:
case event = <-events:
case event = <-screen.Events:
case <-screen.DrawChan():
for len(screen.DrawChan()) > 0 {
<-screen.DrawChan()
}
}
ulua.Lock.Lock()
if action.InfoBar.HasPrompt {
action.InfoBar.HandleEvent(event)
} else {
action.Tabs.HandleEvent(event)
}
ulua.Lock.Unlock()
}

341
cmd/micro/micro_test.go Normal file
View File

@@ -0,0 +1,341 @@
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"testing"
"github.com/go-errors/errors"
"github.com/stretchr/testify/assert"
"github.com/zyedidia/micro/v2/internal/action"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell"
)
var tempDir string
var sim tcell.SimulationScreen
func init() {
screen.Events = make(chan tcell.Event, 8)
}
func startup(args []string) (tcell.SimulationScreen, error) {
var err error
tempDir, err = ioutil.TempDir("", "micro_test")
if err != nil {
return nil, err
}
err = config.InitConfigDir(tempDir)
if err != nil {
return nil, err
}
config.InitRuntimeFiles()
err = config.ReadSettings()
if err != nil {
return nil, err
}
err = config.InitGlobalSettings()
if err != nil {
return nil, err
}
s, err := screen.InitSimScreen()
if err != nil {
return nil, err
}
defer func() {
if err := recover(); err != nil {
screen.Screen.Fini()
fmt.Println("Micro encountered an error:", err)
// backup all open buffers
for _, b := range buffer.OpenBuffers {
b.Backup()
}
// Print the stack trace too
log.Fatalf(errors.Wrap(err, 2).ErrorStack())
os.Exit(1)
}
}()
err = config.LoadAllPlugins()
if err != nil {
screen.TermMessage(err)
}
action.InitBindings()
action.InitCommands()
err = config.InitColorscheme()
if err != nil {
return nil, err
}
b := LoadInput(args)
if len(b) == 0 {
return nil, errors.New("No buffers opened")
}
action.InitTabs(b)
action.InitGlobals()
err = config.RunPluginFn("init")
if err != nil {
return nil, err
}
s.InjectResize()
handleEvent()
return s, nil
}
func cleanup() {
os.RemoveAll(tempDir)
}
func handleEvent() {
screen.Lock()
e := screen.Screen.PollEvent()
screen.Unlock()
if e != nil {
screen.Events <- e
}
DoEvent()
}
func injectKey(key tcell.Key, r rune, mod tcell.ModMask) {
sim.InjectKey(key, r, mod)
handleEvent()
}
func injectMouse(x, y int, buttons tcell.ButtonMask, mod tcell.ModMask) {
sim.InjectMouse(x, y, buttons, mod)
handleEvent()
}
func injectString(str string) {
// the tcell simulation screen event channel can only handle
// 10 events at once, so we need to divide up the key events
// into chunks of 10 and handle the 10 events before sending
// another chunk of events
iters := len(str) / 10
extra := len(str) % 10
for i := 0; i < iters; i++ {
s := i * 10
e := i*10 + 10
sim.InjectKeyBytes([]byte(str[s:e]))
for i := 0; i < 10; i++ {
handleEvent()
}
}
sim.InjectKeyBytes([]byte(str[len(str)-extra:]))
for i := 0; i < extra; i++ {
handleEvent()
}
}
func openFile(file string) {
injectKey(tcell.KeyCtrlE, rune(tcell.KeyCtrlE), tcell.ModCtrl)
injectString(fmt.Sprintf("open %s", file))
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
}
func createTestFile(name string, content string) (string, error) {
testf, err := ioutil.TempFile("", name)
if err != nil {
return "", err
}
if _, err := testf.Write([]byte(content)); err != nil {
return "", err
}
if err := testf.Close(); err != nil {
return "", err
}
return testf.Name(), nil
}
func TestMain(m *testing.M) {
var err error
sim, err = startup([]string{})
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
retval := m.Run()
cleanup()
os.Exit(retval)
}
func TestSimpleEdit(t *testing.T) {
file, err := createTestFile("micro_simple_edit_test", "base content")
if err != nil {
t.Error(err)
return
}
defer os.Remove(file)
openFile(file)
var buf *buffer.Buffer
for _, b := range buffer.OpenBuffers {
if b.Path == file {
buf = b
}
}
if buf == nil {
t.Errorf("Could not find buffer %s", file)
return
}
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
injectKey(tcell.KeyUp, 0, tcell.ModNone)
injectString("first line")
// test both kinds of backspace
for i := 0; i < len("ne"); i++ {
injectKey(tcell.KeyBackspace, rune(tcell.KeyBackspace), tcell.ModNone)
}
for i := 0; i < len(" li"); i++ {
injectKey(tcell.KeyBackspace2, rune(tcell.KeyBackspace2), tcell.ModNone)
}
injectString("foobar")
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err := ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, "firstfoobar\nbase content\n", string(data))
}
func TestMouse(t *testing.T) {
file, err := createTestFile("micro_mouse_test", "base content")
if err != nil {
t.Error(err)
return
}
defer os.Remove(file)
openFile(file)
// buffer:
// base content
// the selections need to happen at different locations to avoid a double click
injectMouse(3, 0, tcell.Button1, tcell.ModNone)
injectKey(tcell.KeyLeft, 0, tcell.ModNone)
injectMouse(0, 0, tcell.ButtonNone, tcell.ModNone)
injectString("secondline")
// buffer:
// secondlinebase content
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
// buffer:
// secondline
// base content
injectMouse(2, 0, tcell.Button1, tcell.ModNone)
injectMouse(0, 0, tcell.ButtonNone, tcell.ModNone)
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
// buffer:
//
// secondline
// base content
injectKey(tcell.KeyUp, 0, tcell.ModNone)
injectString("firstline")
// buffer:
// firstline
// secondline
// base content
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err := ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, "firstline\nsecondline\nbase content\n", string(data))
}
var srTestStart = `foo
foo
foofoofoo
Ernleȝe foo æðelen
`
var srTest2 = `test_string
test_string
test_stringtest_stringtest_string
Ernleȝe test_string æðelen
`
var srTest3 = `test_foo
test_string
test_footest_stringtest_foo
Ernleȝe test_string æðelen
`
func TestSearchAndReplace(t *testing.T) {
file, err := createTestFile("micro_search_replace_test", srTestStart)
if err != nil {
t.Error(err)
return
}
defer os.Remove(file)
openFile(file)
injectKey(tcell.KeyCtrlE, rune(tcell.KeyCtrlE), tcell.ModCtrl)
injectString(fmt.Sprintf("replaceall %s %s", "foo", "test_string"))
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err := ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, srTest2, string(data))
injectKey(tcell.KeyCtrlE, rune(tcell.KeyCtrlE), tcell.ModCtrl)
injectString(fmt.Sprintf("replace %s %s", "string", "foo"))
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
injectString("ynyny")
injectKey(tcell.KeyEscape, 0, tcell.ModNone)
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err = ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, srTest3, string(data))
}
func TestMultiCursor(t *testing.T) {
// TODO
}
func TestSettingsPersistence(t *testing.T) {
// TODO
}
// more tests (rendering, tabs, plugins)?

10
go.mod
View File

@@ -1,4 +1,4 @@
module github.com/zyedidia/micro
module github.com/zyedidia/micro/v2
require (
github.com/blang/semver v3.5.1+incompatible
@@ -12,12 +12,12 @@ require (
github.com/sergi/go-diff v1.1.0
github.com/stretchr/testify v1.4.0
github.com/yuin/gopher-lua v0.0.0-20191220021717-ab39c6098bdb
github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197
github.com/zyedidia/clipboard v1.0.3
github.com/zyedidia/glob v0.0.0-20170209203856-dd4023a66dc3
github.com/zyedidia/highlight v0.0.0-20170330143449-201131ce5cf5
github.com/zyedidia/json5 v0.0.0-20200102012142-2da050b1a98d
github.com/zyedidia/pty v2.0.0+incompatible // indirect
github.com/zyedidia/tcell v1.4.4
github.com/zyedidia/tcell v1.4.10
github.com/zyedidia/terminal v0.0.0-20180726154117-533c623e2415
golang.org/x/text v0.3.2
gopkg.in/sourcemap.v1 v1.0.5 // indirect
@@ -25,4 +25,8 @@ require (
layeh.com/gopher-luar v1.0.7
)
replace github.com/kballard/go-shellquote => github.com/zyedidia/go-shellquote v0.0.0-20200613203517-eccd813c0655
replace github.com/mattn/go-runewidth => github.com/p-e-w/go-runewidth v0.0.10-0.20200613030200-3e1705c5c059
go 1.11

16
go.sum
View File

@@ -12,8 +12,6 @@ github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdk
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -23,10 +21,10 @@ github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tW
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/p-e-w/go-runewidth v0.0.10-0.20200613030200-3e1705c5c059 h1:/+h2b6i15wh4EWsFkfdNdBE1jjGA872tpXEyhPM5aYg=
github.com/p-e-w/go-runewidth v0.0.10-0.20200613030200-3e1705c5c059/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robertkrimen/otto v0.0.0-20191219234010-c382bd3c16ff h1:+6NUiITWwE5q1KO6SAfUX918c+Tab0+tGAM/mtdlUyA=
@@ -40,10 +38,12 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
github.com/yuin/gopher-lua v0.0.0-20191220021717-ab39c6098bdb h1:ZkM6LRnq40pR1Ox0hTHlnpkcOTuFIDQpZ1IN8rKKhX0=
github.com/yuin/gopher-lua v0.0.0-20191220021717-ab39c6098bdb/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197 h1:gYTNnAW6azuB3BbA6QYWO/H4F2ABSOjjw3Z03tlXd2c=
github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197/go.mod h1:WDk3p8GiZV9+xFWlSo8qreeoLhW6Ik692rqXk+cNeRY=
github.com/zyedidia/clipboard v1.0.3 h1:F/nCDVYMdbDWTmY8s8cJl0tnwX32q96IF09JHM14bUI=
github.com/zyedidia/clipboard v1.0.3/go.mod h1:zykFnZUXX0ErxqvYLUFEq7QDJKId8rmh2FgD0/Y8cjA=
github.com/zyedidia/glob v0.0.0-20170209203856-dd4023a66dc3 h1:oMHjjTLfGXVuyOQBYj5/td9WC0mw4g1xDBPovIqmHew=
github.com/zyedidia/glob v0.0.0-20170209203856-dd4023a66dc3/go.mod h1:YKbIYP//Eln8eDgAJGI3IDvR3s4Tv9Z9TGIOumiyQ5c=
github.com/zyedidia/go-shellquote v0.0.0-20200613203517-eccd813c0655 h1:Z3RhH6hvcSx7eX6Q/pP6YVsgea/1eMDG99vtWwi3nK4=
github.com/zyedidia/go-shellquote v0.0.0-20200613203517-eccd813c0655/go.mod h1:1sTqqO+kcYzZp43M5VsJe1tns9IzlSeC9jB6c2+o/5Y=
github.com/zyedidia/highlight v0.0.0-20170330143449-201131ce5cf5 h1:Zs6mpwXvlqpF9zHl5XaN0p5V4J9XvP+WBuiuXyIgqvc=
github.com/zyedidia/highlight v0.0.0-20170330143449-201131ce5cf5/go.mod h1:c1r+Ob9tUTPB0FKWO1+x+Hsc/zNa45WdGq7Y38Ybip0=
github.com/zyedidia/json5 v0.0.0-20200102012142-2da050b1a98d h1:zmDMkh22zXOB7gz8jFaI4GpI7llsPgzm38/jG0UgxjE=
@@ -52,8 +52,8 @@ github.com/zyedidia/poller v1.0.1 h1:Tt9S3AxAjXwWGNiC2TUdRJkQDZSzCBNVQ4xXiQ7440s
github.com/zyedidia/poller v1.0.1/go.mod h1:vZXJOHGDcuK08GXhF6IAY0ZFd2WcgOR5DOTp84Uk5eE=
github.com/zyedidia/pty v2.0.0+incompatible h1:Ou5vXL6tvjst+RV8sUFISbuKDnUJPhnpygApMFGweqw=
github.com/zyedidia/pty v2.0.0+incompatible/go.mod h1:4y9l9yJZNxRa7GB/fB+mmDmGkG3CqmzLf4vUxGGotEA=
github.com/zyedidia/tcell v1.4.4 h1:o34LXujNuSueuyTy+5eoQW+rQr8g0UbY8k1NczZyskQ=
github.com/zyedidia/tcell v1.4.4/go.mod h1:HhlbMSCcGX15rFDB+Q1Lk3pKEOocsCUAQC3zhZ9sadA=
github.com/zyedidia/tcell v1.4.10 h1:40iES9kNgiaTvp/wLTB4Elikx4uDPIPdV5fhI2EQiog=
github.com/zyedidia/tcell v1.4.10/go.mod h1:HhlbMSCcGX15rFDB+Q1Lk3pKEOocsCUAQC3zhZ9sadA=
github.com/zyedidia/terminal v0.0.0-20180726154117-533c623e2415 h1:752dTQ5OatJ9M5ULK2+9lor+nzyZz+LYDo3WGngg3Rc=
github.com/zyedidia/terminal v0.0.0-20180726154117-533c623e2415/go.mod h1:8leT8G0Cm8NoJHdrrKHyR9MirWoF4YW7pZh06B6H+1E=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=

View File

@@ -5,15 +5,14 @@ import (
"runtime"
"strings"
"time"
"unicode/utf8"
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/clipboard"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
)
@@ -60,7 +59,7 @@ func (h *BufPane) MousePress(e *tcell.EventMouse) bool {
h.doubleClick = false
h.Cursor.SelectLine()
h.Cursor.CopySelection("primary")
h.Cursor.CopySelection(clipboard.PrimaryReg)
} else {
// Double click
h.lastClickTime = time.Now()
@@ -69,7 +68,7 @@ func (h *BufPane) MousePress(e *tcell.EventMouse) bool {
h.tripleClick = false
h.Cursor.SelectWord()
h.Cursor.CopySelection("primary")
h.Cursor.CopySelection(clipboard.PrimaryReg)
}
} else {
h.doubleClick = false
@@ -175,7 +174,7 @@ func (h *BufPane) CursorRight() bool {
if tabstospaces && tabmovement {
tabsize := int(h.Buf.Settings["tabsize"].(float64))
line := h.Buf.LineBytes(h.Cursor.Y)
if h.Cursor.X+tabsize < utf8.RuneCount(line) && util.IsSpaces(line[h.Cursor.X:h.Cursor.X+tabsize]) && util.IsBytesWhitespace(line[0:h.Cursor.X]) {
if h.Cursor.X+tabsize < util.CharacterCount(line) && util.IsSpaces(line[h.Cursor.X:h.Cursor.X+tabsize]) && util.IsBytesWhitespace(line[0:h.Cursor.X]) {
for i := 0; i < tabsize; i++ {
h.Cursor.Right()
}
@@ -291,6 +290,19 @@ func (h *BufPane) StartOfText() bool {
return true
}
// StartOfTextToggle toggles the cursor between the start of the text of the line
// and the start of the line
func (h *BufPane) StartOfTextToggle() bool {
h.Cursor.Deselect(true)
if h.Cursor.IsStartOfText() {
h.Cursor.Start()
} else {
h.Cursor.StartOfText()
}
h.Relocate()
return true
}
// StartOfLine moves the cursor to the start of the line
func (h *BufPane) StartOfLine() bool {
h.Cursor.Deselect(true)
@@ -325,6 +337,22 @@ func (h *BufPane) SelectToStartOfText() bool {
return true
}
// SelectToStartOfTextToggle toggles the selection between the start of the text
// on the current line and the start of the line
func (h *BufPane) SelectToStartOfTextToggle() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
if h.Cursor.IsStartOfText() {
h.Cursor.Start()
} else {
h.Cursor.StartOfText()
}
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectToStartOfLine selects to the start of the current line
func (h *BufPane) SelectToStartOfLine() bool {
if !h.Cursor.HasSelection() {
@@ -457,7 +485,7 @@ func (h *BufPane) InsertNewline() bool {
// Remove the whitespaces if keepautoindent setting is off
if util.IsSpacesOrTabs(h.Buf.LineBytes(h.Cursor.Y-1)) && !h.Buf.Settings["keepautoindent"].(bool) {
line := h.Buf.LineBytes(h.Cursor.Y - 1)
h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y - 1}, buffer.Loc{X: utf8.RuneCount(line), Y: h.Cursor.Y - 1})
h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y - 1}, buffer.Loc{X: util.CharacterCount(line), Y: h.Cursor.Y - 1})
}
}
h.Cursor.LastVisualX = h.Cursor.GetVisualX()
@@ -482,7 +510,7 @@ func (h *BufPane) Backspace() bool {
// tab (tabSize number of spaces)
lineStart := util.SliceStart(h.Buf.LineBytes(h.Cursor.Y), h.Cursor.X)
tabSize := int(h.Buf.Settings["tabsize"].(float64))
if h.Buf.Settings["tabstospaces"].(bool) && util.IsSpaces(lineStart) && len(lineStart) != 0 && utf8.RuneCount(lineStart)%tabSize == 0 {
if h.Buf.Settings["tabstospaces"].(bool) && util.IsSpaces(lineStart) && len(lineStart) != 0 && util.CharacterCount(lineStart)%tabSize == 0 {
loc := h.Cursor.Loc
h.Buf.Remove(loc.Move(-tabSize, h.Buf), loc)
} else {
@@ -635,7 +663,12 @@ func (h *BufPane) Autocomplete() bool {
return false
}
if !util.IsNonAlphaNumeric(h.Cursor.RuneUnder(h.Cursor.X)) {
if h.Cursor.X == 0 {
return false
}
r := h.Cursor.RuneUnder(h.Cursor.X)
prev := h.Cursor.RuneUnder(h.Cursor.X - 1)
if !util.IsAutocomplete(prev) || !util.IsNonAlphaNumeric(r) {
// don't autocomplete if cursor is on alpha numeric character (middle of a word)
return false
}
@@ -699,6 +732,7 @@ func (h *BufPane) Save() bool {
}
// SaveAsCB performs a save as and does a callback at the very end (after all prompts have been resolved)
// The callback is only called if the save was successful
func (h *BufPane) SaveAsCB(action string, callback func()) bool {
InfoBar.Prompt("Filename: ", "", "Save", nil, func(resp string, canceled bool) {
if !canceled {
@@ -729,6 +763,7 @@ func (h *BufPane) SaveAs() bool {
// This function saves the buffer to `filename` and changes the buffer's path and name
// to `filename` if the save is successful
// The callback is only called if the save was successful
func (h *BufPane) saveBufToFile(filename string, action string, callback func()) bool {
err := h.Buf.SaveAs(filename)
if err != nil {
@@ -741,6 +776,9 @@ func (h *BufPane) saveBufToFile(filename string, action string, callback func())
h.Buf.Path = filename
h.Buf.SetName(filename)
InfoBar.Message("Saved " + filename)
if callback != nil {
callback()
}
}
}
if h.Buf.Settings["autosu"].(bool) {
@@ -751,9 +789,6 @@ func (h *BufPane) saveBufToFile(filename string, action string, callback func())
saveWithSudo()
h.completeAction(action)
}
if callback != nil {
callback()
}
})
return false
}
@@ -764,19 +799,56 @@ func (h *BufPane) saveBufToFile(filename string, action string, callback func())
h.Buf.Path = filename
h.Buf.SetName(filename)
InfoBar.Message("Saved " + filename)
}
if callback != nil {
callback()
if callback != nil {
callback()
}
}
return true
}
// Find opens a prompt and searches forward for the input
func (h *BufPane) Find() bool {
return h.find(true)
}
// FindLiteral is the same as Find() but does not support regular expressions
func (h *BufPane) FindLiteral() bool {
return h.find(false)
}
// Search searches for a given string/regex in the buffer and selects the next
// match if a match is found
// This function affects lastSearch and lastSearchRegex (saved searches) for
// use with FindNext and FindPrevious
func (h *BufPane) Search(str string, useRegex bool, searchDown bool) error {
match, found, err := h.Buf.FindNext(str, h.Buf.Start(), h.Buf.End(), h.Cursor.Loc, searchDown, useRegex)
if err != nil {
return err
}
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
h.lastSearch = str
h.lastSearchRegex = useRegex
h.Relocate()
} else {
h.Cursor.ResetSelection()
}
return nil
}
func (h *BufPane) find(useRegex bool) bool {
h.searchOrig = h.Cursor.Loc
InfoBar.Prompt("Find: ", "", "Find", func(resp string) {
prompt := "Find: "
if useRegex {
prompt = "Find (regex): "
}
InfoBar.Prompt(prompt, "", "Find", func(resp string) {
// Event callback
match, found, _ := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, true)
match, found, _ := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
@@ -791,7 +863,7 @@ func (h *BufPane) Find() bool {
}, func(resp string, canceled bool) {
// Finished callback
if !canceled {
match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, true)
match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
if err != nil {
InfoBar.Error(err)
}
@@ -802,6 +874,7 @@ func (h *BufPane) Find() bool {
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
h.lastSearch = resp
h.lastSearchRegex = useRegex
} else {
h.Cursor.ResetSelection()
InfoBar.Message("No matches found")
@@ -825,7 +898,7 @@ func (h *BufPane) FindNext() bool {
if h.Cursor.HasSelection() {
searchLoc = h.Cursor.CurSelection[1]
}
match, found, err := h.Buf.FindNext(h.lastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, true, true)
match, found, err := h.Buf.FindNext(h.lastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, true, h.lastSearchRegex)
if err != nil {
InfoBar.Error(err)
}
@@ -852,7 +925,7 @@ func (h *BufPane) FindPrevious() bool {
if h.Cursor.HasSelection() {
searchLoc = h.Cursor.CurSelection[0]
}
match, found, err := h.Buf.FindNext(h.lastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, false, true)
match, found, err := h.Buf.FindNext(h.lastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, false, h.lastSearchRegex)
if err != nil {
InfoBar.Error(err)
}
@@ -888,18 +961,29 @@ func (h *BufPane) Redo() bool {
// Copy the selection to the system clipboard
func (h *BufPane) Copy() bool {
if h.Cursor.HasSelection() {
h.Cursor.CopySelection("clipboard")
h.Cursor.CopySelection(clipboard.ClipboardReg)
h.freshClip = true
if clipboard.Unsupported {
InfoBar.Message("Copied selection (install xclip for external clipboard)")
} else {
InfoBar.Message("Copied selection")
}
InfoBar.Message("Copied selection")
}
h.Relocate()
return true
}
// Copy the current line to the clipboard
func (h *BufPane) CopyLine() bool {
if h.Cursor.HasSelection() {
return false
} else {
h.Cursor.SelectLine()
h.Cursor.CopySelection(clipboard.ClipboardReg)
h.freshClip = true
InfoBar.Message("Copied line")
}
h.Cursor.Deselect(true)
h.Relocate()
return true
}
// CutLine cuts the current line to the clipboard
func (h *BufPane) CutLine() bool {
h.Cursor.SelectLine()
@@ -908,10 +992,10 @@ func (h *BufPane) CutLine() bool {
}
if h.freshClip == true {
if h.Cursor.HasSelection() {
if clip, err := clipboard.ReadAll("clipboard"); err != nil {
// messenger.Error(err)
if clip, err := clipboard.Read(clipboard.ClipboardReg); err != nil {
InfoBar.Error(err)
} else {
clipboard.WriteAll(clip+string(h.Cursor.GetSelection()), "clipboard")
clipboard.WriteMulti(clip+string(h.Cursor.GetSelection()), clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
}
}
} else if time.Since(h.lastCutTime)/time.Second > 10*time.Second || h.freshClip == false {
@@ -929,7 +1013,7 @@ func (h *BufPane) CutLine() bool {
// Cut the selection to the system clipboard
func (h *BufPane) Cut() bool {
if h.Cursor.HasSelection() {
h.Cursor.CopySelection("clipboard")
h.Cursor.CopySelection(clipboard.ClipboardReg)
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
h.freshClip = true
@@ -979,15 +1063,26 @@ func (h *BufPane) MoveLinesUp() bool {
}
start := h.Cursor.CurSelection[0].Y
end := h.Cursor.CurSelection[1].Y
sel := 1
if start > end {
end, start = start, end
sel = 0
}
compensate := false
if h.Cursor.CurSelection[sel].X != 0 {
end++
} else {
compensate = true
}
h.Buf.MoveLinesUp(
start,
end,
)
h.Cursor.CurSelection[1].Y -= 1
if compensate {
h.Cursor.CurSelection[sel].Y -= 1
}
} else {
if h.Cursor.Loc.Y == 0 {
InfoBar.Message("Cannot move further up")
@@ -1012,8 +1107,14 @@ func (h *BufPane) MoveLinesDown() bool {
}
start := h.Cursor.CurSelection[0].Y
end := h.Cursor.CurSelection[1].Y
sel := 1
if start > end {
end, start = start, end
sel = 0
}
if h.Cursor.CurSelection[sel].X != 0 {
end++
}
h.Buf.MoveLinesDown(
@@ -1038,16 +1139,24 @@ func (h *BufPane) MoveLinesDown() bool {
// Paste whatever is in the system clipboard into the buffer
// Delete and paste if the user has a selection
func (h *BufPane) Paste() bool {
clip, _ := clipboard.ReadAll("clipboard")
h.paste(clip)
clip, err := clipboard.ReadMulti(clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
if err != nil {
InfoBar.Error(err)
} else {
h.paste(clip)
}
h.Relocate()
return true
}
// PastePrimary pastes from the primary clipboard (only use on linux)
func (h *BufPane) PastePrimary() bool {
clip, _ := clipboard.ReadAll("primary")
h.paste(clip)
clip, err := clipboard.ReadMulti(clipboard.PrimaryReg, h.Cursor.Num, h.Buf.NumCursors())
if err != nil {
InfoBar.Error(err)
} else {
h.paste(clip)
}
h.Relocate()
return true
}
@@ -1068,11 +1177,7 @@ func (h *BufPane) paste(clip string) {
h.Buf.Insert(h.Cursor.Loc, clip)
// h.Cursor.Loc = h.Cursor.Loc.Move(Count(clip), h.Buf)
h.freshClip = false
if clipboard.Unsupported {
InfoBar.Message("Pasted clipboard (install xclip for external clipboard)")
} else {
InfoBar.Message("Pasted clipboard")
}
InfoBar.Message("Pasted clipboard")
}
// JumpToMatchingBrace moves the cursor to the matching brace if it is
@@ -1120,6 +1225,16 @@ func (h *BufPane) OpenFile() bool {
return true
}
// OpenFile opens a new file in the buffer
func (h *BufPane) JumpLine() bool {
InfoBar.Prompt("> ", "goto ", "Command", nil, func(resp string, canceled bool) {
if !canceled {
h.HandleCommand(resp)
}
})
return true
}
// Start moves the viewport to the start of the buffer
func (h *BufPane) Start() bool {
v := h.GetView()
@@ -1324,6 +1439,18 @@ func (h *BufPane) Escape() bool {
return true
}
// Deselect deselects on the current cursor
func (h *BufPane) Deselect() bool {
h.Cursor.Deselect(true)
return true
}
// ClearInfo clears the infobar
func (h *BufPane) ClearInfo() bool {
InfoBar.Message("")
return true
}
// Quit this will close the current tab or view that is open
func (h *BufPane) Quit() bool {
quit := func() {
@@ -1407,8 +1534,9 @@ func (h *BufPane) AddTab() bool {
// PreviousTab switches to the previous tab in the tab list
func (h *BufPane) PreviousTab() bool {
a := Tabs.Active()
Tabs.SetActive(util.Clamp(a-1, 0, len(Tabs.List)-1))
tabsLen := len(Tabs.List)
a := Tabs.Active() + tabsLen
Tabs.SetActive((a - 1) % tabsLen)
return true
}
@@ -1416,7 +1544,8 @@ func (h *BufPane) PreviousTab() bool {
// NextTab switches to the next tab in the tab list
func (h *BufPane) NextTab() bool {
a := Tabs.Active()
Tabs.SetActive(util.Clamp(a+1, 0, len(Tabs.List)-1))
Tabs.SetActive((a + 1) % len(Tabs.List))
return true
}

View File

@@ -5,7 +5,7 @@ package action
import (
"syscall"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/screen"
)
// Suspend sends micro to the background. This is the same as pressing CtrlZ in most unix programs.

View File

@@ -6,15 +6,22 @@ import (
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"unicode"
"github.com/zyedidia/json5"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell"
)
var Binder = map[string]func(e Event, action string){
"info": InfoMapEvent,
"buffer": BufMapEvent,
"terminal": TermMapEvent,
}
func createBindingsIfNotExist(fname string) {
if _, e := os.Stat(fname); os.IsNotExist(e) {
ioutil.WriteFile(fname, []byte("{}"), 0644)
@@ -23,10 +30,9 @@ func createBindingsIfNotExist(fname string) {
// InitBindings intializes the bindings map by reading from bindings.json
func InitBindings() {
config.Bindings = DefaultBindings()
config.Bindings = DefaultBindings("buffer")
var parsed map[string]string
defaults := DefaultBindings()
var parsed map[string]interface{}
filename := filepath.Join(config.ConfigDir, "bindings.json")
createBindingsIfNotExist(filename)
@@ -44,34 +50,84 @@ func InitBindings() {
}
}
for k, v := range defaults {
BindKey(k, v)
for p, bind := range Binder {
defaults := DefaultBindings(p)
for k, v := range defaults {
BindKey(k, v, bind)
}
}
for k, v := range parsed {
BindKey(k, v)
switch val := v.(type) {
case string:
BindKey(k, val, Binder["buffer"])
case map[string]interface{}:
bind := Binder[k]
for e, a := range val {
s, ok := a.(string)
if !ok {
screen.TermMessage("Error reading bindings.json: non-string and non-map entry", k)
} else {
BindKey(e, s, bind)
}
}
default:
screen.TermMessage("Error reading bindings.json: non-string and non-map entry", k)
}
}
}
func BindKey(k, v string) {
event, ok := findEvent(k)
if !ok {
screen.TermMessage(k, "is not a bindable event")
func BindKey(k, v string, bind func(e Event, a string)) {
event, err := findEvent(k)
if err != nil {
screen.TermMessage(err)
}
switch e := event.(type) {
case KeyEvent:
BufMapKey(e, v)
case MouseEvent:
BufMapMouse(e, v)
case RawEvent:
BufMapKey(e, v)
}
bind(event, v)
config.Bindings[k] = v
// switch e := event.(type) {
// case KeyEvent:
// InfoMapKey(e, v)
// case KeySequenceEvent:
// InfoMapKey(e, v)
// case MouseEvent:
// InfoMapMouse(e, v)
// case RawEvent:
// InfoMapKey(e, v)
// }
}
// findEvent will find binding Key 'b' using string 'k'
func findEvent(k string) (b Event, ok bool) {
var r = regexp.MustCompile("<(.+?)>")
func findEvents(k string) (b KeySequenceEvent, ok bool, err error) {
var events []Event = nil
for len(k) > 0 {
groups := r.FindStringSubmatchIndex(k)
if len(groups) > 3 {
if events == nil {
events = make([]Event, 0, 3)
}
e, ok := findSingleEvent(k[groups[2]:groups[3]])
if !ok {
return KeySequenceEvent{}, false, errors.New("Invalid event " + k[groups[2]:groups[3]])
}
events = append(events, e)
k = k[groups[3]+1:]
} else {
return KeySequenceEvent{}, false, nil
}
}
return KeySequenceEvent{events}, true, nil
}
// findSingleEvent will find binding Key 'b' using string 'k'
func findSingleEvent(k string) (b Event, ok bool) {
modifiers := tcell.ModNone
// First, we'll strip off all the modifiers in the name and add them to the
@@ -162,6 +218,23 @@ modSearch:
return KeyEvent{}, false
}
func findEvent(k string) (Event, error) {
var event Event
event, ok, err := findEvents(k)
if err != nil {
return nil, err
}
if !ok {
event, ok = findSingleEvent(k)
if !ok {
return nil, errors.New(k + " is not a bindable event")
}
}
return event, nil
}
// TryBindKey tries to bind a key by writing to config.ConfigDir/bindings.json
// Returns true if the keybinding already existed and a possible error
func TryBindKey(k, v string, overwrite bool) (bool, error) {
@@ -181,14 +254,14 @@ func TryBindKey(k, v string, overwrite bool) (bool, error) {
return false, errors.New("Error reading bindings.json: " + err.Error())
}
key, ok := findEvent(k)
if !ok {
return false, errors.New("Invalid event " + k)
key, err := findEvent(k)
if err != nil {
return false, err
}
found := false
for ev := range parsed {
if e, ok := findEvent(ev); ok {
if e, err := findEvent(ev); err == nil {
if e == key {
if overwrite {
parsed[ev] = v
@@ -205,7 +278,7 @@ func TryBindKey(k, v string, overwrite bool) (bool, error) {
parsed[k] = v
}
BindKey(k, v)
BindKey(k, v, Binder["buffer"])
txt, _ := json.MarshalIndent(parsed, "", " ")
return true, ioutil.WriteFile(filename, append(txt, '\n'), 0644)
@@ -231,13 +304,13 @@ func UnbindKey(k string) error {
return errors.New("Error reading bindings.json: " + err.Error())
}
key, ok := findEvent(k)
if !ok {
return errors.New("Invalid event " + k)
key, err := findEvent(k)
if err != nil {
return err
}
for ev := range parsed {
if e, ok := findEvent(ev); ok {
if e, err := findEvent(ev); err == nil {
if e == key {
delete(parsed, ev)
break
@@ -245,10 +318,11 @@ func UnbindKey(k string) error {
}
}
defaults := DefaultBindings()
defaults := DefaultBindings("buffer")
if a, ok := defaults[k]; ok {
BindKey(k, a)
BindKey(k, a, Binder["buffer"])
} else if _, ok := config.Bindings[k]; ok {
BufUnmap(key)
delete(config.Bindings, k)
}

View File

@@ -7,25 +7,34 @@ import (
luar "layeh.com/gopher-luar"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/display"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell"
)
type BufKeyAction func(*BufPane) bool
type BufMouseAction func(*BufPane, *tcell.EventMouse) bool
var BufKeyBindings map[Event]BufKeyAction
var BufKeyStrings map[Event]string
var BufMouseBindings map[MouseEvent]BufMouseAction
var BufBindings *KeyTree
func BufKeyActionGeneral(a BufKeyAction) PaneKeyAction {
return func(p Pane) bool {
return a(p.(*BufPane))
}
}
func BufMouseActionGeneral(a BufMouseAction) PaneMouseAction {
return func(p Pane, me *tcell.EventMouse) bool {
return a(p.(*BufPane), me)
}
}
func init() {
BufKeyBindings = make(map[Event]BufKeyAction)
BufKeyStrings = make(map[Event]string)
BufMouseBindings = make(map[MouseEvent]BufMouseAction)
BufBindings = NewKeyTree()
}
func LuaAction(fn string) func(*BufPane) bool {
@@ -51,9 +60,17 @@ func LuaAction(fn string) func(*BufPane) bool {
}
}
// BufMapKey maps a key event to an action
func BufMapKey(k Event, action string) {
BufKeyStrings[k] = action
// BufMapKey maps an event to an action
func BufMapEvent(k Event, action string) {
switch e := k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
bufMapKey(e, action)
case MouseEvent:
bufMapMouse(e, action)
}
}
func bufMapKey(k Event, action string) {
var actionfns []func(*BufPane) bool
var names []string
var types []byte
@@ -103,15 +120,16 @@ func BufMapKey(k Event, action string) {
afn = f
names = append(names, a)
} else {
screen.TermMessage("Error:", a, "does not exist")
screen.TermMessage("Error in bindings: action", a, "does not exist")
continue
}
actionfns = append(actionfns, afn)
}
BufKeyBindings[k] = func(h *BufPane) bool {
bufAction := func(h *BufPane) bool {
cursors := h.Buf.GetCursors()
success := true
for i, a := range actionfns {
innerSuccess := true
for j, c := range cursors {
if c == nil {
continue
@@ -119,26 +137,43 @@ func BufMapKey(k Event, action string) {
h.Buf.SetCurCursor(c.Num)
h.Cursor = c
if i == 0 || (success && types[i-1] == '&') || (!success && types[i-1] == '|') || (types[i-1] == ',') {
success = h.execAction(a, names[i], j)
innerSuccess = innerSuccess && h.execAction(a, names[i], j)
} else {
break
}
}
// if the action changed the current pane, update the reference
h = MainTab().CurPane()
success = innerSuccess
}
return true
}
BufBindings.RegisterKeyBinding(k, BufKeyActionGeneral(bufAction))
}
// BufMapMouse maps a mouse event to an action
func BufMapMouse(k MouseEvent, action string) {
func bufMapMouse(k MouseEvent, action string) {
if f, ok := BufMouseActions[action]; ok {
BufMouseBindings[k] = f
BufBindings.RegisterMouseBinding(k, BufMouseActionGeneral(f))
} else {
delete(BufMouseBindings, k)
BufMapKey(k, action)
// TODO
// delete(BufMouseBindings, k)
bufMapKey(k, action)
}
}
// BufUnmap unmaps a key or mouse event from any action
func BufUnmap(k Event) {
// TODO
// delete(BufKeyBindings, k)
//
// switch e := k.(type) {
// case MouseEvent:
// delete(BufMouseBindings, e)
// }
}
// The BufPane connects the buffer and the window
// It provides a cursor (or multiple) and defines a set of actions
// that can be taken on the buffer
@@ -147,9 +182,13 @@ func BufMapMouse(k MouseEvent, action string) {
type BufPane struct {
display.BWindow
// Buf is the buffer this BufPane views
Buf *buffer.Buffer
// Bindings stores the association of key events and actions
bindings *KeyTree
Cursor *buffer.Cursor // the active cursor
// Cursor is the currently active buffer cursor
Cursor *buffer.Cursor
// Since tcell doesn't differentiate between a mouse release event
// and a mouse move event with no keys pressed, we need to keep
@@ -179,7 +218,8 @@ type BufPane struct {
tripleClick bool
// Last search stores the last successful search for FindNext and FindPrev
lastSearch string
lastSearch string
lastSearchRegex bool
// Should the current multiple cursor selection search based on word or
// based on selection (false for selection, true for word)
multiWord bool
@@ -318,7 +358,7 @@ func (h *BufPane) HandleEvent(event tcell.Event) {
switch e.Buttons() {
case tcell.Button1:
_, my := e.Position()
if h.Buf.Settings["statusline"].(bool) && my >= h.GetView().Y+h.GetView().Height-1 {
if h.Buf.Type.Kind != buffer.BTInfo.Kind && h.Buf.Settings["statusline"].(bool) && my >= h.GetView().Y+h.GetView().Height-1 {
cancel = true
}
case tcell.ButtonNone:
@@ -343,10 +383,11 @@ func (h *BufPane) HandleEvent(event tcell.Event) {
// release the mouse
// if !h.doubleClick && !h.tripleClick {
// h.Cursor.Loc = mouseLoc
// h.Cursor.SetSelectionEnd(h.Cursor.Loc)
// h.Cursor.CopySelection("primary")
// }
if h.Cursor.HasSelection() {
h.Cursor.CopySelection(clipboard.PrimaryReg)
}
h.mouseReleased = true
}
}
@@ -378,13 +419,26 @@ func (h *BufPane) HandleEvent(event tcell.Event) {
}
}
func (h *BufPane) Bindings() *KeyTree {
if h.bindings != nil {
return h.bindings
}
return BufBindings
}
// DoKeyEvent executes a key event by finding the action it is bound
// to and executing it (possibly multiple times for multiple cursors)
func (h *BufPane) DoKeyEvent(e Event) bool {
if action, ok := BufKeyBindings[e]; ok {
return action(h)
binds := h.Bindings()
action, more := binds.NextEvent(e, nil)
if action != nil && !more {
action(h)
binds.ResetEvents()
return true
} else if action == nil && !more {
binds.ResetEvents()
}
return false
return more
}
func (h *BufPane) execAction(action func(*BufPane) bool, name string, cursor int) bool {
@@ -418,22 +472,36 @@ func (h *BufPane) completeAction(action string) {
}
func (h *BufPane) HasKeyEvent(e Event) bool {
_, ok := BufKeyBindings[e]
return ok
// TODO
return true
// _, ok := BufKeyBindings[e]
// return ok
}
// DoMouseEvent executes a mouse event by finding the action it is bound
// to and executing it
func (h *BufPane) DoMouseEvent(e MouseEvent, te *tcell.EventMouse) bool {
if action, ok := BufMouseBindings[e]; ok {
if action(h, te) {
binds := h.Bindings()
action, _ := binds.NextEvent(e, te)
if action != nil {
if action(h) {
h.Relocate()
}
binds.ResetEvents()
return true
} else if h.HasKeyEvent(e) {
return h.DoKeyEvent(e)
}
// TODO
return false
// if action, ok := BufMouseBindings[e]; ok {
// if action(h, te) {
// h.Relocate()
// }
// return true
// } else if h.HasKeyEvent(e) {
// return h.DoKeyEvent(e)
// }
// return false
}
// DoRuneInsert inserts a given rune into the current buffer
@@ -516,106 +584,113 @@ func (h *BufPane) SetActive(b bool) {
// BufKeyActions contains the list of all possible key actions the bufhandler could execute
var BufKeyActions = map[string]BufKeyAction{
"CursorUp": (*BufPane).CursorUp,
"CursorDown": (*BufPane).CursorDown,
"CursorPageUp": (*BufPane).CursorPageUp,
"CursorPageDown": (*BufPane).CursorPageDown,
"CursorLeft": (*BufPane).CursorLeft,
"CursorRight": (*BufPane).CursorRight,
"CursorStart": (*BufPane).CursorStart,
"CursorEnd": (*BufPane).CursorEnd,
"SelectToStart": (*BufPane).SelectToStart,
"SelectToEnd": (*BufPane).SelectToEnd,
"SelectUp": (*BufPane).SelectUp,
"SelectDown": (*BufPane).SelectDown,
"SelectLeft": (*BufPane).SelectLeft,
"SelectRight": (*BufPane).SelectRight,
"WordRight": (*BufPane).WordRight,
"WordLeft": (*BufPane).WordLeft,
"SelectWordRight": (*BufPane).SelectWordRight,
"SelectWordLeft": (*BufPane).SelectWordLeft,
"DeleteWordRight": (*BufPane).DeleteWordRight,
"DeleteWordLeft": (*BufPane).DeleteWordLeft,
"SelectLine": (*BufPane).SelectLine,
"SelectToStartOfLine": (*BufPane).SelectToStartOfLine,
"SelectToStartOfText": (*BufPane).SelectToStartOfText,
"SelectToEndOfLine": (*BufPane).SelectToEndOfLine,
"ParagraphPrevious": (*BufPane).ParagraphPrevious,
"ParagraphNext": (*BufPane).ParagraphNext,
"InsertNewline": (*BufPane).InsertNewline,
"Backspace": (*BufPane).Backspace,
"Delete": (*BufPane).Delete,
"InsertTab": (*BufPane).InsertTab,
"Save": (*BufPane).Save,
"SaveAll": (*BufPane).SaveAll,
"SaveAs": (*BufPane).SaveAs,
"Find": (*BufPane).Find,
"FindNext": (*BufPane).FindNext,
"FindPrevious": (*BufPane).FindPrevious,
"Center": (*BufPane).Center,
"Undo": (*BufPane).Undo,
"Redo": (*BufPane).Redo,
"Copy": (*BufPane).Copy,
"Cut": (*BufPane).Cut,
"CutLine": (*BufPane).CutLine,
"DuplicateLine": (*BufPane).DuplicateLine,
"DeleteLine": (*BufPane).DeleteLine,
"MoveLinesUp": (*BufPane).MoveLinesUp,
"MoveLinesDown": (*BufPane).MoveLinesDown,
"IndentSelection": (*BufPane).IndentSelection,
"OutdentSelection": (*BufPane).OutdentSelection,
"Autocomplete": (*BufPane).Autocomplete,
"CycleAutocompleteBack": (*BufPane).CycleAutocompleteBack,
"OutdentLine": (*BufPane).OutdentLine,
"IndentLine": (*BufPane).IndentLine,
"Paste": (*BufPane).Paste,
"PastePrimary": (*BufPane).PastePrimary,
"SelectAll": (*BufPane).SelectAll,
"OpenFile": (*BufPane).OpenFile,
"Start": (*BufPane).Start,
"End": (*BufPane).End,
"PageUp": (*BufPane).PageUp,
"PageDown": (*BufPane).PageDown,
"SelectPageUp": (*BufPane).SelectPageUp,
"SelectPageDown": (*BufPane).SelectPageDown,
"HalfPageUp": (*BufPane).HalfPageUp,
"HalfPageDown": (*BufPane).HalfPageDown,
"StartOfText": (*BufPane).StartOfText,
"StartOfLine": (*BufPane).StartOfLine,
"EndOfLine": (*BufPane).EndOfLine,
"ToggleHelp": (*BufPane).ToggleHelp,
"ToggleKeyMenu": (*BufPane).ToggleKeyMenu,
"ToggleDiffGutter": (*BufPane).ToggleDiffGutter,
"ToggleRuler": (*BufPane).ToggleRuler,
"ClearStatus": (*BufPane).ClearStatus,
"ShellMode": (*BufPane).ShellMode,
"CommandMode": (*BufPane).CommandMode,
"ToggleOverwriteMode": (*BufPane).ToggleOverwriteMode,
"Escape": (*BufPane).Escape,
"Quit": (*BufPane).Quit,
"QuitAll": (*BufPane).QuitAll,
"AddTab": (*BufPane).AddTab,
"PreviousTab": (*BufPane).PreviousTab,
"NextTab": (*BufPane).NextTab,
"NextSplit": (*BufPane).NextSplit,
"PreviousSplit": (*BufPane).PreviousSplit,
"Unsplit": (*BufPane).Unsplit,
"VSplit": (*BufPane).VSplitAction,
"HSplit": (*BufPane).HSplitAction,
"ToggleMacro": (*BufPane).ToggleMacro,
"PlayMacro": (*BufPane).PlayMacro,
"Suspend": (*BufPane).Suspend,
"ScrollUp": (*BufPane).ScrollUpAction,
"ScrollDown": (*BufPane).ScrollDownAction,
"SpawnMultiCursor": (*BufPane).SpawnMultiCursor,
"SpawnMultiCursorUp": (*BufPane).SpawnMultiCursorUp,
"SpawnMultiCursorDown": (*BufPane).SpawnMultiCursorDown,
"SpawnMultiCursorSelect": (*BufPane).SpawnMultiCursorSelect,
"RemoveMultiCursor": (*BufPane).RemoveMultiCursor,
"RemoveAllMultiCursors": (*BufPane).RemoveAllMultiCursors,
"SkipMultiCursor": (*BufPane).SkipMultiCursor,
"JumpToMatchingBrace": (*BufPane).JumpToMatchingBrace,
"None": (*BufPane).None,
"CursorUp": (*BufPane).CursorUp,
"CursorDown": (*BufPane).CursorDown,
"CursorPageUp": (*BufPane).CursorPageUp,
"CursorPageDown": (*BufPane).CursorPageDown,
"CursorLeft": (*BufPane).CursorLeft,
"CursorRight": (*BufPane).CursorRight,
"CursorStart": (*BufPane).CursorStart,
"CursorEnd": (*BufPane).CursorEnd,
"SelectToStart": (*BufPane).SelectToStart,
"SelectToEnd": (*BufPane).SelectToEnd,
"SelectUp": (*BufPane).SelectUp,
"SelectDown": (*BufPane).SelectDown,
"SelectLeft": (*BufPane).SelectLeft,
"SelectRight": (*BufPane).SelectRight,
"WordRight": (*BufPane).WordRight,
"WordLeft": (*BufPane).WordLeft,
"SelectWordRight": (*BufPane).SelectWordRight,
"SelectWordLeft": (*BufPane).SelectWordLeft,
"DeleteWordRight": (*BufPane).DeleteWordRight,
"DeleteWordLeft": (*BufPane).DeleteWordLeft,
"SelectLine": (*BufPane).SelectLine,
"SelectToStartOfLine": (*BufPane).SelectToStartOfLine,
"SelectToStartOfText": (*BufPane).SelectToStartOfText,
"SelectToStartOfTextToggle": (*BufPane).SelectToStartOfTextToggle,
"SelectToEndOfLine": (*BufPane).SelectToEndOfLine,
"ParagraphPrevious": (*BufPane).ParagraphPrevious,
"ParagraphNext": (*BufPane).ParagraphNext,
"InsertNewline": (*BufPane).InsertNewline,
"Backspace": (*BufPane).Backspace,
"Delete": (*BufPane).Delete,
"InsertTab": (*BufPane).InsertTab,
"Save": (*BufPane).Save,
"SaveAll": (*BufPane).SaveAll,
"SaveAs": (*BufPane).SaveAs,
"Find": (*BufPane).Find,
"FindLiteral": (*BufPane).FindLiteral,
"FindNext": (*BufPane).FindNext,
"FindPrevious": (*BufPane).FindPrevious,
"Center": (*BufPane).Center,
"Undo": (*BufPane).Undo,
"Redo": (*BufPane).Redo,
"Copy": (*BufPane).Copy,
"CopyLine": (*BufPane).CopyLine,
"Cut": (*BufPane).Cut,
"CutLine": (*BufPane).CutLine,
"DuplicateLine": (*BufPane).DuplicateLine,
"DeleteLine": (*BufPane).DeleteLine,
"MoveLinesUp": (*BufPane).MoveLinesUp,
"MoveLinesDown": (*BufPane).MoveLinesDown,
"IndentSelection": (*BufPane).IndentSelection,
"OutdentSelection": (*BufPane).OutdentSelection,
"Autocomplete": (*BufPane).Autocomplete,
"CycleAutocompleteBack": (*BufPane).CycleAutocompleteBack,
"OutdentLine": (*BufPane).OutdentLine,
"IndentLine": (*BufPane).IndentLine,
"Paste": (*BufPane).Paste,
"PastePrimary": (*BufPane).PastePrimary,
"SelectAll": (*BufPane).SelectAll,
"OpenFile": (*BufPane).OpenFile,
"Start": (*BufPane).Start,
"End": (*BufPane).End,
"PageUp": (*BufPane).PageUp,
"PageDown": (*BufPane).PageDown,
"SelectPageUp": (*BufPane).SelectPageUp,
"SelectPageDown": (*BufPane).SelectPageDown,
"HalfPageUp": (*BufPane).HalfPageUp,
"HalfPageDown": (*BufPane).HalfPageDown,
"StartOfText": (*BufPane).StartOfText,
"StartOfTextToggle": (*BufPane).StartOfTextToggle,
"StartOfLine": (*BufPane).StartOfLine,
"EndOfLine": (*BufPane).EndOfLine,
"ToggleHelp": (*BufPane).ToggleHelp,
"ToggleKeyMenu": (*BufPane).ToggleKeyMenu,
"ToggleDiffGutter": (*BufPane).ToggleDiffGutter,
"ToggleRuler": (*BufPane).ToggleRuler,
"ClearStatus": (*BufPane).ClearStatus,
"ShellMode": (*BufPane).ShellMode,
"CommandMode": (*BufPane).CommandMode,
"ToggleOverwriteMode": (*BufPane).ToggleOverwriteMode,
"Escape": (*BufPane).Escape,
"Quit": (*BufPane).Quit,
"QuitAll": (*BufPane).QuitAll,
"AddTab": (*BufPane).AddTab,
"PreviousTab": (*BufPane).PreviousTab,
"NextTab": (*BufPane).NextTab,
"NextSplit": (*BufPane).NextSplit,
"PreviousSplit": (*BufPane).PreviousSplit,
"Unsplit": (*BufPane).Unsplit,
"VSplit": (*BufPane).VSplitAction,
"HSplit": (*BufPane).HSplitAction,
"ToggleMacro": (*BufPane).ToggleMacro,
"PlayMacro": (*BufPane).PlayMacro,
"Suspend": (*BufPane).Suspend,
"ScrollUp": (*BufPane).ScrollUpAction,
"ScrollDown": (*BufPane).ScrollDownAction,
"SpawnMultiCursor": (*BufPane).SpawnMultiCursor,
"SpawnMultiCursorUp": (*BufPane).SpawnMultiCursorUp,
"SpawnMultiCursorDown": (*BufPane).SpawnMultiCursorDown,
"SpawnMultiCursorSelect": (*BufPane).SpawnMultiCursorSelect,
"RemoveMultiCursor": (*BufPane).RemoveMultiCursor,
"RemoveAllMultiCursors": (*BufPane).RemoveAllMultiCursors,
"SkipMultiCursor": (*BufPane).SkipMultiCursor,
"JumpToMatchingBrace": (*BufPane).JumpToMatchingBrace,
"JumpLine": (*BufPane).JumpLine,
"Deselect": (*BufPane).Deselect,
"ClearInfo": (*BufPane).ClearInfo,
"None": (*BufPane).None,
// This was changed to InsertNewline but I don't want to break backwards compatibility
"InsertEnter": (*BufPane).InsertNewline,
@@ -632,54 +707,58 @@ var BufMouseActions = map[string]BufMouseAction{
// Generally actions that modify global editor state like quitting or
// saving should not be included in this list
var MultiActions = map[string]bool{
"CursorUp": true,
"CursorDown": true,
"CursorPageUp": true,
"CursorPageDown": true,
"CursorLeft": true,
"CursorRight": true,
"CursorStart": true,
"CursorEnd": true,
"SelectToStart": true,
"SelectToEnd": true,
"SelectUp": true,
"SelectDown": true,
"SelectLeft": true,
"SelectRight": true,
"WordRight": true,
"WordLeft": true,
"SelectWordRight": true,
"SelectWordLeft": true,
"DeleteWordRight": true,
"DeleteWordLeft": true,
"SelectLine": true,
"SelectToStartOfLine": true,
"SelectToStartOfText": true,
"SelectToEndOfLine": true,
"ParagraphPrevious": true,
"ParagraphNext": true,
"InsertNewline": true,
"Backspace": true,
"Delete": true,
"InsertTab": true,
"FindNext": true,
"FindPrevious": true,
"Cut": true,
"CutLine": true,
"DuplicateLine": true,
"DeleteLine": true,
"MoveLinesUp": true,
"MoveLinesDown": true,
"IndentSelection": true,
"OutdentSelection": true,
"OutdentLine": true,
"IndentLine": true,
"Paste": true,
"PastePrimary": true,
"SelectPageUp": true,
"SelectPageDown": true,
"StartOfLine": true,
"StartOfText": true,
"EndOfLine": true,
"JumpToMatchingBrace": true,
"CursorUp": true,
"CursorDown": true,
"CursorPageUp": true,
"CursorPageDown": true,
"CursorLeft": true,
"CursorRight": true,
"CursorStart": true,
"CursorEnd": true,
"SelectToStart": true,
"SelectToEnd": true,
"SelectUp": true,
"SelectDown": true,
"SelectLeft": true,
"SelectRight": true,
"WordRight": true,
"WordLeft": true,
"SelectWordRight": true,
"SelectWordLeft": true,
"DeleteWordRight": true,
"DeleteWordLeft": true,
"SelectLine": true,
"SelectToStartOfLine": true,
"SelectToStartOfText": true,
"SelectToStartOfTextToggle": true,
"SelectToEndOfLine": true,
"ParagraphPrevious": true,
"ParagraphNext": true,
"InsertNewline": true,
"Backspace": true,
"Delete": true,
"InsertTab": true,
"FindNext": true,
"FindPrevious": true,
"CopyLine": true,
"Copy": true,
"Cut": true,
"CutLine": true,
"DuplicateLine": true,
"DeleteLine": true,
"MoveLinesUp": true,
"MoveLinesDown": true,
"IndentSelection": true,
"OutdentSelection": true,
"OutdentLine": true,
"IndentLine": true,
"Paste": true,
"PastePrimary": true,
"SelectPageUp": true,
"SelectPageDown": true,
"StartOfLine": true,
"StartOfText": true,
"StartOfTextToggle": true,
"EndOfLine": true,
"JumpToMatchingBrace": true,
}

View File

@@ -10,14 +10,14 @@ import (
"regexp"
"strconv"
"strings"
"unicode/utf8"
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
)
// A Command contains information about how to execute a command
@@ -56,6 +56,7 @@ func InitCommands() {
"cd": {(*BufPane).CdCmd, buffer.FileComplete},
"pwd": {(*BufPane).PwdCmd, nil},
"open": {(*BufPane).OpenCmd, buffer.FileComplete},
"tabmove": {(*BufPane).TabMoveCmd, nil},
"tabswitch": {(*BufPane).TabSwitchCmd, nil},
"term": {(*BufPane).TermCmd, nil},
"memusage": {(*BufPane).MemUsageCmd, nil},
@@ -155,6 +156,56 @@ func (h *BufPane) TextFilterCmd(args []string) {
h.Buf.Insert(h.Cursor.Loc, bout.String())
}
// TabMoveCmd moves the current tab to a given index (starts at 1). The
// displaced tabs are moved up.
func (h *BufPane) TabMoveCmd(args []string) {
if len(args) <= 0 {
InfoBar.Error("Not enough arguments: provide an index, starting at 1")
return
}
if len(args[0]) <= 0 {
InfoBar.Error("Invalid argument: empty string")
return
}
num, err := strconv.Atoi(args[0])
if err != nil {
InfoBar.Error("Invalid argument: ", err)
return
}
// Preserve sign for relative move, if one exists
var shiftDirection byte
if strings.Contains("-+", string([]byte{args[0][0]})) {
shiftDirection = args[0][0]
}
// Relative positions -> absolute positions
idxFrom := Tabs.Active()
idxTo := 0
offset := util.Abs(num)
if shiftDirection == '-' {
idxTo = idxFrom - offset
} else if shiftDirection == '+' {
idxTo = idxFrom + offset
} else {
idxTo = offset - 1
}
// Restrain position to within the valid range
idxTo = util.Clamp(idxTo, 0, len(Tabs.List)-1)
activeTab := Tabs.List[idxFrom]
Tabs.RemoveTab(activeTab.ID())
Tabs.List = append(Tabs.List, nil)
copy(Tabs.List[idxTo+1:], Tabs.List[idxTo:])
Tabs.List[idxTo] = activeTab
Tabs.UpdateNames()
Tabs.SetActive(idxTo)
// InfoBar.Message(fmt.Sprintf("Moved tab from slot %d to %d", idxFrom+1, idxTo+1))
}
// TabSwitchCmd switches to a given tab either by name or by number
func (h *BufPane) TabSwitchCmd(args []string) {
if len(args) > 0 {
@@ -289,7 +340,10 @@ func ReloadConfig() {
if err != nil {
screen.TermMessage(err)
}
config.InitGlobalSettings()
err = config.InitGlobalSettings()
if err != nil {
screen.TermMessage(err)
}
InitBindings()
InitCommands()
@@ -427,6 +481,7 @@ func SetGlobalOptionNative(option string, nativeValue interface{}) error {
if !local {
config.GlobalSettings[option] = nativeValue
config.ModifiedSettings[option] = true
if option == "colorscheme" {
// LoadSyntaxFiles()
@@ -451,6 +506,12 @@ func SetGlobalOptionNative(option string, nativeValue interface{}) error {
}
} else if option == "paste" {
screen.Screen.SetPaste(nativeValue.(bool))
} else if option == "clipboard" {
m := clipboard.SetMethod(nativeValue.(string))
err := clipboard.Initialize(m)
if err != nil {
return err
}
} else {
for _, pl := range config.Plugins {
if option == pl.Name {
@@ -651,8 +712,11 @@ func (h *BufPane) GotoCmd(args []string) {
InfoBar.Error(err)
return
}
if line < 0 {
line = h.Buf.LinesNum() + 1 + line
}
line = util.Clamp(line-1, 0, h.Buf.LinesNum()-1)
col = util.Clamp(col-1, 0, utf8.RuneCount(h.Buf.LineBytes(line)))
col = util.Clamp(col-1, 0, util.CharacterCount(h.Buf.LineBytes(line)))
h.Cursor.GotoLoc(buffer.Loc{col, line})
} else {
line, err := strconv.Atoi(args[0])
@@ -660,6 +724,9 @@ func (h *BufPane) GotoCmd(args []string) {
InfoBar.Error(err)
return
}
if line < 0 {
line = h.Buf.LinesNum() + 1 + line
}
line = util.Clamp(line-1, 0, h.Buf.LinesNum()-1)
h.Cursor.GotoLoc(buffer.Loc{0, line})
}
@@ -733,7 +800,8 @@ func (h *BufPane) ReplaceCmd(args []string) {
nreplaced := 0
start := h.Buf.Start()
end := h.Buf.End()
if h.Cursor.HasSelection() {
selection := h.Cursor.HasSelection()
if selection {
start = h.Cursor.CurSelection[0]
end = h.Cursor.CurSelection[1]
}
@@ -744,7 +812,7 @@ func (h *BufPane) ReplaceCmd(args []string) {
return l.GreaterEqual(start) && l.LessEqual(end)
}
searchLoc := start
searchLoc := h.Cursor.Loc
var doReplacement func()
doReplacement = func() {
locs, found, err := h.Buf.FindNext(search, start, end, searchLoc, true, !noRegex)
@@ -755,11 +823,15 @@ func (h *BufPane) ReplaceCmd(args []string) {
if !found || !inRange(locs[0]) || !inRange(locs[1]) {
h.Cursor.ResetSelection()
h.Buf.RelocateCursors()
return
}
h.Cursor.SetSelectionStart(locs[0])
h.Cursor.SetSelectionEnd(locs[1])
h.Cursor.GotoLoc(locs[0])
h.Relocate()
InfoBar.YNPrompt("Perform replacement (y,n,esc)", func(yes, canceled bool) {
if !canceled && yes {
@@ -767,12 +839,14 @@ func (h *BufPane) ReplaceCmd(args []string) {
searchLoc = locs[0]
searchLoc.X += nrunes + locs[0].Diff(locs[1], h.Buf)
end.Move(nrunes, h.Buf)
if end.Y == locs[1].Y {
end = end.Move(nrunes, h.Buf)
}
h.Cursor.Loc = searchLoc
nreplaced++
} else if !canceled && !yes {
searchLoc = locs[0]
searchLoc.X += utf8.RuneCount(replace)
searchLoc.X += util.CharacterCount(replace)
} else if canceled {
h.Cursor.ResetSelection()
h.Buf.RelocateCursors()
@@ -785,14 +859,22 @@ func (h *BufPane) ReplaceCmd(args []string) {
}
h.Buf.RelocateCursors()
h.Relocate()
var s string
if nreplaced > 1 {
InfoBar.Message("Replaced ", nreplaced, " occurrences of ", search)
s = fmt.Sprintf("Replaced %d occurrences of %s", nreplaced, search)
} else if nreplaced == 1 {
InfoBar.Message("Replaced ", nreplaced, " occurrence of ", search)
s = fmt.Sprintf("Replaced 1 occurrence of %s", search)
} else {
InfoBar.Message("Nothing matched ", search)
s = fmt.Sprintf("Nothing matched %s", search)
}
if selection {
s += " in selection"
}
InfoBar.Message(s)
}
// ReplaceAllCmd replaces search term all at once
@@ -821,7 +903,11 @@ func (h *BufPane) TermCmd(args []string) {
term := func(i int, newtab bool) {
t := new(shell.Terminal)
t.Start(args, false, true, nil, nil)
err := t.Start(args, false, true, nil, nil)
if err != nil {
InfoBar.Error(err)
return
}
id := h.ID()
if newtab {

View File

@@ -0,0 +1,21 @@
package action
var termdefaults = map[string]string{
"<Ctrl-q><Ctrl-q>": "Exit",
"<Ctrl-e><Ctrl-e>": "CommandMode",
"<Ctrl-w><Ctrl-w>": "NextSplit",
}
// DefaultBindings returns a map containing micro's default keybindings
func DefaultBindings(pane string) map[string]string {
switch pane {
case "info":
return infodefaults
case "buffer":
return bufdefaults
case "terminal":
return termdefaults
default:
return map[string]string{}
}
}

View File

@@ -1,107 +1,179 @@
package action
// DefaultBindings returns a map containing micro's default keybindings
func DefaultBindings() map[string]string {
return map[string]string{
"Up": "CursorUp",
"Down": "CursorDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "WordLeft",
"AltRight": "WordRight",
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "StartOfText",
"CtrlRight": "EndOfLine",
"CtrlShiftLeft": "SelectToStartOfText",
"ShiftHome": "SelectToStartOfText",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "CycleAutocompleteBack|OutdentSelection|OutdentLine",
"CtrlO": "OpenFile",
"CtrlS": "Save",
"CtrlF": "Find",
"CtrlN": "FindNext",
"CtrlP": "FindPrevious",
"CtrlZ": "Undo",
"CtrlY": "Redo",
"CtrlC": "Copy",
"CtrlX": "Cut",
"CtrlK": "CutLine",
"CtrlD": "DuplicateLine",
"CtrlV": "Paste",
"CtrlA": "SelectAll",
"CtrlT": "AddTab",
"Alt,": "PreviousTab",
"Alt.": "NextTab",
"Home": "StartOfText",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"PageUp": "CursorPageUp",
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"CtrlG": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"CtrlR": "ToggleRuler",
"CtrlL": "command-edit:goto ",
"Delete": "Delete",
"CtrlB": "ShellMode",
"CtrlQ": "Quit",
"CtrlE": "CommandMode",
"CtrlW": "NextSplit",
"CtrlU": "ToggleMacro",
"CtrlJ": "PlayMacro",
"Insert": "ToggleOverwriteMode",
var bufdefaults = map[string]string{
"Up": "CursorUp",
"Down": "CursorDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "WordLeft",
"AltRight": "WordRight",
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "StartOfTextToggle",
"CtrlRight": "EndOfLine",
"CtrlShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "CycleAutocompleteBack|OutdentSelection|OutdentLine",
"Ctrl-o": "OpenFile",
"Ctrl-s": "Save",
"Ctrl-f": "Find",
"Ctrl-n": "FindNext",
"Ctrl-p": "FindPrevious",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-d": "DuplicateLine",
"Ctrl-v": "Paste",
"Ctrl-a": "SelectAll",
"Ctrl-t": "AddTab",
"Alt-,": "PreviousTab",
"Alt-.": "NextTab",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"PageUp": "CursorPageUp",
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"Ctrl-g": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"Ctrl-r": "ToggleRuler",
"Ctrl-l": "command-edit:goto ",
"Delete": "Delete",
"Ctrl-b": "ShellMode",
"Ctrl-q": "Quit",
"Ctrl-e": "CommandMode",
"Ctrl-w": "NextSplit",
"Ctrl-u": "ToggleMacro",
"Ctrl-j": "PlayMacro",
"Insert": "ToggleOverwriteMode",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// "Alt-p": "CursorUp",
// "Alt-n": "CursorDown",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// "Alt-p": "CursorUp",
// "Alt-n": "CursorDown",
// Integration with file managers
"F2": "Save",
"F3": "Find",
"F4": "Quit",
"F7": "Find",
"F10": "Quit",
"Esc": "Escape",
// Integration with file managers
"F2": "Save",
"F3": "Find",
"F4": "Quit",
"F7": "Find",
"F10": "Quit",
"Esc": "Escape,Deselect,ClearInfo,RemoveAllMultiCursors",
// Mouse bindings
"MouseWheelUp": "ScrollUp",
"MouseWheelDown": "ScrollDown",
"MouseLeft": "MousePress",
"MouseMiddle": "PastePrimary",
"Ctrl-MouseLeft": "MouseMultiCursor",
// Mouse bindings
"MouseWheelUp": "ScrollUp",
"MouseWheelDown": "ScrollDown",
"MouseLeft": "MousePress",
"MouseMiddle": "PastePrimary",
"Ctrl-MouseLeft": "MouseMultiCursor",
"Alt-n": "SpawnMultiCursor",
"AltShiftUp": "SpawnMultiCursorUp",
"AltShiftDown": "SpawnMultiCursorDown",
"Alt-m": "SpawnMultiCursorSelect",
"Alt-p": "RemoveMultiCursor",
"Alt-c": "RemoveAllMultiCursors",
"Alt-x": "SkipMultiCursor",
}
"Alt-n": "SpawnMultiCursor",
"AltShiftUp": "SpawnMultiCursorUp",
"AltShiftDown": "SpawnMultiCursorDown",
"Alt-m": "SpawnMultiCursorSelect",
"Alt-p": "RemoveMultiCursor",
"Alt-c": "RemoveAllMultiCursors",
"Alt-x": "SkipMultiCursor",
}
var infodefaults = map[string]string{
"Up": "HistoryUp",
"Down": "HistoryDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "WordLeft",
"AltRight": "WordRight",
"AltUp": "CursorStart",
"AltDown": "CursorEnd",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "StartOfTextToggle",
"CtrlRight": "EndOfLine",
"CtrlShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Enter": "ExecuteCommand",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "CommandComplete",
"Backtab": "CycleAutocompleteBack",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-v": "Paste",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"Delete": "Delete",
"Ctrl-q": "AbortCommand",
"Ctrl-e": "EndOfLine",
"Ctrl-a": "StartOfLine",
"Ctrl-w": "DeleteWordLeft",
"Insert": "ToggleOverwriteMode",
"Ctrl-b": "WordLeft",
"Ctrl-f": "WordRight",
"Ctrl-d": "DeleteWordLeft",
"Ctrl-m": "ExecuteCommand",
"Ctrl-n": "HistoryDown",
"Ctrl-p": "HistoryUp",
"Ctrl-u": "SelectToStart",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// Integration with file managers
"F10": "AbortCommand",
"Esc": "AbortCommand",
// Mouse bindings
"MouseWheelUp": "HistoryUp",
"MouseWheelDown": "HistoryDown",
"MouseLeft": "MousePress",
"MouseMiddle": "PastePrimary",
}

View File

@@ -2,108 +2,180 @@
package action
// DefaultBindings returns a map containing micro's default keybindings
func DefaultBindings() map[string]string {
return map[string]string{
"Up": "CursorUp",
"Down": "CursorDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"CtrlLeft": "WordLeft",
"CtrlRight": "WordRight",
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"CtrlShiftRight": "SelectWordRight",
"CtrlShiftLeft": "SelectWordLeft",
"AltLeft": "StartOfText",
"AltRight": "EndOfLine",
"AltShiftLeft": "SelectToStartOfText",
"ShiftHome": "SelectToStartOfText",
"AltShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "CycleAutocompleteBack|OutdentSelection|OutdentLine",
"CtrlO": "OpenFile",
"CtrlS": "Save",
"CtrlF": "Find",
"CtrlN": "FindNext",
"CtrlP": "FindPrevious",
"CtrlZ": "Undo",
"CtrlY": "Redo",
"CtrlC": "Copy",
"CtrlX": "Cut",
"CtrlK": "CutLine",
"CtrlD": "DuplicateLine",
"CtrlV": "Paste",
"CtrlA": "SelectAll",
"CtrlT": "AddTab",
"Alt,": "PreviousTab",
"Alt.": "NextTab",
"Home": "StartOfText",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"PageUp": "CursorPageUp",
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"CtrlG": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"CtrlR": "ToggleRuler",
"CtrlL": "command-edit:goto ",
"Delete": "Delete",
"CtrlB": "ShellMode",
"CtrlQ": "Quit",
"CtrlE": "CommandMode",
"CtrlW": "NextSplit",
"CtrlU": "ToggleMacro",
"CtrlJ": "PlayMacro",
"Insert": "ToggleOverwriteMode",
var bufdefaults = map[string]string{
"Up": "CursorUp",
"Down": "CursorDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"CtrlLeft": "WordLeft",
"CtrlRight": "WordRight",
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"CtrlShiftRight": "SelectWordRight",
"CtrlShiftLeft": "SelectWordLeft",
"AltLeft": "StartOfTextToggle",
"AltRight": "EndOfLine",
"AltShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"AltShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "CycleAutocompleteBack|OutdentSelection|OutdentLine",
"Ctrl-o": "OpenFile",
"Ctrl-s": "Save",
"Ctrl-f": "Find",
"Ctrl-n": "FindNext",
"Ctrl-p": "FindPrevious",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-d": "DuplicateLine",
"Ctrl-v": "Paste",
"Ctrl-a": "SelectAll",
"Ctrl-t": "AddTab",
"Alt-,": "PreviousTab",
"Alt-.": "NextTab",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"PageUp": "CursorPageUp",
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"Ctrl-g": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"Ctrl-r": "ToggleRuler",
"Ctrl-l": "command-edit:goto ",
"Delete": "Delete",
"Ctrl-b": "ShellMode",
"Ctrl-q": "Quit",
"Ctrl-e": "CommandMode",
"Ctrl-w": "NextSplit",
"Ctrl-u": "ToggleMacro",
"Ctrl-j": "PlayMacro",
"Insert": "ToggleOverwriteMode",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// "Alt-p": "CursorUp",
// "Alt-n": "CursorDown",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// "Alt-p": "CursorUp",
// "Alt-n": "CursorDown",
// Integration with file managers
"F2": "Save",
"F3": "Find",
"F4": "Quit",
"F7": "Find",
"F10": "Quit",
"Esc": "Escape",
// Integration with file managers
"F2": "Save",
"F3": "Find",
"F4": "Quit",
"F7": "Find",
"F10": "Quit",
"Esc": "Escape,Deselect,ClearInfo,RemoveAllMultiCursors",
// Mouse bindings
"MouseWheelUp": "ScrollUp",
"MouseWheelDown": "ScrollDown",
"MouseLeft": "MousePress",
"MouseMiddle": "PastePrimary",
"Ctrl-MouseLeft": "MouseMultiCursor",
// Mouse bindings
"MouseWheelUp": "ScrollUp",
"MouseWheelDown": "ScrollDown",
"MouseLeft": "MousePress",
"MouseMiddle": "PastePrimary",
"Ctrl-MouseLeft": "MouseMultiCursor",
"Alt-n": "SpawnMultiCursor",
"Alt-m": "SpawnMultiCursorSelect",
"AltShiftUp": "SpawnMultiCursorUp",
"AltShiftDown": "SpawnMultiCursorDown",
"Alt-p": "RemoveMultiCursor",
"Alt-c": "RemoveAllMultiCursors",
"Alt-x": "SkipMultiCursor",
}
"Alt-n": "SpawnMultiCursor",
"Alt-m": "SpawnMultiCursorSelect",
"AltShiftUp": "SpawnMultiCursorUp",
"AltShiftDown": "SpawnMultiCursorDown",
"Alt-p": "RemoveMultiCursor",
"Alt-c": "RemoveAllMultiCursors",
"Alt-x": "SkipMultiCursor",
}
var infodefaults = map[string]string{
"Up": "HistoryUp",
"Down": "HistoryDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "StartOfTextToggle",
"AltRight": "EndOfLine",
"AltUp": "CursorStart",
"AltDown": "CursorEnd",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "WordLeft",
"CtrlRight": "WordRight",
"CtrlShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Enter": "ExecuteCommand",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "CommandComplete",
"Backtab": "CycleAutocompleteBack",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-v": "Paste",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"Delete": "Delete",
"Ctrl-q": "AbortCommand",
"Ctrl-e": "EndOfLine",
"Ctrl-a": "StartOfLine",
"Ctrl-w": "DeleteWordLeft",
"Insert": "ToggleOverwriteMode",
"Ctrl-b": "WordLeft",
"Ctrl-f": "WordRight",
"Ctrl-d": "DeleteWordLeft",
"Ctrl-m": "ExecuteCommand",
"Ctrl-n": "HistoryDown",
"Ctrl-p": "HistoryUp",
"Ctrl-u": "SelectToStart",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// Integration with file managers
"F10": "AbortCommand",
"Esc": "AbortCommand",
// Mouse bindings
"MouseWheelUp": "HistoryUp",
"MouseWheelDown": "HistoryDown",
"MouseLeft": "MousePress",
"MouseMiddle": "PastePrimary",
}

View File

@@ -1,10 +1,17 @@
package action
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/zyedidia/tcell"
)
type Event interface{}
type Event interface {
Name() string
}
// RawEvent is simply an escape code
// We allow users to directly bind escape codes
@@ -13,6 +20,10 @@ type RawEvent struct {
esc string
}
func (r RawEvent) Name() string {
return r.esc
}
// KeyEvent is a key event containing a key code,
// some possible modifiers (alt, ctrl, etc...) and
// a rune if it was simply a character press
@@ -22,6 +33,63 @@ type KeyEvent struct {
code tcell.Key
mod tcell.ModMask
r rune
any bool
}
func (k KeyEvent) Name() string {
if k.any {
return "<any>"
}
s := ""
m := []string{}
if k.mod&tcell.ModShift != 0 {
m = append(m, "Shift")
}
if k.mod&tcell.ModAlt != 0 {
m = append(m, "Alt")
}
if k.mod&tcell.ModMeta != 0 {
m = append(m, "Meta")
}
if k.mod&tcell.ModCtrl != 0 {
m = append(m, "Ctrl")
}
ok := false
if s, ok = tcell.KeyNames[k.code]; !ok {
if k.code == tcell.KeyRune {
s = string(k.r)
} else {
s = fmt.Sprintf("Key[%d,%d]", k.code, int(k.r))
}
}
if len(m) != 0 {
if k.mod&tcell.ModCtrl != 0 && strings.HasPrefix(s, "Ctrl-") {
s = s[5:]
if len(s) == 1 {
s = strings.ToLower(s)
}
}
return fmt.Sprintf("%s-%s", strings.Join(m, "-"), s)
}
return s
}
// A KeySequence defines a list of consecutive
// events. All events in the sequence must be KeyEvents
// or MouseEvents.
type KeySequenceEvent struct {
keys []Event
}
func (k KeySequenceEvent) Name() string {
buf := bytes.Buffer{}
for _, e := range k.keys {
buf.WriteByte('<')
buf.WriteString(e.Name())
buf.WriteByte('>')
}
return buf.String()
}
// MouseEvent is a mouse event with a mouse button and
@@ -31,8 +99,54 @@ type MouseEvent struct {
mod tcell.ModMask
}
type KeyAction func(Handler) bool
type MouseAction func(Handler, tcell.EventMouse) bool
func (m MouseEvent) Name() string {
mod := ""
if m.mod&tcell.ModShift != 0 {
mod = "Shift-"
}
if m.mod&tcell.ModAlt != 0 {
mod = "Alt-"
}
if m.mod&tcell.ModMeta != 0 {
mod = "Meta-"
}
if m.mod&tcell.ModCtrl != 0 {
mod = "Ctrl-"
}
for k, v := range mouseEvents {
if v == m.btn {
return fmt.Sprintf("%s%s", mod, k)
}
}
return ""
}
// ConstructEvent takes a tcell event and returns a micro
// event. Note that tcell events can't express certain
// micro events such as key sequences. This function is
// mostly used for debugging/raw panes or constructing
// intermediate micro events while parsing a sequence.
func ConstructEvent(event tcell.Event) (Event, error) {
switch e := event.(type) {
case *tcell.EventKey:
return KeyEvent{
code: e.Key(),
mod: e.Modifiers(),
r: e.Rune(),
}, nil
case *tcell.EventRaw:
return RawEvent{
esc: e.EscSeq(),
}, nil
case *tcell.EventMouse:
return MouseEvent{
btn: e.Buttons(),
mod: e.Modifiers(),
}, nil
}
return nil, errors.New("No micro event equivalent")
}
// A Handler will take a tcell event and execute it
// appropriately

View File

@@ -1,6 +1,6 @@
package action
import "github.com/zyedidia/micro/internal/buffer"
import "github.com/zyedidia/micro/v2/internal/buffer"
var InfoBar *InfoPane
var LogBufPane *BufPane

View File

@@ -5,9 +5,9 @@ import (
"sort"
"strings"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
)
// This file is meant (for now) for autocompletion in command mode, not
@@ -186,6 +186,16 @@ func OptionValueComplete(b *buffer.Buffer) ([]string, []string) {
if strings.HasPrefix("doas", input) {
suggestions = append(suggestions, "doas")
}
case "clipboard":
if strings.HasPrefix("external", input) {
suggestions = append(suggestions, "external")
}
if strings.HasPrefix("internal", input) {
suggestions = append(suggestions, "internal")
}
if strings.HasPrefix("terminal", input) {
suggestions = append(suggestions, "terminal")
}
}
}
sort.Strings(suggestions)

View File

@@ -2,17 +2,57 @@ package action
import (
"bytes"
"strings"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/display"
"github.com/zyedidia/micro/internal/info"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/micro/v2/internal/info"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
)
type InfoKeyAction func(*InfoPane)
var InfoBindings *KeyTree
var InfoBufBindings *KeyTree
func init() {
InfoBindings = NewKeyTree()
InfoBufBindings = NewKeyTree()
}
func InfoMapEvent(k Event, action string) {
switch e := k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
infoMapKey(e, action)
case MouseEvent:
infoMapMouse(e, action)
}
}
func infoMapKey(k Event, action string) {
if f, ok := InfoKeyActions[action]; ok {
InfoBindings.RegisterKeyBinding(k, InfoKeyActionGeneral(f))
} else if f, ok := BufKeyActions[action]; ok {
InfoBufBindings.RegisterKeyBinding(k, BufKeyActionGeneral(f))
}
}
func infoMapMouse(k MouseEvent, action string) {
// TODO: map mouse
if f, ok := BufMouseActions[action]; ok {
InfoBufBindings.RegisterMouseBinding(k, BufMouseActionGeneral(f))
} else {
infoMapKey(k, action)
}
}
func InfoKeyActionGeneral(a InfoKeyAction) PaneKeyAction {
return func(p Pane) bool {
a(p.(*InfoPane))
return true
}
}
type InfoPane struct {
*BufPane
*info.InfoBuf
@@ -22,6 +62,7 @@ func NewInfoPane(ib *info.InfoBuf, w display.BWindow, tab *Tab) *InfoPane {
ip := new(InfoPane)
ip.InfoBuf = ib
ip.BufPane = NewBufPane(ib.Buffer, w, tab)
ip.BufPane.bindings = InfoBufBindings
return ip
}
@@ -76,104 +117,43 @@ func (h *InfoPane) HandleEvent(event tcell.Event) {
// DoKeyEvent executes a key event for the command bar, doing any overridden actions
func (h *InfoPane) DoKeyEvent(e KeyEvent) bool {
done := false
if action, ok := BufKeyBindings[e]; ok {
estr := BufKeyStrings[e]
for _, s := range InfoNones {
if s == estr {
return false
}
}
for s, a := range InfoOverrides {
// TODO this is a hack and really we should have support
// for having binding overrides for different buffers
if strings.HasPrefix(estr, s) {
done = true
a(h)
break
}
}
if !done {
done = action(h.BufPane)
action, more := InfoBindings.NextEvent(e, nil)
if action != nil && !more {
action(h)
InfoBindings.ResetEvents()
return true
} else if action == nil && !more {
InfoBindings.ResetEvents()
// return false //TODO:?
}
if !more {
action, more = InfoBufBindings.NextEvent(e, nil)
if action != nil && !more {
done := action(h.BufPane)
InfoBufBindings.ResetEvents()
return done
} else if action == nil && !more {
InfoBufBindings.ResetEvents()
}
}
return done
return more
}
// InfoNones is a list of actions that should have no effect when executed
// by an infohandler
var InfoNones = []string{
"Save",
"SaveAll",
"SaveAs",
"Find",
"FindNext",
"FindPrevious",
"Center",
"DuplicateLine",
"MoveLinesUp",
"MoveLinesDown",
"OpenFile",
"Start",
"End",
"PageUp",
"PageDown",
"SelectPageUp",
"SelectPageDown",
"HalfPageUp",
"HalfPageDown",
"ToggleHelp",
"ToggleKeyMenu",
"ToggleDiffGutter",
"ToggleRuler",
"JumpLine",
"ClearStatus",
"ShellMode",
"CommandMode",
"AddTab",
"PreviousTab",
"NextTab",
"NextSplit",
"PreviousSplit",
"Unsplit",
"VSplit",
"HSplit",
"ToggleMacro",
"PlayMacro",
"Suspend",
"ScrollUp",
"ScrollDown",
"SpawnMultiCursor",
"SpawnMultiCursorSelect",
"RemoveMultiCursor",
"RemoveAllMultiCursors",
"SkipMultiCursor",
}
// InfoOverrides is the list of actions which have been overridden
// by the infohandler
var InfoOverrides = map[string]InfoKeyAction{
"CursorUp": (*InfoPane).CursorUp,
"CursorDown": (*InfoPane).CursorDown,
"InsertNewline": (*InfoPane).InsertNewline,
"Autocomplete": (*InfoPane).Autocomplete,
"Escape": (*InfoPane).Escape,
"Quit": (*InfoPane).Quit,
"QuitAll": (*InfoPane).QuitAll,
}
// CursorUp cycles history up
func (h *InfoPane) CursorUp() {
// HistoryUp cycles history up
func (h *InfoPane) HistoryUp() {
h.UpHistory(h.History[h.PromptType])
}
// CursorDown cycles history down
func (h *InfoPane) CursorDown() {
// HistoryDown cycles history down
func (h *InfoPane) HistoryDown() {
h.DownHistory(h.History[h.PromptType])
}
// Autocomplete begins autocompletion
func (h *InfoPane) Autocomplete() {
func (h *InfoPane) CommandComplete() {
b := h.Buf
if b.HasSuggestions {
b.CycleAutocomplete(true)
@@ -201,24 +181,23 @@ func (h *InfoPane) Autocomplete() {
}
}
// InsertNewline completes the prompt
func (h *InfoPane) InsertNewline() {
// ExecuteCommand completes the prompt
func (h *InfoPane) ExecuteCommand() {
if !h.HasYN {
h.DonePrompt(false)
}
}
// Quit cancels the prompt
func (h *InfoPane) Quit() {
// AbortCommand cancels the prompt
func (h *InfoPane) AbortCommand() {
h.DonePrompt(true)
}
// QuitAll cancels the prompt
func (h *InfoPane) QuitAll() {
h.DonePrompt(true)
}
// Escape cancels the prompt
func (h *InfoPane) Escape() {
h.DonePrompt(true)
// InfoKeyActions contains the list of all possible key actions the infopane could execute
var InfoKeyActions = map[string]InfoKeyAction{
"HistoryUp": (*InfoPane).HistoryUp,
"HistoryDown": (*InfoPane).HistoryDown,
"CommandComplete": (*InfoPane).CommandComplete,
"ExecuteCommand": (*InfoPane).ExecuteCommand,
"AbortCommand": (*InfoPane).AbortCommand,
}

259
internal/action/keytree.go Normal file
View File

@@ -0,0 +1,259 @@
package action
import (
"bytes"
"github.com/zyedidia/tcell"
)
type PaneKeyAction func(Pane) bool
type PaneMouseAction func(Pane, *tcell.EventMouse) bool
type PaneKeyAnyAction func(Pane, []KeyEvent) bool
// A KeyTreeNode stores a single node in the KeyTree (trie). The
// children are stored as a map, and any node may store a list of
// actions (the list will be nil if no actions correspond to a certain
// node)
type KeyTreeNode struct {
children map[Event]*KeyTreeNode
// Only one of these actions may be active in the current
// mode, and only one will be returned. If multiple actions
// are active, it is undefined which one will be the one
// returned.
actions []TreeAction
}
func NewKeyTreeNode() *KeyTreeNode {
n := new(KeyTreeNode)
n.children = make(map[Event]*KeyTreeNode)
n.actions = []TreeAction{}
return n
}
// A TreeAction stores an action, and a set of mode constraints for
// the action to be active.
type TreeAction struct {
// only one of these can be non-nil
action PaneKeyAction
any PaneKeyAnyAction
mouse PaneMouseAction
modes []ModeConstraint
}
// A KeyTree is a data structure for storing keybindings. It maps
// key events to actions, and maintains a set of currently enabled
// modes, which affects the action that is returned for a key event.
// The tree acts like a Trie for Events to handle sequence events.
type KeyTree struct {
root *KeyTreeNode
modes map[string]bool
cursor KeyTreeCursor
}
// A KeyTreeCursor keeps track of the current location within the
// tree, and stores any information from previous events that may
// be needed to execute the action (values of wildcard events or
// mouse events)
type KeyTreeCursor struct {
node *KeyTreeNode
recordedEvents []Event
wildcards []KeyEvent
mouseInfo *tcell.EventMouse
}
// MakeClosure uses the information stored in a key tree cursor to construct
// a PaneKeyAction from a TreeAction (which may have a PaneKeyAction, PaneMouseAction,
// or AnyAction)
func (k *KeyTreeCursor) MakeClosure(a TreeAction) PaneKeyAction {
if a.action != nil {
return a.action
} else if a.any != nil {
return func(p Pane) bool {
return a.any(p, k.wildcards)
}
} else if a.mouse != nil {
return func(p Pane) bool {
return a.mouse(p, k.mouseInfo)
}
}
return nil
}
// NewKeyTree allocates and returns an empty key tree
func NewKeyTree() *KeyTree {
root := NewKeyTreeNode()
tree := new(KeyTree)
tree.root = root
tree.modes = make(map[string]bool)
tree.cursor = KeyTreeCursor{
node: root,
wildcards: []KeyEvent{},
mouseInfo: nil,
}
return tree
}
// A ModeConstraint specifies that an action can only be executed
// while a certain mode is enabled or disabled.
type ModeConstraint struct {
mode string
disabled bool
}
// RegisterKeyBinding registers a PaneKeyAction with an Event.
func (k *KeyTree) RegisterKeyBinding(e Event, a PaneKeyAction) {
k.registerBinding(e, TreeAction{
action: a,
any: nil,
mouse: nil,
modes: nil,
})
}
// RegisterKeyAnyBinding registers a PaneKeyAnyAction with an Event.
// The event should contain an "any" event.
func (k *KeyTree) RegisterKeyAnyBinding(e Event, a PaneKeyAnyAction) {
k.registerBinding(e, TreeAction{
action: nil,
any: a,
mouse: nil,
modes: nil,
})
}
// RegisterMouseBinding registers a PaneMouseAction with an Event.
// The event should contain a mouse event.
func (k *KeyTree) RegisterMouseBinding(e Event, a PaneMouseAction) {
k.registerBinding(e, TreeAction{
action: nil,
any: nil,
mouse: a,
modes: nil,
})
}
func (k *KeyTree) registerBinding(e Event, a TreeAction) {
switch ev := e.(type) {
case KeyEvent, MouseEvent:
newNode, ok := k.root.children[e]
if !ok {
newNode = NewKeyTreeNode()
k.root.children[e] = newNode
}
newNode.actions = append(newNode.actions, a)
case KeySequenceEvent:
n := k.root
for _, key := range ev.keys {
newNode, ok := n.children[key]
if !ok {
newNode = NewKeyTreeNode()
n.children[key] = newNode
}
n = newNode
}
n.actions = append(n.actions, a)
}
}
// NextEvent returns the action for the current sequence where e is the next
// event. Even if the action was registered as a PaneKeyAnyAction or PaneMouseAction,
// it will be returned as a PaneKeyAction closure where the appropriate arguments
// have been provided.
// If no action is associated with the given Event, or mode constraints are not
// met for that action, nil is returned.
// A boolean is returned to indicate if there is a conflict with this action. A
// conflict occurs when there is an active action for this event but there are
// bindings associated with further sequences starting with this event. The
// calling function can decide what to do about the conflict (e.g. use a
// timeout).
func (k *KeyTree) NextEvent(e Event, mouse *tcell.EventMouse) (PaneKeyAction, bool) {
n := k.cursor.node
c, ok := n.children[e]
if !ok {
return nil, false
}
more := len(c.children) > 0
k.cursor.node = c
k.cursor.recordedEvents = append(k.cursor.recordedEvents, e)
switch ev := e.(type) {
case KeyEvent:
if ev.any {
k.cursor.wildcards = append(k.cursor.wildcards, ev)
}
case MouseEvent:
k.cursor.mouseInfo = mouse
}
if len(c.actions) > 0 {
// check if actions are active
for _, a := range c.actions {
active := true
for _, mc := range a.modes {
// if any mode constraint is not met, the action is not active
hasMode := k.modes[mc.mode]
if hasMode != mc.disabled {
active = false
}
}
if active {
// the first active action to be found is returned
return k.cursor.MakeClosure(a), more
}
}
}
return nil, more
}
// ResetEvents sets the current sequence back to the initial value.
func (k *KeyTree) ResetEvents() {
k.cursor.node = k.root
k.cursor.wildcards = []KeyEvent{}
k.cursor.recordedEvents = []Event{}
k.cursor.mouseInfo = nil
}
// CurrentEventsStr returns the list of recorded events as a string
func (k *KeyTree) RecordedEventsStr() string {
buf := &bytes.Buffer{}
for _, e := range k.cursor.recordedEvents {
buf.WriteString(e.Name())
}
return buf.String()
}
// DeleteBinding removes any currently active actions associated with the
// given event.
func (k *KeyTree) DeleteBinding(e Event) {
}
// DeleteAllBindings removes all actions associated with the given event,
// regardless of whether they are active or not.
func (k *KeyTree) DeleteAllBindings(e Event) {
}
// SetMode enables or disabled a given mode
func (k *KeyTree) SetMode(mode string, en bool) {
k.modes[mode] = en
}
// HasMode returns if the given mode is currently active
func (k *KeyTree) HasMode(mode string) bool {
return k.modes[mode]
}

View File

@@ -1,7 +1,7 @@
package action
import (
"github.com/zyedidia/micro/internal/display"
"github.com/zyedidia/micro/v2/internal/display"
)
type Pane interface {

View File

@@ -4,8 +4,8 @@ import (
"fmt"
"reflect"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/display"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/tcell"
)
@@ -35,6 +35,13 @@ func (h *RawPane) HandleEvent(event tcell.Event) {
}
h.Buf.Insert(h.Cursor.Loc, reflect.TypeOf(event).String()[7:])
e, err := ConstructEvent(event)
if err == nil {
h.Buf.Insert(h.Cursor.Loc, fmt.Sprintf(": %s", e.Name()))
}
h.Buf.Insert(h.Cursor.Loc, fmt.Sprintf(": %q\n", event.EscSeq()))
h.Relocate()
}

View File

@@ -1,11 +1,11 @@
package action
import (
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/display"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/views"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/views"
"github.com/zyedidia/tcell"
)
@@ -166,6 +166,8 @@ type Tab struct {
active int
resizing *views.Node // node currently being resized
// captures whether the mouse is released
release bool
}
// NewTabFromBuffer creates a new tab from the given buffer
@@ -173,6 +175,7 @@ func NewTabFromBuffer(x, y, width, height int, b *buffer.Buffer) *Tab {
t := new(Tab)
t.Node = views.NewRoot(x, y, width, height)
t.UIWindow = display.NewUIWindow(t.Node)
t.release = true
e := NewBufPaneFromBuf(b, t)
e.SetID(t.ID())
@@ -185,6 +188,7 @@ func NewTabFromPane(x, y, width, height int, pane Pane) *Tab {
t := new(Tab)
t.Node = views.NewRoot(x, y, width, height)
t.UIWindow = display.NewUIWindow(t.Node)
t.release = true
pane.SetTab(t)
pane.SetID(t.ID())
@@ -203,6 +207,8 @@ func (t *Tab) HandleEvent(event tcell.Event) {
mx, my := e.Position()
switch e.Buttons() {
case tcell.Button1:
wasReleased := t.release
t.release = false
if t.resizing != nil {
var size int
if t.resizing.Kind == views.STVert {
@@ -215,22 +221,24 @@ func (t *Tab) HandleEvent(event tcell.Event) {
return
}
resizeID := t.GetMouseSplitID(buffer.Loc{mx, my})
if resizeID != 0 {
t.resizing = t.GetNode(uint64(resizeID))
return
}
if wasReleased {
t.resizing = t.GetMouseSplitNode(buffer.Loc{mx, my})
if t.resizing != nil {
return
}
for i, p := range t.Panes {
v := p.GetView()
inpane := mx >= v.X && mx < v.X+v.Width && my >= v.Y && my < v.Y+v.Height
if inpane {
t.SetActive(i)
break
for i, p := range t.Panes {
v := p.GetView()
inpane := mx >= v.X && mx < v.X+v.Width && my >= v.Y && my < v.Y+v.Height
if inpane {
t.SetActive(i)
break
}
}
}
case tcell.ButtonNone:
t.resizing = nil
t.release = true
default:
for _, p := range t.Panes {
v := p.GetView()

View File

@@ -4,7 +4,7 @@ package action
import (
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/v2/internal/shell"
)
// TermEmuSupported is a constant that marks if the terminal emulator is supported
@@ -24,7 +24,10 @@ func RunTermEmulator(h *BufPane, input string, wait bool, getOutput bool, callba
}
t := new(shell.Terminal)
t.Start(args, getOutput, wait, callback, userargs)
err = t.Start(args, getOutput, wait, callback, userargs)
if err != nil {
return err
}
h.AddTab()
id := MainTab().Panes[0].ID()

View File

@@ -4,14 +4,49 @@ import (
"errors"
"runtime"
"github.com/zyedidia/clipboard"
"github.com/zyedidia/micro/internal/display"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/tcell"
"github.com/zyedidia/terminal"
)
type TermKeyAction func(*TermPane)
var TermBindings *KeyTree
func init() {
TermBindings = NewKeyTree()
}
func TermKeyActionGeneral(a TermKeyAction) PaneKeyAction {
return func(p Pane) bool {
a(p.(*TermPane))
return true
}
}
func TermMapEvent(k Event, action string) {
switch e := k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
termMapKey(e, action)
case MouseEvent:
termMapMouse(e, action)
}
}
func termMapKey(k Event, action string) {
if f, ok := TermKeyActions[action]; ok {
TermBindings.RegisterKeyBinding(k, TermKeyActionGeneral(f))
}
}
func termMapMouse(k MouseEvent, action string) {
// TODO: map mouse
termMapKey(k, action)
}
type TermPane struct {
*shell.Terminal
display.Window
@@ -53,6 +88,7 @@ func (t *TermPane) Tab() *Tab {
func (t *TermPane) Close() {}
// Quit closes this termpane
func (t *TermPane) Quit() {
t.Close()
if len(MainTab().Panes) > 1 {
@@ -66,6 +102,7 @@ func (t *TermPane) Quit() {
}
}
// Unsplit removes this split
func (t *TermPane) Unsplit() {
n := MainTab().GetNode(t.id)
n.Unsplit()
@@ -81,6 +118,26 @@ func (t *TermPane) Unsplit() {
// copy-paste
func (t *TermPane) HandleEvent(event tcell.Event) {
if e, ok := event.(*tcell.EventKey); ok {
ke := KeyEvent{
code: e.Key(),
mod: e.Modifiers(),
r: e.Rune(),
}
action, more := TermBindings.NextEvent(ke, nil)
if !more {
if action != nil {
action(t)
TermBindings.ResetEvents()
return
}
TermBindings.ResetEvents()
}
if more {
return
}
if t.Status == shell.TTDone {
switch e.Key() {
case tcell.KeyEscape, tcell.KeyCtrlQ, tcell.KeyEnter:
@@ -90,7 +147,7 @@ func (t *TermPane) HandleEvent(event tcell.Event) {
}
}
if e.Key() == tcell.KeyCtrlC && t.HasSelection() {
clipboard.WriteAll(t.GetSelection(t.GetView().Width), "clipboard")
clipboard.Write(t.GetSelection(t.GetView().Width), clipboard.ClipboardReg)
InfoBar.Message("Copied selection to clipboard")
} else if t.Status != shell.TTDone {
t.WriteString(event.EscSeq())
@@ -134,6 +191,41 @@ func (t *TermPane) HandleEvent(event tcell.Event) {
}
}
// Exit closes the termpane
func (t *TermPane) Exit() {
t.Terminal.Close()
t.Quit()
}
// CommandMode opens the termpane's command mode
func (t *TermPane) CommandMode() {
InfoBar.Prompt("> ", "", "TerminalCommand", nil, func(resp string, canceled bool) {
if !canceled {
t.HandleCommand(resp)
}
})
}
// NextSplit moves to the next split
func (t *TermPane) NextSplit() {
a := t.tab.active
if a < len(t.tab.Panes)-1 {
a++
} else {
a = 0
}
t.tab.SetActive(a)
}
// HandleCommand handles a command for the term pane
func (t *TermPane) HandleCommand(input string) {
InfoBar.Error("Commands are unsupported in term for now")
}
// TermKeyActions contains the list of all possible key actions the termpane could execute
var TermKeyActions = map[string]TermKeyAction{
"Exit": (*TermPane).Exit,
"CommandMode": (*TermPane).CommandMode,
"NextSplit": (*TermPane).NextSplit,
}

View File

@@ -6,9 +6,8 @@ import (
"os"
"sort"
"strings"
"unicode/utf8"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/util"
)
// A Completer is a function that takes a buffer and returns info
@@ -54,7 +53,7 @@ func (b *Buffer) CycleAutocomplete(forward bool) {
start := c.Loc
end := c.Loc
if prevSuggestion < len(b.Suggestions) && prevSuggestion >= 0 {
start = end.Move(-utf8.RuneCountInString(b.Completions[prevSuggestion]), b)
start = end.Move(-util.CharacterCountInString(b.Completions[prevSuggestion]), b)
} else {
// end = start.Move(1, b)
}
@@ -82,7 +81,7 @@ func GetWord(b *Buffer) ([]byte, int) {
args := bytes.FieldsFunc(l, util.IsNonAlphaNumeric)
input := args[len(args)-1]
return input, c.X - utf8.RuneCount(input)
return input, c.X - util.CharacterCount(input)
}
// GetArg gets the most recent word (separated by ' ' only)
@@ -98,7 +97,7 @@ func GetArg(b *Buffer) (string, int) {
if i == len(args)-1 {
break
}
argstart += utf8.RuneCount(a) + 1
argstart += util.CharacterCount(a) + 1
}
return input, argstart
@@ -162,7 +161,7 @@ func BufferComplete(b *Buffer) ([]string, []string) {
return []string{}, []string{}
}
inputLen := utf8.RuneCount(input)
inputLen := util.CharacterCount(input)
suggestionsSet := make(map[string]struct{})
@@ -171,7 +170,7 @@ func BufferComplete(b *Buffer) ([]string, []string) {
l := b.LineBytes(i)
words := bytes.FieldsFunc(l, util.IsNonAlphaNumeric)
for _, w := range words {
if bytes.HasPrefix(w, input) && utf8.RuneCount(w) > inputLen {
if bytes.HasPrefix(w, input) && util.CharacterCount(w) > inputLen {
strw := string(w)
if _, ok := suggestionsSet[strw]; !ok {
suggestionsSet[strw] = struct{}{}
@@ -184,7 +183,7 @@ func BufferComplete(b *Buffer) ([]string, []string) {
l := b.LineBytes(i)
words := bytes.FieldsFunc(l, util.IsNonAlphaNumeric)
for _, w := range words {
if bytes.HasPrefix(w, input) && utf8.RuneCount(w) > inputLen {
if bytes.HasPrefix(w, input) && util.CharacterCount(w) > inputLen {
strw := string(w)
if _, ok := suggestionsSet[strw]; !ok {
suggestionsSet[strw] = struct{}{}

View File

@@ -7,9 +7,9 @@ import (
"path/filepath"
"time"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"golang.org/x/text/encoding"
)
@@ -28,29 +28,53 @@ The backup was created on %s, and the file is
Options: [r]ecover, [i]gnore: `
var backupRequestChan chan *Buffer
func backupThread() {
for {
time.Sleep(time.Second * 8)
for len(backupRequestChan) > 0 {
b := <-backupRequestChan
b.Backup()
}
}
}
func init() {
backupRequestChan = make(chan *Buffer, 10)
go backupThread()
}
func (b *Buffer) RequestBackup() {
if !b.requestedBackup {
select {
case backupRequestChan <- b:
default:
// channel is full
}
b.requestedBackup = true
}
}
// Backup saves the current buffer to ConfigDir/backups
func (b *Buffer) Backup(checkTime bool) error {
func (b *Buffer) Backup() error {
if !b.Settings["backup"].(bool) || b.Path == "" || b.Type != BTDefault {
return nil
}
if checkTime {
sub := time.Now().Sub(b.lastbackup)
if sub < time.Duration(backupTime)*time.Millisecond {
return nil
}
backupdir, err := util.ReplaceHome(b.Settings["backupdir"].(string))
if len(backupdir) == 0 || err != nil {
backupdir = filepath.Join(config.ConfigDir, "backups")
}
b.lastbackup = time.Now()
backupdir := filepath.Join(config.ConfigDir, "backups")
if _, err := os.Stat(backupdir); os.IsNotExist(err) {
os.Mkdir(backupdir, os.ModePerm)
}
name := filepath.Join(backupdir, util.EscapePath(b.AbsPath))
err := overwriteFile(name, encoding.Nop, func(file io.Writer) (e error) {
err = overwriteFile(name, encoding.Nop, func(file io.Writer) (e error) {
if len(b.lines) == 0 {
return
}
@@ -74,12 +98,14 @@ func (b *Buffer) Backup(checkTime bool) error {
return
}, false)
b.requestedBackup = false
return err
}
// RemoveBackup removes any backup file associated with this buffer
func (b *Buffer) RemoveBackup() {
if !b.Settings["backup"].(bool) || b.Path == "" || b.Type != BTDefault {
if !b.Settings["backup"].(bool) || b.Settings["permbackup"].(bool) || b.Path == "" || b.Type != BTDefault {
return
}
f := filepath.Join(config.ConfigDir, "backups", util.EscapePath(b.AbsPath))
@@ -89,7 +115,7 @@ func (b *Buffer) RemoveBackup() {
// ApplyBackup applies the corresponding backup file to this buffer (if one exists)
// Returns true if a backup was applied
func (b *Buffer) ApplyBackup(fsize int64) bool {
if b.Settings["backup"].(bool) && len(b.Path) > 0 && b.Type == BTDefault {
if b.Settings["backup"].(bool) && !b.Settings["permbackup"].(bool) && len(b.Path) > 0 && b.Type == BTDefault {
backupfile := filepath.Join(config.ConfigDir, "backups", util.EscapePath(b.AbsPath))
if info, err := os.Stat(backupfile); err == nil {
backup, err := os.Open(backupfile)

View File

@@ -5,6 +5,7 @@ import (
"bytes"
"crypto/md5"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
@@ -14,16 +15,15 @@ import (
"strings"
"sync"
"time"
"unicode/utf8"
luar "layeh.com/gopher-luar"
dmp "github.com/sergi/go-diff/diffmatchpatch"
"github.com/zyedidia/micro/internal/config"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/pkg/highlight"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/pkg/highlight"
"golang.org/x/text/encoding/htmlindex"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
@@ -60,6 +60,9 @@ var (
BTRaw = BufType{4, false, true, false}
// BTInfo is a buffer for inputting information
BTInfo = BufType{5, false, true, false}
// BTStdout is a buffer that only writes to stdout
// when closed
BTStdout = BufType{6, false, true, true}
// ErrFileTooLarge is returned when the file is too large to hash
// (fastdirty is automatically enabled)
@@ -82,6 +85,8 @@ type SharedBuffer struct {
// Name of the buffer on the status line
name string
toStdout bool
// Settings customized by the user
Settings map[string]interface{}
@@ -97,9 +102,7 @@ type SharedBuffer struct {
diffLock sync.RWMutex
diff map[int]DiffStatus
// counts the number of edits
// resets every backupTime edits
lastbackup time.Time
requestedBackup bool
// ReloadDisabled allows the user to disable reloads if they
// are viewing a file that is constantly changing
@@ -146,14 +149,14 @@ func (b *SharedBuffer) MarkModified(start, end int) {
return
}
start = util.Clamp(start, 0, len(b.lines))
end = util.Clamp(end, 0, len(b.lines))
start = util.Clamp(start, 0, len(b.lines)-1)
end = util.Clamp(end, 0, len(b.lines)-1)
l := -1
for i := start; i <= end; i++ {
l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
}
b.Highlighter.HighlightMatches(b, start, l+1)
b.Highlighter.HighlightMatches(b, start, l)
}
// DisableReload disables future reloads of this sharedbuffer
@@ -186,13 +189,22 @@ type Buffer struct {
StartCursor Loc
}
// NewBufferFromFile opens a new buffer using the given path
// It will also automatically handle `~`, and line/column with filename:l:c
// It will return an empty buffer if the path does not exist
// and an error if the file is a directory
func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
// NewBufferFromFileAtLoc opens a new buffer with a given cursor location
// If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
// would otherwise be (start of file, or saved cursor position if `savecursor` is
// enabled)
func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
var err error
filename, cursorPos := util.GetPathAndCursorPosition(path)
filename := path
if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
var cursorPos []string
filename, cursorPos = util.GetPathAndCursorPosition(filename)
cursorLoc, err = ParseCursorLocation(cursorPos)
if err != nil {
cursorLoc = Loc{-1, -1}
}
}
filename, err = util.ReplaceHome(filename)
if err != nil {
return nil, err
@@ -207,11 +219,6 @@ func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
defer file.Close()
cursorLoc, cursorerr := ParseCursorLocation(cursorPos)
if cursorerr != nil {
cursorLoc = Loc{-1, -1}
}
var buf *Buffer
if err != nil {
// File does not exist -- create an empty buffer with that name
@@ -223,6 +230,19 @@ func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
return buf, nil
}
// NewBufferFromFile opens a new buffer using the given path
// It will also automatically handle `~`, and line/column with filename:l:c
// It will return an empty buffer if the path does not exist
// and an error if the file is a directory
func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
}
// NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
}
// NewBufferFromString creates a new buffer containing the given string
func NewBufferFromString(text, path string, btype BufType) *Buffer {
return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
@@ -249,6 +269,7 @@ func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufT
}
}
hasBackup := false
if !found {
b.SharedBuffer = new(SharedBuffer)
b.Type = btype
@@ -271,11 +292,25 @@ func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufT
b.Settings["encoding"] = "utf-8"
}
hasBackup := b.ApplyBackup(size)
hasBackup = b.ApplyBackup(size)
if !hasBackup {
reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
b.LineArray = NewLineArray(uint64(size), FFAuto, reader)
var ff FileFormat = FFAuto
if size == 0 {
// for empty files, use the fileformat setting instead of
// autodetection
switch b.Settings["fileformat"] {
case "unix":
ff = FFUnix
case "dos":
ff = FFDos
}
}
b.LineArray = NewLineArray(uint64(size), ff, reader)
}
b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
@@ -320,7 +355,9 @@ func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufT
if size > LargeFileThreshold {
// If the file is larger than LargeFileThreshold fastdirty needs to be on
b.Settings["fastdirty"] = true
} else {
} else if !hasBackup {
// since applying a backup does not save the applied backup to disk, we should
// not calculate the original hash based on the backup data
calcHash(b, &b.origHash)
}
}
@@ -355,6 +392,10 @@ func (b *Buffer) Fini() {
b.Serialize()
}
b.RemoveBackup()
if b.Type == BTStdout {
fmt.Fprint(util.Stdout, string(b.Bytes()))
}
}
// GetName returns the name that should be displayed in the statusline
@@ -385,7 +426,7 @@ func (b *Buffer) Insert(start Loc, text string) {
b.EventHandler.active = b.curCursor
b.EventHandler.Insert(start, text)
go b.Backup(true)
b.RequestBackup()
}
}
@@ -396,7 +437,7 @@ func (b *Buffer) Remove(start, end Loc) {
b.EventHandler.active = b.curCursor
b.EventHandler.Remove(start, end)
go b.Backup(true)
b.RequestBackup()
}
}
@@ -464,7 +505,7 @@ func (b *Buffer) RuneAt(loc Loc) rune {
if len(line) > 0 {
i := 0
for len(line) > 0 {
r, size := utf8.DecodeRune(line)
r, _, size := util.DecodeCharacter(line)
line = line[size:]
i++
@@ -493,6 +534,22 @@ func (b *Buffer) Modified() bool {
return buff != b.origHash
}
// Size returns the number of bytes in the current buffer
func (b *Buffer) Size() int {
nb := 0
for i := 0; i < b.LinesNum(); i++ {
nb += len(b.LineBytes(i))
if i != b.LinesNum()-1 {
if b.Endings == FFDos {
nb++ // carriage return
}
nb++ // newline
}
}
return nb
}
// calcHash calculates md5 hash of all lines in the buffer
func calcHash(b *Buffer, out *[md5.Size]byte) error {
h := md5.New()
@@ -538,7 +595,37 @@ func (b *Buffer) UpdateRules() {
return
}
syntaxFile := ""
foundDef := false
var header *highlight.Header
// search for the syntax file in the user's custom syntax files
for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
data, err := f.Data()
if err != nil {
screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
continue
}
header, err = highlight.MakeHeaderYaml(data)
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
syndef, err := highlight.ParseDef(file, header)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
b.SyntaxDef = syndef
syntaxFile = f.Name()
foundDef = true
break
}
}
// search in the default syntax files
for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
data, err := f.Data()
if err != nil {
@@ -563,33 +650,8 @@ func (b *Buffer) UpdateRules() {
}
}
if syntaxFile == "" {
// search for the syntax file in the user's custom syntax files
for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
data, err := f.Data()
if err != nil {
screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
continue
}
header, err = highlight.MakeHeaderYaml(data)
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
syndef, err := highlight.ParseDef(file, header)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
b.SyntaxDef = syndef
break
}
}
} else {
if syntaxFile != "" && !foundDef {
// we found a syntax file using a syntax header file
for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
if f.Name() == syntaxFile {
data, err := f.Data()
@@ -792,19 +854,18 @@ func (b *Buffer) MoveLinesUp(start int, end int) {
}
l := string(b.LineBytes(start - 1))
if end == len(b.lines) {
b.Insert(
b.insert(
Loc{
utf8.RuneCount(b.lines[end-1].data),
util.CharacterCount(b.lines[end-1].data),
end - 1,
},
"\n"+l,
)
} else {
b.Insert(
Loc{0, end},
l+"\n",
[]byte{'\n'},
)
}
b.Insert(
Loc{0, end},
l+"\n",
)
b.Remove(
Loc{0, start - 1},
Loc{0, start},
@@ -813,7 +874,7 @@ func (b *Buffer) MoveLinesUp(start int, end int) {
// MoveLinesDown moves the range of lines down one row
func (b *Buffer) MoveLinesDown(start int, end int) {
if start < 0 || start >= end || end >= len(b.lines)-1 {
if start < 0 || start >= end || end >= len(b.lines) {
return
}
l := string(b.LineBytes(end))

View File

@@ -16,7 +16,7 @@ func TestAuto1(t *testing.T) {
"",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
@@ -25,7 +25,7 @@ func TestAuto1(t *testing.T) {
"fq",
},
},
operation{
{
start: Loc{3, 0},
end: Loc{0, 1},
text: []string{
@@ -58,7 +58,7 @@ func TestAuto2(t *testing.T) {
"gmm",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
@@ -66,7 +66,7 @@ func TestAuto2(t *testing.T) {
"o",
},
},
operation{
{
start: Loc{3, 1},
end: Loc{3, 1},
text: []string{
@@ -74,7 +74,7 @@ func TestAuto2(t *testing.T) {
"avb",
},
},
operation{
{
start: Loc{4, 1},
end: Loc{1, 5},
text: []string{
@@ -111,7 +111,7 @@ func TestAuto3(t *testing.T) {
"xuccnb",
},
[]operation{
operation{
{
start: Loc{2, 3},
end: Loc{2, 3},
text: []string{
@@ -145,14 +145,14 @@ func TestAuto4(t *testing.T) {
"lnqdgorosf",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{4, 0},
text: []string{
"hp",
},
},
operation{
{
start: Loc{6, 0},
end: Loc{0, 1},
text: []string{
@@ -161,7 +161,7 @@ func TestAuto4(t *testing.T) {
"mpx",
},
},
operation{
{
start: Loc{1, 1},
end: Loc{1, 1},
text: []string{
@@ -170,7 +170,7 @@ func TestAuto4(t *testing.T) {
"",
},
},
operation{
{
start: Loc{1, 1},
end: Loc{1, 1},
text: []string{
@@ -178,7 +178,7 @@ func TestAuto4(t *testing.T) {
"mo",
},
},
operation{
{
start: Loc{1, 3},
end: Loc{2, 4},
text: []string{
@@ -210,14 +210,14 @@ func TestBug19872UndoIsFunky(t *testing.T) {
"something else",
},
[]operation{
operation{
{
start: Loc{0, 1},
end: Loc{1, 1},
text: []string{
"",
},
},
operation{
{
start: Loc{0, 2},
end: Loc{1, 3},
text: []string{
@@ -244,14 +244,14 @@ func TestBug19872UndoIsFunky_2(t *testing.T) {
"something else",
},
[]operation{
operation{
{
start: Loc{0, 1},
end: Loc{0, 1},
text: []string{
" ",
},
},
operation{
{
start: Loc{0, 2},
end: Loc{0, 2},
text: []string{
@@ -281,7 +281,7 @@ func TestInsertEmptyText(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
@@ -310,14 +310,14 @@ func TestLastOpIsNoOp(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
operation{
{
start: Loc{0, 3},
end: Loc{0, 3},
text: []string{
@@ -346,7 +346,7 @@ func TestInsertTextWithoutNewline1(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
@@ -375,7 +375,7 @@ func TestInsertTextWithoutNewline2(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
@@ -404,7 +404,7 @@ func TestInsertOneNewline(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{3, 0},
end: Loc{3, 0},
text: []string{
@@ -435,7 +435,7 @@ func TestInsertTextWithOneNewline(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
@@ -466,7 +466,7 @@ func TestInsertTextWithTwoNewlines(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
@@ -499,7 +499,7 @@ func TestInsertTextWithManyNewlines(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
@@ -536,7 +536,7 @@ func TestInsertMultipleNewlines(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
@@ -547,7 +547,7 @@ func TestInsertMultipleNewlines(t *testing.T) {
"",
},
},
operation{
{
start: Loc{14, 2},
end: Loc{14, 2},
text: []string{
@@ -582,7 +582,7 @@ func TestDeleteEmptyText(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
@@ -611,7 +611,7 @@ func TestDeleteTextFromOneLine(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
@@ -640,7 +640,7 @@ func TestDeleteTextFromOneLine2(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
@@ -669,7 +669,7 @@ func TestDeleteAllTextFromALine(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{13, 0},
text: []string{
@@ -698,7 +698,7 @@ func TestDeleteTextFromTwoLines(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{3, 0},
end: Loc{5, 1},
text: []string{
@@ -726,7 +726,7 @@ func TestDeleteTextFromManyLines(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{3, 0},
end: Loc{4, 2},
text: []string{
@@ -753,7 +753,7 @@ func TestDeleteEverything(t *testing.T) {
"1",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 4},
text: []string{
@@ -778,14 +778,14 @@ func TestTwoUnrelatedEdits(t *testing.T) {
"123",
},
[]operation{
operation{
{
start: Loc{0, 1},
end: Loc{2, 1},
text: []string{
"\t",
},
},
operation{
{
start: Loc{0, 2},
end: Loc{4, 2},
text: []string{
@@ -814,14 +814,14 @@ func TestTwoEditsOnOneLine(t *testing.T) {
"\t\t<!@#fifth#@!>\t\t",
},
[]operation{
operation{
{
start: Loc{2, 4},
end: Loc{6, 4},
text: []string{
"",
},
},
operation{
{
start: Loc{11, 4},
end: Loc{15, 4},
text: []string{
@@ -846,21 +846,21 @@ func TestManyEdits(t *testing.T) {
"{\"x\" : 1}",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
"\n ",
},
},
operation{
{
start: Loc{4, 0},
end: Loc{5, 0},
text: []string{
"",
},
},
operation{
{
start: Loc{8, 0},
end: Loc{8, 0},
text: []string{
@@ -885,21 +885,21 @@ func TestManyEditsReversed(t *testing.T) {
"}",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{2, 1},
text: []string{
"",
},
},
operation{
{
start: Loc{5, 1},
end: Loc{5, 1},
text: []string{
" ",
},
},
operation{
{
start: Loc{8, 1},
end: Loc{0, 2},
text: []string{
@@ -924,7 +924,7 @@ func TestReplacingNewlines1(t *testing.T) {
"}",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{0, 1},
text: []string{
@@ -932,7 +932,7 @@ func TestReplacingNewlines1(t *testing.T) {
"\t",
},
},
operation{
{
start: Loc{10, 1},
end: Loc{0, 3},
text: []string{
@@ -962,7 +962,7 @@ func TestReplacingNewlines2(t *testing.T) {
"and the last line",
},
[]operation{
operation{
{
start: Loc{4, 0},
end: Loc{0, 2},
text: []string{
@@ -971,7 +971,7 @@ func TestReplacingNewlines2(t *testing.T) {
"some more text",
},
},
operation{
{
start: Loc{1, 2},
end: Loc{0, 3},
text: []string{
@@ -981,14 +981,14 @@ func TestReplacingNewlines2(t *testing.T) {
"asd",
},
},
operation{
{
start: Loc{0, 4},
end: Loc{5, 4},
text: []string{
"zzzzzzzz",
},
},
operation{
{
start: Loc{10, 4},
end: Loc{15, 5},
text: []string{
@@ -1024,14 +1024,14 @@ func TestAdvanced1(t *testing.T) {
" ,\"e\": /*comment*/ [null] }",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
operation{
{
start: Loc{2, 0},
end: Loc{9, 0},
text: []string{
@@ -1039,7 +1039,7 @@ func TestAdvanced1(t *testing.T) {
" ",
},
},
operation{
{
start: Loc{15, 0},
end: Loc{13, 1},
text: []string{
@@ -1047,7 +1047,7 @@ func TestAdvanced1(t *testing.T) {
" ",
},
},
operation{
{
start: Loc{17, 1},
end: Loc{8, 2},
text: []string{
@@ -1055,14 +1055,14 @@ func TestAdvanced1(t *testing.T) {
" ",
},
},
operation{
{
start: Loc{21, 2},
end: Loc{8, 3},
text: []string{
"",
},
},
operation{
{
start: Loc{9, 3},
end: Loc{9, 3},
text: []string{
@@ -1070,7 +1070,7 @@ func TestAdvanced1(t *testing.T) {
" ",
},
},
operation{
{
start: Loc{27, 3},
end: Loc{27, 3},
text: []string{
@@ -1078,7 +1078,7 @@ func TestAdvanced1(t *testing.T) {
" ",
},
},
operation{
{
start: Loc{31, 3},
end: Loc{31, 3},
text: []string{
@@ -1086,7 +1086,7 @@ func TestAdvanced1(t *testing.T) {
" ",
},
},
operation{
{
start: Loc{32, 3},
end: Loc{33, 3},
text: []string{
@@ -1116,21 +1116,21 @@ func TestAdvancedSimplified(t *testing.T) {
" ,def",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{3, 0},
text: []string{
"",
},
},
operation{
{
start: Loc{6, 0},
end: Loc{1, 1},
text: []string{
"",
},
},
operation{
{
start: Loc{2, 1},
end: Loc{2, 1},
text: []string{
@@ -1158,7 +1158,7 @@ func TestIssue144(t *testing.T) {
"",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 5},
text: []string{
@@ -1194,7 +1194,7 @@ func TestIssue2586ReplacingSelectedEndOfLineWithNewlineLocksUpTheDocument(t *tes
"interesting",
},
[]operation{
operation{
{
start: Loc{9, 0},
end: Loc{0, 1},
text: []string{
@@ -1222,7 +1222,7 @@ func TestIssue3980(t *testing.T) {
"}",
},
[]operation{
operation{
{
start: Loc{7, 0},
end: Loc{8, 0},
text: []string{
@@ -1230,7 +1230,7 @@ func TestIssue3980(t *testing.T) {
"",
},
},
operation{
{
start: Loc{16, 2},
end: Loc{17, 2},
text: []string{
@@ -1238,14 +1238,14 @@ func TestIssue3980(t *testing.T) {
"",
},
},
operation{
{
start: Loc{17, 2},
end: Loc{17, 2},
text: []string{
" ",
},
},
operation{
{
start: Loc{4, 3},
end: Loc{4, 3},
text: []string{
@@ -1273,14 +1273,14 @@ func TestTouchingEditsTwoInsertsAtTheSamePosition(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"a",
},
},
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
@@ -1301,14 +1301,14 @@ func TestTouchingEditsInsertAndReplaceTouching(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"b",
},
},
operation{
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
@@ -1329,14 +1329,14 @@ func TestTouchingEditsTwoTouchingReplaces(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"H",
},
},
operation{
{
start: Loc{1, 0},
end: Loc{2, 0},
text: []string{
@@ -1357,14 +1357,14 @@ func TestTouchingEditsTwoTouchingDeletes(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
operation{
{
start: Loc{1, 0},
end: Loc{2, 0},
text: []string{
@@ -1385,14 +1385,14 @@ func TestTouchingEditsInsertAndReplace(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"H",
},
},
operation{
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
@@ -1413,14 +1413,14 @@ func TestTouchingEditsReplaceAndInsert(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
"H",
},
},
operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
@@ -1441,7 +1441,7 @@ func TestSingleDelete1(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
@@ -1462,7 +1462,7 @@ func TestSingleDelete2(t *testing.T) {
"helloworld",
},
[]operation{
operation{
{
start: Loc{2, 0},
end: Loc{7, 0},
text: []string{
@@ -1483,7 +1483,7 @@ func TestSingleDelete3(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{5, 0},
text: []string{
@@ -1504,7 +1504,7 @@ func TestSingleDelete4(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{6, 0},
text: []string{
@@ -1525,7 +1525,7 @@ func TestSingleDelete5(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{11, 0},
text: []string{
@@ -1548,7 +1548,7 @@ func TestMultiDelete6(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{5, 0},
end: Loc{5, 2},
text: []string{
@@ -1571,7 +1571,7 @@ func TestMultiDelete7(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{11, 0},
end: Loc{11, 2},
text: []string{
@@ -1594,7 +1594,7 @@ func TestMultiDelete8(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 2},
text: []string{
@@ -1617,7 +1617,7 @@ func TestMultiDelete9(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{11, 0},
end: Loc{0, 2},
text: []string{
@@ -1638,7 +1638,7 @@ func TestSingleInsert1(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
@@ -1659,7 +1659,7 @@ func TestSingleInsert2(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
@@ -1680,7 +1680,7 @@ func TestSingleInsert3(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{5, 0},
end: Loc{5, 0},
text: []string{
@@ -1701,7 +1701,7 @@ func TestSingleInsert4(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{6, 0},
end: Loc{6, 0},
text: []string{
@@ -1722,7 +1722,7 @@ func TestSingleInsert5(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{11, 0},
end: Loc{11, 0},
text: []string{
@@ -1743,7 +1743,7 @@ func TestMultiInsert6(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
@@ -1765,7 +1765,7 @@ func TestMultiInsert7(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{11, 0},
end: Loc{11, 0},
text: []string{
@@ -1787,7 +1787,7 @@ func TestMultiInsert8(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{6, 0},
end: Loc{6, 0},
text: []string{
@@ -1810,7 +1810,7 @@ func TestMultiInsert9(t *testing.T) {
"hello world",
},
[]operation{
operation{
{
start: Loc{6, 0},
end: Loc{6, 0},
text: []string{
@@ -1825,65 +1825,3 @@ func TestMultiInsert9(t *testing.T) {
},
)
}
func BenchmarkBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
TestAuto1(nil)
TestAuto2(nil)
TestAuto3(nil)
TestAuto4(nil)
TestBug19872UndoIsFunky(nil)
TestBug19872UndoIsFunky_2(nil)
TestInsertEmptyText(nil)
TestLastOpIsNoOp(nil)
TestInsertTextWithoutNewline1(nil)
TestInsertTextWithoutNewline2(nil)
TestInsertOneNewline(nil)
TestInsertTextWithOneNewline(nil)
TestInsertTextWithTwoNewlines(nil)
TestInsertTextWithManyNewlines(nil)
TestInsertMultipleNewlines(nil)
TestDeleteEmptyText(nil)
TestDeleteTextFromOneLine(nil)
TestDeleteTextFromOneLine2(nil)
TestDeleteAllTextFromALine(nil)
TestDeleteTextFromTwoLines(nil)
TestDeleteTextFromManyLines(nil)
TestDeleteEverything(nil)
TestTwoUnrelatedEdits(nil)
TestTwoEditsOnOneLine(nil)
TestManyEdits(nil)
TestManyEditsReversed(nil)
TestReplacingNewlines1(nil)
TestReplacingNewlines2(nil)
TestAdvanced1(nil)
TestAdvancedSimplified(nil)
TestIssue144(nil)
TestIssue2586ReplacingSelectedEndOfLineWithNewlineLocksUpTheDocument(nil)
TestIssue3980(nil)
TestTouchingEditsTwoInsertsAtTheSamePosition(nil)
TestTouchingEditsInsertAndReplaceTouching(nil)
TestTouchingEditsTwoTouchingReplaces(nil)
TestTouchingEditsTwoTouchingDeletes(nil)
TestTouchingEditsInsertAndReplace(nil)
TestTouchingEditsReplaceAndInsert(nil)
TestSingleDelete1(nil)
TestSingleDelete2(nil)
TestSingleDelete3(nil)
TestSingleDelete4(nil)
TestSingleDelete5(nil)
TestMultiDelete6(nil)
TestMultiDelete7(nil)
TestMultiDelete8(nil)
TestMultiDelete9(nil)
TestSingleInsert1(nil)
TestSingleInsert2(nil)
TestSingleInsert3(nil)
TestSingleInsert4(nil)
TestSingleInsert5(nil)
TestMultiInsert6(nil)
TestMultiInsert7(nil)
TestMultiInsert8(nil)
TestMultiInsert9(nil)
}
}

View File

@@ -1,13 +1,15 @@
package buffer
import (
"math/rand"
"strings"
"testing"
testifyAssert "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/assert"
lua "github.com/yuin/gopher-lua"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/util"
)
type operation struct {
@@ -16,34 +18,15 @@ type operation struct {
text []string
}
type asserter interface {
Equal(interface{}, interface{}, ...interface{}) bool
NotEqual(interface{}, interface{}, ...interface{}) bool
}
type noOpAsserter struct {
}
func (a *noOpAsserter) Equal(interface{}, interface{}, ...interface{}) bool {
return true
}
func (a *noOpAsserter) NotEqual(interface{}, interface{}, ...interface{}) bool {
return true
}
func init() {
ulua.L = lua.NewState()
config.InitGlobalSettings()
config.GlobalSettings["backup"] = false
config.GlobalSettings["fastdirty"] = true
}
func check(t *testing.T, before []string, operations []operation, after []string) {
var assert asserter
if t == nil {
// Benchmark mode; don't perform assertions
assert = &noOpAsserter{}
} else {
assert = testifyAssert.New(t)
}
assert := assert.New(t)
b := NewBufferFromString(strings.Join(before, "\n"), "", BTDefault)
@@ -79,13 +62,14 @@ func check(t *testing.T, before []string, operations []operation, after []string
cursor := cursors[i]
b.SetCurCursor(cursor.Num)
cursor.DeleteSelection()
cursor.ResetSelection()
b.Insert(cursor.Loc, strings.Join(op.text, "\n"))
}
checkText(after)
for b.UndoStack.Peek() != nil {
// must have exactly two events per operation (delete and insert)
for range operations {
b.UndoOneEvent()
b.UndoOneEvent()
}
@@ -93,7 +77,7 @@ func check(t *testing.T, before []string, operations []operation, after []string
for i, op := range operations {
cursor := cursors[i]
if !cursor.HasSelection() {
if op.start == op.end {
assert.Equal(op.start, cursor.Loc)
} else {
assert.Equal(op.start, cursor.CurSelection[0])
@@ -101,7 +85,8 @@ func check(t *testing.T, before []string, operations []operation, after []string
}
}
for b.RedoStack.Peek() != nil {
for range operations {
b.RedoOneEvent()
b.RedoOneEvent()
}
@@ -109,3 +94,229 @@ func check(t *testing.T, before []string, operations []operation, after []string
b.Close()
}
const maxLineLength = 200
var alphabet = []rune(" abcdeäم📚")
func randomString(length int) string {
runes := make([]rune, length)
for i := range runes {
runes[i] = alphabet[rand.Intn(len(alphabet))]
}
return string(runes)
}
func randomText(nLines int) string {
lines := make([]string, nLines)
for i := range lines {
lines[i] = randomString(rand.Intn(maxLineLength + 1))
}
return strings.Join(lines, "\n")
}
func benchCreateAndClose(testingB *testing.B, nLines int) {
rand.Seed(int64(nLines))
text := randomText(nLines)
testingB.ResetTimer()
for i := 0; i < testingB.N; i++ {
b := NewBufferFromString(text, "", BTDefault)
b.Close()
}
}
func benchRead(testingB *testing.B, nLines int) {
rand.Seed(int64(nLines))
b := NewBufferFromString(randomText(nLines), "", BTDefault)
testingB.ResetTimer()
for i := 0; i < testingB.N; i++ {
b.Bytes()
for j := 0; j < b.LinesNum(); j++ {
b.Line(j)
b.LineBytes(j)
}
}
testingB.StopTimer()
b.Close()
}
func benchEdit(testingB *testing.B, nLines, nCursors int) {
rand.Seed(int64(nLines + nCursors))
b := NewBufferFromString(randomText(nLines), "", BTDefault)
regionSize := nLines / nCursors
operations := make([]operation, nCursors)
for i := range operations {
startLine := (i * regionSize) + rand.Intn(regionSize-5)
startColumn := rand.Intn(util.CharacterCountInString(b.Line(startLine)) + 1)
endLine := startLine + 1 + rand.Intn(5)
endColumn := rand.Intn(util.CharacterCountInString(b.Line(endLine)) + 1)
operations[i] = operation{
start: Loc{startColumn, startLine},
end: Loc{endColumn, endLine},
text: []string{randomText(2 + rand.Intn(4))},
}
}
testingB.ResetTimer()
for i := 0; i < testingB.N; i++ {
b.SetCursors([]*Cursor{})
var cursors []*Cursor
for _, op := range operations {
cursor := NewCursor(b, op.start)
cursor.SetSelectionStart(op.start)
cursor.SetSelectionEnd(op.end)
b.AddCursor(cursor)
cursors = append(cursors, cursor)
}
for j, op := range operations {
cursor := cursors[j]
b.SetCurCursor(cursor.Num)
cursor.DeleteSelection()
b.Insert(cursor.Loc, op.text[0])
}
for b.UndoStack.Peek() != nil {
b.UndoOneEvent()
}
}
testingB.StopTimer()
b.Close()
}
func BenchmarkCreateAndClose10Lines(b *testing.B) {
benchCreateAndClose(b, 10)
}
func BenchmarkCreateAndClose100Lines(b *testing.B) {
benchCreateAndClose(b, 100)
}
func BenchmarkCreateAndClose1000Lines(b *testing.B) {
benchCreateAndClose(b, 1000)
}
func BenchmarkCreateAndClose10000Lines(b *testing.B) {
benchCreateAndClose(b, 10000)
}
func BenchmarkCreateAndClose100000Lines(b *testing.B) {
benchCreateAndClose(b, 100000)
}
func BenchmarkCreateAndClose1000000Lines(b *testing.B) {
benchCreateAndClose(b, 1000000)
}
func BenchmarkRead10Lines(b *testing.B) {
benchRead(b, 10)
}
func BenchmarkRead100Lines(b *testing.B) {
benchRead(b, 100)
}
func BenchmarkRead1000Lines(b *testing.B) {
benchRead(b, 1000)
}
func BenchmarkRead10000Lines(b *testing.B) {
benchRead(b, 10000)
}
func BenchmarkRead100000Lines(b *testing.B) {
benchRead(b, 100000)
}
func BenchmarkRead1000000Lines(b *testing.B) {
benchRead(b, 1000000)
}
func BenchmarkEdit10Lines1Cursor(b *testing.B) {
benchEdit(b, 10, 1)
}
func BenchmarkEdit100Lines1Cursor(b *testing.B) {
benchEdit(b, 100, 1)
}
func BenchmarkEdit100Lines10Cursors(b *testing.B) {
benchEdit(b, 100, 10)
}
func BenchmarkEdit1000Lines1Cursor(b *testing.B) {
benchEdit(b, 1000, 1)
}
func BenchmarkEdit1000Lines10Cursors(b *testing.B) {
benchEdit(b, 1000, 10)
}
func BenchmarkEdit1000Lines100Cursors(b *testing.B) {
benchEdit(b, 1000, 100)
}
func BenchmarkEdit10000Lines1Cursor(b *testing.B) {
benchEdit(b, 10000, 1)
}
func BenchmarkEdit10000Lines10Cursors(b *testing.B) {
benchEdit(b, 10000, 10)
}
func BenchmarkEdit10000Lines100Cursors(b *testing.B) {
benchEdit(b, 10000, 100)
}
func BenchmarkEdit10000Lines1000Cursors(b *testing.B) {
benchEdit(b, 10000, 1000)
}
func BenchmarkEdit100000Lines1Cursor(b *testing.B) {
benchEdit(b, 100000, 1)
}
func BenchmarkEdit100000Lines10Cursors(b *testing.B) {
benchEdit(b, 100000, 10)
}
func BenchmarkEdit100000Lines100Cursors(b *testing.B) {
benchEdit(b, 100000, 100)
}
func BenchmarkEdit100000Lines1000Cursors(b *testing.B) {
benchEdit(b, 100000, 1000)
}
func BenchmarkEdit1000000Lines1Cursor(b *testing.B) {
benchEdit(b, 1000000, 1)
}
func BenchmarkEdit1000000Lines10Cursors(b *testing.B) {
benchEdit(b, 1000000, 10)
}
func BenchmarkEdit1000000Lines100Cursors(b *testing.B) {
benchEdit(b, 1000000, 100)
}
func BenchmarkEdit1000000Lines1000Cursors(b *testing.B) {
benchEdit(b, 1000000, 1000)
}

View File

@@ -1,15 +1,13 @@
package buffer
import (
"unicode/utf8"
"github.com/zyedidia/clipboard"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/util"
)
// InBounds returns whether the given location is a valid character position in the given buffer
func InBounds(pos Loc, buf *Buffer) bool {
if pos.Y < 0 || pos.Y >= len(buf.lines) || pos.X < 0 || pos.X > utf8.RuneCount(buf.LineBytes(pos.Y)) {
if pos.Y < 0 || pos.Y >= len(buf.lines) || pos.X < 0 || pos.X > util.CharacterCount(buf.LineBytes(pos.Y)) {
return false
}
@@ -76,9 +74,6 @@ func (c *Cursor) GetVisualX() int {
bytes := c.buf.LineBytes(c.Y)
tabsize := int(c.buf.Settings["tabsize"].(float64))
if c.X > utf8.RuneCount(bytes) {
c.X = utf8.RuneCount(bytes) - 1
}
return util.StringWidth(bytes, c.X, tabsize)
}
@@ -102,25 +97,38 @@ func (c *Cursor) Start() {
func (c *Cursor) StartOfText() {
c.Start()
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == utf8.RuneCount(c.buf.LineBytes(c.Y)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
break
}
c.Right()
}
}
// IsStartOfText returns whether the cursor is at the first
// non-whitespace rune of the line it is on
func (c *Cursor) IsStartOfText() bool {
x := 0
for util.IsWhitespace(c.RuneUnder(x)) {
if x == util.CharacterCount(c.buf.LineBytes(c.Y)) {
break
}
x++
}
return c.X == x
}
// End moves the cursor to the end of the line it is on
func (c *Cursor) End() {
c.X = utf8.RuneCount(c.buf.LineBytes(c.Y))
c.X = util.CharacterCount(c.buf.LineBytes(c.Y))
c.LastVisualX = c.GetVisualX()
}
// CopySelection copies the user's selection to either "primary"
// or "clipboard"
func (c *Cursor) CopySelection(target string) {
func (c *Cursor) CopySelection(target clipboard.Register) {
if c.HasSelection() {
if target != "primary" || c.buf.Settings["useprimary"].(bool) {
clipboard.WriteAll(string(c.GetSelection()), target)
if target != clipboard.PrimaryReg || c.buf.Settings["useprimary"].(bool) {
clipboard.WriteMulti(string(c.GetSelection()), target, c.Num, c.buf.NumCursors())
}
}
}
@@ -229,8 +237,14 @@ func (c *Cursor) UpN(amount int) {
bytes := c.buf.LineBytes(proposedY)
c.X = c.GetCharPosInLine(bytes, c.LastVisualX)
if c.X > utf8.RuneCount(bytes) || (amount < 0 && proposedY == c.Y) {
c.X = utf8.RuneCount(bytes)
if c.X > util.CharacterCount(bytes) || (amount < 0 && proposedY == c.Y) {
c.X = util.CharacterCount(bytes)
c.StoreVisualX()
}
if c.X < 0 || (amount > 0 && proposedY == c.Y) {
c.X = 0
c.StoreVisualX()
}
c.Y = proposedY
@@ -272,7 +286,7 @@ func (c *Cursor) Right() {
if c.Loc == c.buf.End() {
return
}
if c.X < utf8.RuneCount(c.buf.LineBytes(c.Y)) {
if c.X < util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.X++
} else {
c.Down()
@@ -293,8 +307,8 @@ func (c *Cursor) Relocate() {
if c.X < 0 {
c.X = 0
} else if c.X > utf8.RuneCount(c.buf.LineBytes(c.Y)) {
c.X = utf8.RuneCount(c.buf.LineBytes(c.Y))
} else if c.X > util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.X = util.CharacterCount(c.buf.LineBytes(c.Y))
}
}
@@ -320,7 +334,7 @@ func (c *Cursor) SelectWord() {
c.SetSelectionStart(Loc{backward, c.Y})
c.OrigSelection[0] = c.CurSelection[0]
lineLen := utf8.RuneCount(c.buf.LineBytes(c.Y)) - 1
lineLen := util.CharacterCount(c.buf.LineBytes(c.Y)) - 1
for forward < lineLen && util.IsWordChar(c.RuneUnder(forward+1)) {
forward++
}
@@ -352,7 +366,7 @@ func (c *Cursor) AddWordToSelection() {
if c.Loc.GreaterThan(c.OrigSelection[1]) {
forward := c.X
lineLen := utf8.RuneCount(c.buf.LineBytes(c.Y)) - 1
lineLen := util.CharacterCount(c.buf.LineBytes(c.Y)) - 1
for forward < lineLen && util.IsWordChar(c.RuneUnder(forward+1)) {
forward++
}
@@ -379,7 +393,7 @@ func (c *Cursor) SelectTo(loc Loc) {
// WordRight moves the cursor one word to the right
func (c *Cursor) WordRight() {
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == utf8.RuneCount(c.buf.LineBytes(c.Y)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.Right()
return
}
@@ -387,7 +401,7 @@ func (c *Cursor) WordRight() {
}
c.Right()
for util.IsWordChar(c.RuneUnder(c.X)) {
if c.X == utf8.RuneCount(c.buf.LineBytes(c.Y)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
@@ -416,14 +430,14 @@ func (c *Cursor) WordLeft() {
// RuneUnder returns the rune under the given x position
func (c *Cursor) RuneUnder(x int) rune {
line := c.buf.LineBytes(c.Y)
if len(line) == 0 || x >= utf8.RuneCount(line) {
if len(line) == 0 || x >= util.CharacterCount(line) {
return '\n'
} else if x < 0 {
x = 0
}
i := 0
for len(line) > 0 {
r, size := utf8.DecodeRune(line)
r, _, size := util.DecodeCharacter(line)
line = line[size:]
if i == x {

View File

@@ -3,12 +3,12 @@ package buffer
import (
"bytes"
"time"
"unicode/utf8"
dmp "github.com/sergi/go-diff/diffmatchpatch"
"github.com/zyedidia/micro/internal/config"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
luar "layeh.com/gopher-luar"
)
@@ -62,10 +62,10 @@ func (eh *EventHandler) DoTextEvent(t *TextEvent, useUndo bool) {
var textX int
if t.EventType == TextEventInsert {
linecount := eh.buf.LinesNum() - oldl
textcount := utf8.RuneCount(text)
textcount := util.CharacterCount(text)
lastnl = bytes.LastIndex(text, []byte{'\n'})
if lastnl >= 0 {
endX = utf8.RuneCount(text[lastnl+1:])
endX = util.CharacterCount(text[lastnl+1:])
textX = endX
} else {
endX = start.X + textcount
@@ -123,7 +123,7 @@ func ExecuteTextEvent(t *TextEvent, buf *SharedBuffer) {
t.Deltas[i].Text = buf.remove(d.Start, d.End)
buf.insert(d.Start, d.Text)
t.Deltas[i].Start = d.Start
t.Deltas[i].End = Loc{d.Start.X + utf8.RuneCount(d.Text), d.Start.Y}
t.Deltas[i].End = Loc{d.Start.X + util.CharacterCount(d.Text), d.Start.Y}
}
for i, j := 0, len(t.Deltas)-1; i < j; i, j = i+1, j-1 {
t.Deltas[i], t.Deltas[j] = t.Deltas[j], t.Deltas[i]
@@ -166,12 +166,12 @@ func (eh *EventHandler) ApplyDiff(new string) {
loc := eh.buf.Start()
for _, d := range diff {
if d.Type == dmp.DiffDelete {
eh.Remove(loc, loc.MoveLA(utf8.RuneCountInString(d.Text), eh.buf.LineArray))
eh.Remove(loc, loc.MoveLA(util.CharacterCountInString(d.Text), eh.buf.LineArray))
} else {
if d.Type == dmp.DiffInsert {
eh.Insert(loc, d.Text)
}
loc = loc.MoveLA(utf8.RuneCountInString(d.Text), eh.buf.LineArray)
loc = loc.MoveLA(util.CharacterCountInString(d.Text), eh.buf.LineArray)
}
}
}

View File

@@ -2,11 +2,12 @@ package buffer
import (
"bufio"
"bytes"
"io"
"sync"
"unicode/utf8"
"github.com/zyedidia/micro/pkg/highlight"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/pkg/highlight"
)
// Finds the byte index of the nth rune in a byte slice
@@ -18,7 +19,7 @@ func runeToByteIndex(n int, txt []byte) int {
count := 0
i := 0
for len(txt) > 0 {
_, size := utf8.DecodeRune(txt)
_, _, size := util.DecodeCharacter(txt)
txt = txt[size:]
count += size
@@ -86,6 +87,8 @@ func NewLineArray(size uint64, endings FileFormat, reader io.Reader) *LineArray
br := bufio.NewReader(reader)
var loaded int
la.Endings = endings
n := 0
for {
data, err := br.ReadBytes('\n')
@@ -152,17 +155,19 @@ func NewLineArray(size uint64, endings FileFormat, reader io.Reader) *LineArray
// Bytes returns the string that should be written to disk when
// the line array is saved
func (la *LineArray) Bytes() []byte {
str := make([]byte, 0, la.initsize+1000) // initsize should provide a good estimate
b := new(bytes.Buffer)
// initsize should provide a good estimate
b.Grow(int(la.initsize + 4096))
for i, l := range la.lines {
str = append(str, l.data...)
b.Write(l.data)
if i != len(la.lines)-1 {
if la.Endings == FFDos {
str = append(str, '\r')
b.WriteByte('\r')
}
str = append(str, '\n')
b.WriteByte('\n')
}
}
return str
return b.Bytes()
}
// newlineBelow adds a newline below the given line number
@@ -186,10 +191,15 @@ func (la *LineArray) newlineBelow(y int) {
func (la *LineArray) insert(pos Loc, value []byte) {
x, y := runeToByteIndex(pos.X, la.lines[pos.Y].data), pos.Y
for i := 0; i < len(value); i++ {
if value[i] == '\n' {
if value[i] == '\n' || (value[i] == '\r' && i < len(value)-1 && value[i+1] == '\n') {
la.split(Loc{x, y})
x = 0
y++
if value[i] == '\r' {
i++
}
continue
}
la.insertByte(Loc{x, y}, value[i])
@@ -296,7 +306,7 @@ func (la *LineArray) Start() Loc {
// End returns the location of the last character in the buffer
func (la *LineArray) End() Loc {
numlines := len(la.lines)
return Loc{utf8.RuneCount(la.lines[numlines-1].data), numlines - 1}
return Loc{util.CharacterCount(la.lines[numlines-1].data), numlines - 1}
}
// LineBytes returns line n as an array of bytes

View File

@@ -46,14 +46,15 @@ func TestInsert(t *testing.T) {
assert.Equal(t, []byte("Uppen Sevarne staþe, foobar sel þar him þuhte,"), sub1)
la.insert(Loc{25, 2}, []byte("ಮಣ್ಣಾಗಿ"))
la.insert(Loc{25, 2}, []byte("H̼̥̯͇͙̕͘͞e̸̦̞̠̣̰͙̼̥̦̼̖̬͕͕̰̯̫͇̕ĺ̜̠̩̯̯͙̼̭̠͕̮̞͜l̶͓̫̞̮͈͞ͅo̸͔͙̳̠͈̮̼̳͙̥̲͜͠"))
sub2 := la.Substr(Loc{0, 2}, Loc{60, 2})
assert.Equal(t, []byte("He wonede at Ernleȝe at æಮಣ್ಣಾಗಿðelen are chirechen,"), sub2)
assert.Equal(t, []byte("He wonede at Ernleȝe at æH̼̥̯͇͙̕͘͞e̸̦̞̠̣̰͙̼̥̦̼̖̬͕͕̰̯̫͇̕ĺ̜̠̩̯̯͙̼̭̠͕̮̞͜l̶͓̫̞̮͈͞ͅo̸͔͙̳̠͈̮̼̳͙̥̲͜͠ðelen are chirechen,"), sub2)
}
func TestRemove(t *testing.T) {
la.remove(Loc{20, 3}, Loc{27, 3})
la.remove(Loc{25, 2}, Loc{32, 2})
la.remove(Loc{25, 2}, Loc{30, 2})
bytes := la.Bytes()
assert.Equal(t, unicode_txt, string(bytes))

View File

@@ -1,9 +1,7 @@
package buffer
import (
"unicode/utf8"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/util"
)
// Loc stores a location
@@ -68,9 +66,9 @@ func DiffLA(a, b Loc, buf *LineArray) int {
loc := 0
for i := a.Y + 1; i < b.Y; i++ {
// + 1 for the newline
loc += utf8.RuneCount(buf.LineBytes(i)) + 1
loc += util.CharacterCount(buf.LineBytes(i)) + 1
}
loc += utf8.RuneCount(buf.LineBytes(a.Y)) - a.X + b.X + 1
loc += util.CharacterCount(buf.LineBytes(a.Y)) - a.X + b.X + 1
return loc
}
@@ -80,7 +78,7 @@ func (l Loc) right(buf *LineArray) Loc {
return Loc{l.X + 1, l.Y}
}
var res Loc
if l.X < utf8.RuneCount(buf.LineBytes(l.Y)) {
if l.X < util.CharacterCount(buf.LineBytes(l.Y)) {
res = Loc{l.X + 1, l.Y}
} else {
res = Loc{0, l.Y + 1}
@@ -97,7 +95,7 @@ func (l Loc) left(buf *LineArray) Loc {
if l.X > 0 {
res = Loc{l.X - 1, l.Y}
} else {
res = Loc{utf8.RuneCount(buf.LineBytes(l.Y - 1)), l.Y - 1}
res = Loc{util.CharacterCount(buf.LineBytes(l.Y - 1)), l.Y - 1}
}
return res
}

View File

@@ -1,7 +1,7 @@
package buffer
import (
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/tcell"
)

View File

@@ -11,11 +11,10 @@ import (
"path/filepath"
"runtime"
"unicode"
"unicode/utf8"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/htmlindex"
"golang.org/x/text/transform"
@@ -97,12 +96,11 @@ func (b *Buffer) saveToFile(filename string, withSudo bool) error {
return errors.New("Save with sudo not supported on Windows")
}
b.UpdateRules()
if b.Settings["rmtrailingws"].(bool) {
for i, l := range b.lines {
leftover := utf8.RuneCount(bytes.TrimRightFunc(l.data, unicode.IsSpace))
leftover := util.CharacterCount(bytes.TrimRightFunc(l.data, unicode.IsSpace))
linelen := utf8.RuneCount(l.data)
linelen := util.CharacterCount(l.data)
b.Remove(Loc{leftover, i}, Loc{linelen, i})
}
@@ -196,5 +194,6 @@ func (b *Buffer) saveToFile(filename string, withSudo bool) error {
absPath, _ := filepath.Abs(filename)
b.AbsPath = absPath
b.isModified = false
b.UpdateRules()
return err
}

View File

@@ -2,12 +2,18 @@ package buffer
import (
"regexp"
"unicode/utf8"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/util"
)
func (b *Buffer) findDown(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
lastcn := util.CharacterCount(b.LineBytes(b.LinesNum() - 1))
if start.Y > b.LinesNum()-1 {
start.X = lastcn - 1
}
if end.Y > b.LinesNum()-1 {
end.X = lastcn
}
start.Y = util.Clamp(start.Y, 0, b.LinesNum()-1)
end.Y = util.Clamp(end.Y, 0, b.LinesNum()-1)
@@ -20,19 +26,19 @@ func (b *Buffer) findDown(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
charpos := 0
if i == start.Y && start.Y == end.Y {
nchars := utf8.RuneCount(l)
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == start.Y {
nchars := utf8.RuneCount(l)
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == end.Y {
nchars := utf8.RuneCount(l)
nchars := util.CharacterCount(l)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
}
@@ -49,6 +55,13 @@ func (b *Buffer) findDown(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
}
func (b *Buffer) findUp(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
lastcn := util.CharacterCount(b.LineBytes(b.LinesNum() - 1))
if start.Y > b.LinesNum()-1 {
start.X = lastcn - 1
}
if end.Y > b.LinesNum()-1 {
end.X = lastcn
}
start.Y = util.Clamp(start.Y, 0, b.LinesNum()-1)
end.Y = util.Clamp(end.Y, 0, b.LinesNum()-1)
@@ -61,19 +74,19 @@ func (b *Buffer) findUp(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
charpos := 0
if i == start.Y && start.Y == end.Y {
nchars := utf8.RuneCount(l)
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == start.Y {
nchars := utf8.RuneCount(l)
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == end.Y {
nchars := utf8.RuneCount(l)
nchars := util.CharacterCount(l)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
}
@@ -133,7 +146,7 @@ func (b *Buffer) FindNext(s string, start, end, from Loc, down bool, useRegex bo
// ReplaceRegex replaces all occurrences of 'search' with 'replace' in the given area
// and returns the number of replacements made and the number of runes
// added or removed
// added or removed on the last line of the range
func (b *Buffer) ReplaceRegex(start, end Loc, search *regexp.Regexp, replace []byte) (int, int) {
if start.GreaterThan(end) {
start, end = end, start
@@ -163,12 +176,14 @@ func (b *Buffer) ReplaceRegex(start, end Loc, search *regexp.Regexp, replace []b
result = search.Expand(result, replace, in, submatches)
}
found++
netrunes += utf8.RuneCount(in) - utf8.RuneCount(result)
if i == end.Y {
netrunes += util.CharacterCount(result) - util.CharacterCount(in)
}
return result
})
from := Loc{charpos, i}
to := Loc{charpos + utf8.RuneCount(l), i}
to := Loc{charpos + util.CharacterCount(l), i}
deltas = append(deltas, Delta{newText, from, to})
}

View File

@@ -10,8 +10,8 @@ import (
"golang.org/x/text/encoding"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
)
// The SerializedBuffer holds the types that get serialized when a buffer is saved

View File

@@ -1,8 +1,8 @@
package buffer
import (
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
)
func (b *Buffer) SetOptionNative(option string, nativeValue interface{}) error {
@@ -10,9 +10,11 @@ func (b *Buffer) SetOptionNative(option string, nativeValue interface{}) error {
if option == "fastdirty" {
if !nativeValue.(bool) {
e := calcHash(b, &b.origHash)
if e == ErrFileTooLarge {
b.Settings["fastdirty"] = false
if !b.Modified() {
e := calcHash(b, &b.origHash)
if e == ErrFileTooLarge {
b.Settings["fastdirty"] = false
}
}
}
} else if option == "statusline" {

View File

@@ -0,0 +1,151 @@
package clipboard
import (
"errors"
"github.com/zyedidia/clipboard"
)
type Method int
const (
// External relies on external tools for accessing the clipboard
// These include xclip, xsel, wl-clipboard for linux, pbcopy/pbpaste on Mac,
// and Syscalls on Windows.
External Method = iota
// Terminal uses the terminal to manage the clipboard via OSC 52. Many
// terminals do not support OSC 52, in which case this method won't work.
Terminal
// Internal just manages the clipboard with an internal buffer and doesn't
// attempt to interface with the system clipboard
Internal
)
// CurrentMethod is the method used to store clipboard information
var CurrentMethod Method = Internal
// A Register is a buffer used to store text. The system clipboard has the 'clipboard'
// and 'primary' (linux-only) registers, but other registers may be used internal to micro.
type Register int
const (
// ClipboardReg is the main system clipboard
ClipboardReg Register = -1
// PrimaryReg is the system primary clipboard (linux only)
PrimaryReg = -2
)
// Initialize attempts to initialize the clipboard using the given method
func Initialize(m Method) error {
var err error
switch m {
case External:
err = clipboard.Initialize()
}
return err
}
// SetMethod changes the clipboard access method
func SetMethod(m string) Method {
switch m {
case "internal":
CurrentMethod = Internal
case "external":
CurrentMethod = External
case "terminal":
CurrentMethod = Terminal
}
return CurrentMethod
}
// Read reads from a clipboard register
func Read(r Register) (string, error) {
return read(r, CurrentMethod)
}
// Write writes text to a clipboard register
func Write(text string, r Register) error {
return write(text, r, CurrentMethod)
}
// ReadMulti reads text from a clipboard register for a certain multi-cursor
func ReadMulti(r Register, num, ncursors int) (string, error) {
clip, err := Read(r)
if err != nil {
return "", err
}
if ValidMulti(r, clip, ncursors) {
return multi.getText(r, num), nil
}
return clip, nil
}
// WriteMulti writes text to a clipboard register for a certain multi-cursor
func WriteMulti(text string, r Register, num int, ncursors int) error {
return writeMulti(text, r, num, ncursors, CurrentMethod)
}
// ValidMulti checks if the internal multi-clipboard is valid and up-to-date
// with the system clipboard
func ValidMulti(r Register, clip string, ncursors int) bool {
return multi.isValid(r, clip, ncursors)
}
func writeMulti(text string, r Register, num int, ncursors int, m Method) error {
multi.writeText(text, r, num, ncursors)
return write(multi.getAllText(r), r, m)
}
func read(r Register, m Method) (string, error) {
switch m {
case External:
switch r {
case ClipboardReg:
return clipboard.ReadAll("clipboard")
case PrimaryReg:
return clipboard.ReadAll("primary")
default:
return internal.read(r), nil
}
case Internal:
return internal.read(r), nil
case Terminal:
switch r {
case ClipboardReg:
// terminal paste works by sending an esc sequence to the
// terminal to trigger a paste event
return terminal.read("clipboard")
case PrimaryReg:
return terminal.read("primary")
default:
return internal.read(r), nil
}
}
return "", errors.New("Invalid clipboard method")
}
func write(text string, r Register, m Method) error {
switch m {
case External:
switch r {
case ClipboardReg:
return clipboard.WriteAll(text, "clipboard")
case PrimaryReg:
return clipboard.WriteAll(text, "primary")
default:
internal.write(text, r)
}
case Internal:
internal.write(text, r)
case Terminal:
switch r {
case ClipboardReg:
return terminal.write(text, "c")
case PrimaryReg:
return terminal.write(text, "p")
default:
internal.write(text, r)
}
}
return nil
}

View File

@@ -0,0 +1,17 @@
package clipboard
type internalClipboard map[Register]string
var internal internalClipboard
func init() {
internal = make(internalClipboard)
}
func (c internalClipboard) read(r Register) string {
return c[r]
}
func (c internalClipboard) write(text string, r Register) {
c[r] = text
}

View File

@@ -0,0 +1,63 @@
package clipboard
import (
"bytes"
)
// For storing multi cursor clipboard contents
type multiClipboard map[Register][]string
var multi multiClipboard
func (c multiClipboard) getAllText(r Register) string {
content := c[r]
if content == nil {
return ""
}
buf := &bytes.Buffer{}
for _, s := range content {
buf.WriteString(s)
}
return buf.String()
}
func (c multiClipboard) getText(r Register, num int) string {
content := c[r]
if content == nil || len(content) <= num {
return ""
}
return content[num]
}
// isValid checks if the text stored in this multi-clipboard is the same as the
// text stored in the system clipboard (provided as an argument), and therefore
// if it is safe to use the multi-clipboard for pasting instead of the system
// clipboard.
func (c multiClipboard) isValid(r Register, clipboard string, ncursors int) bool {
content := c[r]
if content == nil || len(content) != ncursors {
return false
}
return clipboard == c.getAllText(r)
}
func (c multiClipboard) writeText(text string, r Register, num int, ncursors int) {
content := c[r]
if content == nil || len(content) != ncursors {
content = make([]string, ncursors, ncursors)
c[r] = content
}
if num >= ncursors {
return
}
content[num] = text
}
func init() {
multi = make(multiClipboard)
}

View File

@@ -0,0 +1,33 @@
package clipboard
import (
"errors"
"time"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell"
)
type terminalClipboard struct{}
var terminal terminalClipboard
func (t terminalClipboard) read(reg string) (string, error) {
screen.Screen.GetClipboard(reg)
// wait at most 200ms for response
for {
select {
case event := <-screen.Events:
e, ok := event.(*tcell.EventPaste)
if ok {
return e.Text(), nil
}
case <-time.After(200 * time.Millisecond):
return "", errors.New("No clipboard received from terminal")
}
}
}
func (t terminalClipboard) write(text, reg string) error {
return screen.Screen.SetClipboard(text, reg)
}

View File

@@ -117,16 +117,12 @@ func ParseColorscheme(text string) (map[string]tcell.Style, error) {
// StringToStyle returns a style from a string
// The strings must be in the format "extra foregroundcolor,backgroundcolor"
// The 'extra' can be bold, reverse, or underline
// The 'extra' can be bold, reverse, italic or underline
func StringToStyle(str string) tcell.Style {
var fg, bg string
spaceSplit := strings.Split(str, " ")
var split []string
if len(spaceSplit) > 1 {
split = strings.Split(spaceSplit[1], ",")
} else {
split = strings.Split(str, ",")
}
split = strings.Split(spaceSplit[len(spaceSplit)-1], ",")
if len(split) > 1 {
fg, bg = split[0], split[1]
} else {
@@ -151,6 +147,9 @@ func StringToStyle(str string) tcell.Style {
if strings.Contains(str, "bold") {
style = style.Bold(true)
}
if strings.Contains(str, "italic") {
style = style.Italic(true)
}
if strings.Contains(str, "reverse") {
style = style.Reverse(true)
}

View File

@@ -26,6 +26,18 @@ func TestAttributeStringToStyle(t *testing.T) {
assert.NotEqual(t, 0, attr&tcell.AttrBold)
}
func TestMultiAttributesStringToStyle(t *testing.T) {
s := StringToStyle("bold italic underline cyan,brightcyan")
fg, bg, attr := s.Decompose()
assert.Equal(t, tcell.ColorTeal, fg)
assert.Equal(t, tcell.ColorAqua, bg)
assert.NotEqual(t, 0, attr&tcell.AttrBold)
assert.NotEqual(t, 0, attr&tcell.AttrItalic)
assert.NotEqual(t, 0, attr&tcell.AttrUnderline)
}
func TestColor256StringToStyle(t *testing.T) {
s := StringToStyle("128,60")

View File

@@ -5,7 +5,7 @@ import (
"log"
lua "github.com/yuin/gopher-lua"
ulua "github.com/zyedidia/micro/internal/lua"
ulua "github.com/zyedidia/micro/v2/internal/lua"
)
// ErrNoSuchFunction is returned when Call is executed on a function that does not exist

View File

@@ -16,8 +16,8 @@ import (
"github.com/blang/semver"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/json5"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/internal/util"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/util"
)
var (
@@ -607,7 +607,7 @@ func UpdatePlugins(out io.Writer, plugins []string) {
// if no plugins are specified, update all installed plugins.
if len(plugins) == 0 {
for _, p := range Plugins {
if !p.IsEnabled() {
if !p.IsEnabled() || p.Default {
continue
}
plugins = append(plugins, p.Name)

File diff suppressed because one or more lines are too long

View File

@@ -3,6 +3,7 @@ package config
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
@@ -12,7 +13,7 @@ import (
"github.com/zyedidia/glob"
"github.com/zyedidia/json5"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/util"
"golang.org/x/text/encoding/htmlindex"
)
@@ -26,16 +27,23 @@ var (
GlobalSettings map[string]interface{}
// This is the raw parsed json
parsedSettings map[string]interface{}
parsedSettings map[string]interface{}
settingsParseError bool
// ModifiedSettings is a map of settings which should be written to disk
// because they have been modified by the user in this session
ModifiedSettings map[string]bool
)
func init() {
ModifiedSettings = make(map[string]bool)
parsedSettings = make(map[string]interface{})
}
// Options with validators
var optionValidators = map[string]optionValidator{
"autosave": validateNonNegativeValue,
"clipboard": validateClipboard,
"tabsize": validatePositiveValue,
"scrollmargin": validateNonNegativeValue,
"scrollspeed": validateNonNegativeValue,
@@ -50,12 +58,14 @@ func ReadSettings() error {
if _, e := os.Stat(filename); e == nil {
input, err := ioutil.ReadFile(filename)
if err != nil {
settingsParseError = true
return errors.New("Error reading settings.json file: " + err.Error())
}
if !strings.HasPrefix(string(input), "null") {
// Unmarshal the input into the parsed map
err = json5.Unmarshal(input, &parsedSettings)
if err != nil {
settingsParseError = true
return errors.New("Error reading settings.json: " + err.Error())
}
@@ -75,16 +85,33 @@ func ReadSettings() error {
return nil
}
func verifySetting(option string, value reflect.Type, def reflect.Type) bool {
var interfaceArr []interface{}
switch option {
case "pluginrepos", "pluginchannels":
return value.AssignableTo(reflect.TypeOf(interfaceArr))
default:
return def.AssignableTo(value)
}
}
// InitGlobalSettings initializes the options map and sets all options to their default values
// Must be called after ReadSettings
func InitGlobalSettings() {
func InitGlobalSettings() error {
var err error
GlobalSettings = DefaultGlobalSettings()
for k, v := range parsedSettings {
if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
if _, ok := GlobalSettings[k]; ok && !verifySetting(k, reflect.TypeOf(v), reflect.TypeOf(GlobalSettings[k])) {
err = errors.New(fmt.Sprintf("Global Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", k, reflect.TypeOf(v), GlobalSettings[k], reflect.TypeOf(GlobalSettings[k])))
continue
}
GlobalSettings[k] = v
}
}
return err
}
// InitLocalSettings scans the json in settings.json and sets the options locally based
@@ -97,6 +124,10 @@ func InitLocalSettings(settings map[string]interface{}, path string) error {
if strings.HasPrefix(k, "ft:") {
if settings["filetype"].(string) == k[3:] {
for k1, v1 := range v.(map[string]interface{}) {
if _, ok := settings[k1]; ok && !verifySetting(k1, reflect.TypeOf(v1), reflect.TypeOf(settings[k1])) {
parseError = errors.New(fmt.Sprintf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", k, reflect.TypeOf(v1), settings[k1], reflect.TypeOf(settings[k1])))
continue
}
settings[k1] = v1
}
}
@@ -109,6 +140,10 @@ func InitLocalSettings(settings map[string]interface{}, path string) error {
if g.MatchString(path) {
for k1, v1 := range v.(map[string]interface{}) {
if _, ok := settings[k1]; ok && !verifySetting(k1, reflect.TypeOf(v1), reflect.TypeOf(settings[k1])) {
parseError = errors.New(fmt.Sprintf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", k, reflect.TypeOf(v1), settings[k1], reflect.TypeOf(settings[k1])))
continue
}
settings[k1] = v1
}
}
@@ -120,10 +155,35 @@ func InitLocalSettings(settings map[string]interface{}, path string) error {
// WriteSettings writes the settings to the specified filename as JSON
func WriteSettings(filename string) error {
if settingsParseError {
// Don't write settings if there was a parse error
// because this will delete the settings.json if it
// is invalid. Instead we should allow the user to fix
// it manually.
return nil
}
var err error
if _, e := os.Stat(ConfigDir); e == nil {
defaults := DefaultGlobalSettings()
// remove any options froms parsedSettings that have since been marked as default
for k, v := range parsedSettings {
if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
cur, okcur := GlobalSettings[k]
if def, ok := defaults[k]; ok && okcur && reflect.DeepEqual(cur, def) {
delete(parsedSettings, k)
}
}
}
// add any options to parsedSettings that have since been marked as non-default
for k, v := range GlobalSettings {
parsedSettings[k] = v
if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
if _, wr := ModifiedSettings[k]; wr {
parsedSettings[k] = v
}
}
}
txt, _ := json.MarshalIndent(parsedSettings, "", " ")
@@ -132,10 +192,23 @@ func WriteSettings(filename string) error {
return err
}
// OverwriteSettings writes the current settings to settings.json and
// resets any user configuration of local settings present in settings.json
func OverwriteSettings(filename string) error {
settings := make(map[string]interface{})
var err error
if _, e := os.Stat(ConfigDir); e == nil {
txt, _ := json.MarshalIndent(GlobalSettings, "", " ")
defaults := DefaultGlobalSettings()
for k, v := range GlobalSettings {
if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
if _, wr := ModifiedSettings[k]; wr {
settings[k] = v
}
}
}
txt, _ := json.MarshalIndent(settings, "", " ")
err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
}
return err
@@ -144,7 +217,7 @@ func OverwriteSettings(filename string) error {
// RegisterCommonOptionPlug creates a new option (called pl.name). This is meant to be called by plugins to add options.
func RegisterCommonOptionPlug(pl string, name string, defaultvalue interface{}) error {
name = pl + "." + name
if v, ok := GlobalSettings[name]; !ok {
if _, ok := GlobalSettings[name]; !ok {
defaultCommonSettings[name] = defaultvalue
GlobalSettings[name] = defaultvalue
err := WriteSettings(filepath.Join(ConfigDir, "settings.json"))
@@ -152,7 +225,7 @@ func RegisterCommonOptionPlug(pl string, name string, defaultvalue interface{})
return errors.New("Error writing settings.json file: " + err.Error())
}
} else {
defaultCommonSettings[name] = v
defaultCommonSettings[name] = defaultvalue
}
return nil
}
@@ -186,6 +259,7 @@ var defaultCommonSettings = map[string]interface{}{
"autoindent": true,
"autosu": false,
"backup": true,
"backupdir": "",
"basename": false,
"colorcolumn": float64(0),
"cursorline": true,
@@ -200,9 +274,11 @@ var defaultCommonSettings = map[string]interface{}{
"keepautoindent": false,
"matchbrace": true,
"mkparents": false,
"permbackup": false,
"readonly": false,
"rmtrailingws": false,
"ruler": true,
"relativeruler": false,
"savecursor": false,
"saveundo": false,
"scrollbar": false,
@@ -247,10 +323,14 @@ func DefaultCommonSettings() map[string]interface{} {
// default values
var DefaultGlobalOnlySettings = map[string]interface{}{
"autosave": float64(0),
"clipboard": "external",
"colorscheme": "default",
"divchars": "|-",
"divreverse": true,
"infobar": true,
"keymenu": false,
"mouse": true,
"parsecursor": false,
"paste": false,
"savehistory": true,
"sucmd": "sudo",
@@ -372,6 +452,22 @@ func validateColorscheme(option string, value interface{}) error {
return nil
}
func validateClipboard(option string, value interface{}) error {
val, ok := value.(string)
if !ok {
return errors.New("Expected string type for clipboard")
}
switch val {
case "internal", "external", "terminal":
default:
return errors.New(option + " must be 'internal', 'external', or 'terminal'")
}
return nil
}
func validateLineEnding(option string, value interface{}) error {
endingType, ok := value.(string)

View File

@@ -2,13 +2,12 @@ package display
import (
"strconv"
"unicode/utf8"
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
)
@@ -73,9 +72,9 @@ func (w *BufWindow) getStartInfo(n, lineN int) ([]byte, int, int, *tcell.Style)
curStyle := config.DefStyle
var s *tcell.Style
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
r, _, size := util.DecodeCharacter(b)
curStyle, found := w.getStyle(curStyle, bloc, r)
curStyle, found := w.getStyle(curStyle, bloc)
if found {
s = &curStyle
}
@@ -237,7 +236,7 @@ func (w *BufWindow) LocFromVisual(svloc buffer.Loc) buffer.Loc {
return bloc
}
r, size := utf8.DecodeRune(line)
r, _, size := util.DecodeCharacter(line)
draw()
width := 0
@@ -336,7 +335,14 @@ func (w *BufWindow) drawDiffGutter(backgroundStyle tcell.Style, softwrapped bool
}
func (w *BufWindow) drawLineNum(lineNumStyle tcell.Style, softwrapped bool, maxLineNumLength int, vloc *buffer.Loc, bloc *buffer.Loc) {
lineNum := strconv.Itoa(bloc.Y + 1)
cursorLine := w.Buf.GetActiveCursor().Loc.Y
var lineInt int
if w.Buf.Settings["relativeruler"] == false || cursorLine == bloc.Y {
lineInt = bloc.Y + 1
} else {
lineInt = bloc.Y - cursorLine
}
lineNum := strconv.Itoa(util.Abs(lineInt))
// Write the spaces before the line number if necessary
for i := 0; i < maxLineNumLength-len(lineNum); i++ {
@@ -360,7 +366,7 @@ func (w *BufWindow) drawLineNum(lineNumStyle tcell.Style, softwrapped bool, maxL
// getStyle returns the highlight style for the given character position
// If there is no change to the current highlight style it just returns that
func (w *BufWindow) getStyle(style tcell.Style, bloc buffer.Loc, r rune) (tcell.Style, bool) {
func (w *BufWindow) getStyle(style tcell.Style, bloc buffer.Loc) (tcell.Style, bool) {
if group, ok := w.Buf.Match(bloc.Y)[bloc.X]; ok {
s := config.GetColor(group.String())
return s, true
@@ -510,8 +516,15 @@ func (w *BufWindow) displayBuffer() {
}
bloc.X = bslice
draw := func(r rune, style tcell.Style, showcursor bool) {
draw := func(r rune, combc []rune, style tcell.Style, showcursor bool) {
if nColsBeforeStart <= 0 {
_, origBg, _ := style.Decompose()
_, defBg, _ := config.DefStyle.Decompose()
// syntax highlighting with non-default background takes precedence
// over cursor-line and color-column
dontOverrideBackground := origBg != defBg
for _, c := range cursors {
if c.HasSelection() &&
(bloc.GreaterEqual(c.CurSelection[0]) && bloc.LessThan(c.CurSelection[1]) ||
@@ -524,7 +537,7 @@ func (w *BufWindow) displayBuffer() {
}
}
if b.Settings["cursorline"].(bool) && w.active &&
if b.Settings["cursorline"].(bool) && w.active && !dontOverrideBackground &&
!c.HasSelection() && c.Y == bloc.Y {
if s, ok := config.Colorscheme["cursor-line"]; ok {
fg, _, _ := s.Decompose()
@@ -556,7 +569,7 @@ func (w *BufWindow) displayBuffer() {
}
if s, ok := config.Colorscheme["color-column"]; ok {
if colorcolumn != 0 && vloc.X-w.gutterOffset == colorcolumn {
if colorcolumn != 0 && vloc.X-w.gutterOffset+w.StartCol == colorcolumn && !dontOverrideBackground {
fg, _, _ := s.Decompose()
style = style.Background(fg)
}
@@ -568,7 +581,7 @@ func (w *BufWindow) displayBuffer() {
}
}
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, r, nil, style)
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, r, combc, style)
if showcursor {
for _, c := range cursors {
@@ -584,10 +597,11 @@ func (w *BufWindow) displayBuffer() {
totalwidth := w.StartCol - nColsBeforeStart
for len(line) > 0 {
r, size := utf8.DecodeRune(line)
curStyle, _ = w.getStyle(curStyle, bloc, r)
r, combc, size := util.DecodeCharacter(line)
draw(r, curStyle, true)
curStyle, _ = w.getStyle(curStyle, bloc)
draw(r, combc, curStyle, true)
width := 0
@@ -604,7 +618,7 @@ func (w *BufWindow) displayBuffer() {
// Draw any extra characters either spaces for tabs or @ for incomplete wide runes
if width > 1 {
for i := 1; i < width; i++ {
draw(char, curStyle, false)
draw(char, nil, curStyle, false)
}
}
bloc.X++
@@ -650,7 +664,7 @@ func (w *BufWindow) displayBuffer() {
for i := vloc.X; i < bufWidth; i++ {
curStyle := style
if s, ok := config.Colorscheme["color-column"]; ok {
if colorcolumn != 0 && i-w.gutterOffset == colorcolumn {
if colorcolumn != 0 && i-w.gutterOffset+w.StartCol == colorcolumn {
fg, _, _ := s.Decompose()
curStyle = style.Background(fg)
}
@@ -659,7 +673,8 @@ func (w *BufWindow) displayBuffer() {
}
if vloc.X != bufWidth {
draw(' ', curStyle, true)
// Display newline within a selection
draw(' ', nil, config.DefStyle, true)
}
bloc.X = w.StartCol
@@ -682,8 +697,27 @@ func (w *BufWindow) displayStatusLine() {
w.sline.Display()
} else if w.Y+w.Height != infoY {
w.drawStatus = true
divchars := config.GetGlobalOption("divchars").(string)
if util.CharacterCountInString(divchars) != 2 {
divchars = "|-"
}
_, _, size := util.DecodeCharacterInString(divchars)
divchar, combc, _ := util.DecodeCharacterInString(divchars[size:])
dividerStyle := config.DefStyle
if style, ok := config.Colorscheme["divider"]; ok {
dividerStyle = style
}
divreverse := config.GetGlobalOption("divreverse").(bool)
if divreverse {
dividerStyle = dividerStyle.Reverse(true)
}
for x := w.X; x < w.X+w.Width; x++ {
screen.SetContent(x, w.Y+w.Height-1, '-', nil, config.DefStyle.Reverse(true))
screen.SetContent(x, w.Y+w.Height-1, divchar, combc, dividerStyle)
}
} else {
w.drawStatus = false

View File

@@ -1,14 +1,12 @@
package display
import (
"unicode/utf8"
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/info"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/info"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
)
@@ -70,7 +68,7 @@ func (i *InfoWindow) IsActive() bool { return true }
func (i *InfoWindow) LocFromVisual(vloc buffer.Loc) buffer.Loc {
c := i.Buffer.GetActiveCursor()
l := i.Buffer.LineBytes(0)
n := utf8.RuneCountInString(i.Msg)
n := util.CharacterCountInString(i.Msg)
return buffer.Loc{c.GetCharPosInLine(l, vloc.X-n), 0}
}
@@ -86,13 +84,13 @@ func (i *InfoWindow) displayBuffer() {
activeC := b.GetActiveCursor()
blocX := 0
vlocX := utf8.RuneCountInString(i.Msg)
vlocX := util.CharacterCountInString(i.Msg)
tabsize := 4
line, nColsBeforeStart, bslice := util.SliceVisualEnd(line, blocX, tabsize)
blocX = bslice
draw := func(r rune, style tcell.Style) {
draw := func(r rune, combc []rune, style tcell.Style) {
if nColsBeforeStart <= 0 {
bloc := buffer.Loc{X: blocX, Y: 0}
if activeC.HasSelection() &&
@@ -112,8 +110,9 @@ func (i *InfoWindow) displayBuffer() {
c := r
if j > 0 {
c = ' '
combc = nil
}
screen.SetContent(vlocX, i.Y, c, nil, style)
screen.SetContent(vlocX, i.Y, c, combc, style)
}
vlocX++
}
@@ -124,9 +123,9 @@ func (i *InfoWindow) displayBuffer() {
for len(line) > 0 {
curVX := vlocX
curBX := blocX
r, size := utf8.DecodeRune(line)
r, combc, size := util.DecodeCharacter(line)
draw(r, i.defStyle())
draw(r, combc, i.defStyle())
width := 0
@@ -146,7 +145,7 @@ func (i *InfoWindow) displayBuffer() {
// Draw any extra characters either spaces for tabs or @ for incomplete wide runes
if width > 1 {
for j := 1; j < width; j++ {
draw(char, i.defStyle())
draw(char, nil, i.defStyle())
}
}
if activeC.X == curBX {
@@ -191,7 +190,7 @@ func (i *InfoWindow) scrollToSuggestion() {
s := i.totalSize()
for j, n := range i.Suggestions {
c := utf8.RuneCountInString(n)
c := util.CharacterCountInString(n)
if j == i.CurSuggestion {
if x+c >= i.hscroll+i.Width {
i.hscroll = util.Clamp(x+c+1-i.Width, 0, s-i.Width)
@@ -209,13 +208,13 @@ func (i *InfoWindow) scrollToSuggestion() {
}
func (i *InfoWindow) Display() {
i.Clear()
x := 0
if config.GetGlobalOption("keymenu").(bool) {
i.displayKeyMenu()
}
if i.HasPrompt || config.GlobalSettings["infobar"].(bool) {
i.Clear()
x := 0
if config.GetGlobalOption("keymenu").(bool) {
i.displayKeyMenu()
}
if !i.HasPrompt && !i.HasMessage && !i.HasError {
return
}

View File

@@ -6,17 +6,16 @@ import (
"regexp"
"strconv"
"strings"
"unicode/utf8"
luar "layeh.com/gopher-luar"
runewidth "github.com/mattn/go-runewidth"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
ulua "github.com/zyedidia/micro/internal/lua"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
)
// StatusLine represents the information line at the bottom
@@ -168,34 +167,36 @@ func (s *StatusLine) Display() {
statusLineStyle = style
}
leftLen := util.StringWidth(leftText, utf8.RuneCount(leftText), 1)
rightLen := util.StringWidth(rightText, utf8.RuneCount(rightText), 1)
leftLen := util.StringWidth(leftText, util.CharacterCount(leftText), 1)
rightLen := util.StringWidth(rightText, util.CharacterCount(rightText), 1)
winX := s.win.X
for x := 0; x < s.win.Width; x++ {
if x < leftLen {
r, size := utf8.DecodeRune(leftText)
r, combc, size := util.DecodeCharacter(leftText)
leftText = leftText[size:]
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
combc = nil
x++
}
screen.SetContent(winX+x, y, c, nil, statusLineStyle)
screen.SetContent(winX+x, y, c, combc, statusLineStyle)
}
} else if x >= s.win.Width-rightLen && x < rightLen+s.win.Width-rightLen {
r, size := utf8.DecodeRune(rightText)
r, combc, size := util.DecodeCharacter(rightText)
rightText = rightText[size:]
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
combc = nil
x++
}
screen.SetContent(winX+x, y, c, nil, statusLineStyle)
screen.SetContent(winX+x, y, c, combc, statusLineStyle)
}
} else {
screen.SetContent(winX+x, y, ' ', nil, statusLineStyle)

View File

@@ -1,13 +1,11 @@
package display
import (
"unicode/utf8"
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
)
type TabWindow struct {
@@ -34,7 +32,7 @@ func (w *TabWindow) LocFromVisual(vloc buffer.Loc) int {
for i, n := range w.Names {
x++
s := utf8.RuneCountInString(n)
s := util.CharacterCountInString(n)
if vloc.Y == w.Y && vloc.X < x+s {
return i
}
@@ -75,7 +73,7 @@ func (w *TabWindow) SetActive(a int) {
s := w.TotalSize()
for i, n := range w.Names {
c := utf8.RuneCountInString(n)
c := util.CharacterCountInString(n)
if i == a {
if x+c >= w.hscroll+w.Width {
w.hscroll = util.Clamp(x+c+1-w.Width, 0, s-w.Width)

View File

@@ -1,12 +1,11 @@
package display
import (
"unicode/utf8"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/shell"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
"github.com/zyedidia/terminal"
)
@@ -98,12 +97,12 @@ func (w *TermWindow) Display() {
}
text := []byte(w.Name())
textLen := utf8.RuneCount(text)
textLen := util.CharacterCount(text)
for x := 0; x < w.Width; x++ {
if x < textLen {
r, size := utf8.DecodeRune(text)
r, combc, size := util.DecodeCharacter(text)
text = text[size:]
screen.SetContent(w.X+x, w.Y+w.Height, r, nil, statusLineStyle)
screen.SetContent(w.X+x, w.Y+w.Height, r, combc, statusLineStyle)
} else {
screen.SetContent(w.X+x, w.Y+w.Height, ' ', nil, statusLineStyle)
}

View File

@@ -1,10 +1,11 @@
package display
import (
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/internal/views"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/internal/views"
)
type UIWindow struct {
@@ -24,16 +25,27 @@ func (w *UIWindow) drawNode(n *views.Node) {
dividerStyle = style
}
divchars := config.GetGlobalOption("divchars").(string)
if util.CharacterCountInString(divchars) != 2 {
divchars = "|-"
}
divchar, combc, _ := util.DecodeCharacterInString(divchars)
divreverse := config.GetGlobalOption("divreverse").(bool)
if divreverse {
dividerStyle = dividerStyle.Reverse(true)
}
for i, c := range cs {
if c.IsLeaf() && c.Kind == views.STVert {
if c.Kind == views.STVert {
if i != len(cs)-1 {
for h := 0; h < c.H; h++ {
screen.SetContent(c.X+c.W, c.Y+h, '|', nil, dividerStyle.Reverse(true))
screen.SetContent(c.X+c.W, c.Y+h, divchar, combc, dividerStyle)
}
}
} else {
w.drawNode(c)
}
w.drawNode(c)
}
}
@@ -41,32 +53,32 @@ func (w *UIWindow) Display() {
w.drawNode(w.root)
}
func (w *UIWindow) GetMouseSplitID(vloc buffer.Loc) uint64 {
var mouseLoc func(*views.Node) uint64
mouseLoc = func(n *views.Node) uint64 {
func (w *UIWindow) GetMouseSplitNode(vloc buffer.Loc) *views.Node {
var mouseLoc func(*views.Node) *views.Node
mouseLoc = func(n *views.Node) *views.Node {
cs := n.Children()
for i, c := range cs {
if c.Kind == views.STVert {
if i != len(cs)-1 {
if vloc.X == c.X+c.W && vloc.Y >= c.Y && vloc.Y < c.Y+c.H {
return c.ID()
return c
}
}
} else if c.Kind == views.STHoriz {
if i != len(cs)-1 {
if vloc.Y == c.Y+c.H-1 && vloc.X >= c.X && vloc.X < c.X+c.W {
return c.ID()
return c
}
}
}
}
for _, c := range cs {
m := mouseLoc(c)
if m != 0 {
if m != nil {
return m
}
}
return 0
return nil
}
return mouseLoc(w.root)
}

View File

@@ -1,7 +1,7 @@
package display
import (
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/v2/internal/buffer"
)
type View struct {

View File

@@ -5,7 +5,7 @@ import (
"os"
"path/filepath"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/v2/internal/config"
)
// LoadHistory attempts to load user history from configDir/buffers/history

View File

@@ -3,7 +3,7 @@ package info
import (
"fmt"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/v2/internal/buffer"
)
// The InfoBuf displays messages and other info at the bottom of the screen.
@@ -146,7 +146,7 @@ func (i *InfoBuf) DonePrompt(canceled bool) {
h := i.History[i.PromptType]
h[len(h)-1] = resp
}
i.PromptCallback = nil
// i.PromptCallback = nil
}
i.Replace(i.Start(), i.End(), "")
}

View File

@@ -15,14 +15,17 @@ import (
"regexp"
"runtime"
"strings"
"sync"
"time"
"unicode/utf8"
humanize "github.com/dustin/go-humanize"
lua "github.com/yuin/gopher-lua"
luar "layeh.com/gopher-luar"
)
var L *lua.LState
var Lock sync.Mutex
// LoadFile loads a lua file
func LoadFile(module string, file string, data []byte) error {
@@ -69,6 +72,8 @@ func Import(pkg string) *lua.LTable {
return importTime()
case "unicode/utf8", "utf8":
return importUtf8()
case "humanize":
return importHumanize()
default:
return nil
}
@@ -556,3 +561,12 @@ func importUtf8() *lua.LTable {
return pkg
}
func importHumanize() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Bytes", luar.New(L, humanize.Bytes))
L.SetField(pkg, "Ordinal", luar.New(L, humanize.Ordinal))
return pkg
}

View File

@@ -1,12 +1,12 @@
package screen
import (
"fmt"
"errors"
"os"
"sync"
"github.com/zyedidia/micro/internal/config"
"github.com/zyedidia/micro/internal/util"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell"
)
@@ -18,6 +18,9 @@ import (
// same time too.
var Screen tcell.Screen
// Events is the channel of tcell events
var Events chan (tcell.Event)
// The lock is necessary since the screen is polled on a separate thread
var lock sync.Mutex
@@ -97,6 +100,10 @@ func ShowCursor(x, y int) {
// SetContent sets a cell at a point on the screen and makes sure that it is
// synced with the last cursor location
func SetContent(x, y int, mainc rune, combc []rune, style tcell.Style) {
if !Screen.CanDisplay(mainc, true) {
mainc = '<27>'
}
Screen.SetContent(x, y, mainc, combc, style)
if util.FakeCursor && lastCursor.x == x && lastCursor.y == y {
lastCursor.r = mainc
@@ -126,8 +133,8 @@ func TempStart(screenWasNil bool) {
}
// Init creates and initializes the tcell screen
func Init() {
drawChan = make(chan bool)
func Init() error {
drawChan = make(chan bool, 8)
// Should we enable true color?
truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
@@ -146,15 +153,14 @@ func Init() {
var err error
Screen, err = tcell.NewScreen()
if err != nil {
fmt.Println(err)
fmt.Println("Fatal: Micro could not initialize a Screen.")
os.Exit(1)
return err
}
if err = Screen.Init(); err != nil {
fmt.Println(err)
os.Exit(1)
return err
}
Screen.SetPaste(config.GetGlobalOption("paste").(bool))
// restore TERM
if config.GetGlobalOption("xterm").(bool) {
os.Setenv("TERM", oldTerm)
@@ -163,4 +169,30 @@ func Init() {
if config.GetGlobalOption("mouse").(bool) {
Screen.EnableMouse()
}
return nil
}
// InitSimScreen initializes a simulation screen for testing purposes
func InitSimScreen() (tcell.SimulationScreen, error) {
drawChan = make(chan bool, 8)
// Initilize tcell
var err error
s := tcell.NewSimulationScreen("")
if s == nil {
return nil, errors.New("Failed to get a simulation screen")
}
if err = s.Init(); err != nil {
return nil, err
}
s.SetSize(80, 24)
Screen = s
if config.GetGlobalOption("mouse").(bool) {
Screen.EnableMouse()
}
return s, nil
}

View File

@@ -11,7 +11,7 @@ import (
"strings"
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/screen"
)
// ExecCommand executes a command using exec

View File

@@ -5,8 +5,8 @@ import (
"os/exec"
"strconv"
"github.com/zyedidia/micro/internal/buffer"
"github.com/zyedidia/micro/internal/screen"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/terminal"
)

View File

@@ -1,15 +1,11 @@
package util
import (
"unicode/utf8"
)
// LuaRuneAt is a helper function for lua plugins to return the rune
// at an index within a string
func LuaRuneAt(str string, runeidx int) string {
i := 0
for len(str) > 0 {
r, size := utf8.DecodeRuneInString(str)
r, _, size := DecodeCharacterInString(str)
str = str[size:]
@@ -26,7 +22,7 @@ func LuaRuneAt(str string, runeidx int) string {
func LuaGetLeadingWhitespace(s string) string {
ws := []byte{}
for len(s) > 0 {
r, size := utf8.DecodeRuneInString(s)
r, _, size := DecodeCharacterInString(s)
if r == ' ' || r == '\t' {
ws = append(ws, byte(r))
} else {
@@ -40,6 +36,6 @@ func LuaGetLeadingWhitespace(s string) string {
// LuaIsWordChar returns true if the first rune in a string is a word character
func LuaIsWordChar(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
r, _, _ := DecodeCharacterInString(s)
return IsWordChar(r)
}

96
internal/util/unicode.go Normal file
View File

@@ -0,0 +1,96 @@
package util
import (
"unicode"
"unicode/utf8"
)
// Unicode is annoying. A "code point" (rune in Go-speak) may need up to
// 4 bytes to represent it. In general, a code point will represent a
// complete character, but this is not always the case. A character with
// accents may be made up of multiple code points (the code point for the
// original character, and additional code points for each accent/marking).
// The functions below are meant to help deal with these additional "combining"
// code points. In underlying operations (search, replace, etc...), micro will
// treat a character with combining code points as just the original code point.
// For rendering, micro will display the combining characters. It's not perfect
// but it's pretty good.
var minMark = rune(unicode.Mark.R16[0].Lo)
func isMark(r rune) bool {
// Fast path
if r < minMark {
return false
}
return unicode.In(r, unicode.Mark)
}
// DecodeCharacter returns the next character from an array of bytes
// A character is a rune along with any accompanying combining runes
func DecodeCharacter(b []byte) (rune, []rune, int) {
r, size := utf8.DecodeRune(b)
b = b[size:]
c, s := utf8.DecodeRune(b)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
b = b[s:]
c, s = utf8.DecodeRune(b)
}
return r, combc, size
}
// DecodeCharacterInString returns the next character from a string
// A character is a rune along with any accompanying combining runes
func DecodeCharacterInString(str string) (rune, []rune, int) {
r, size := utf8.DecodeRuneInString(str)
str = str[size:]
c, s := utf8.DecodeRuneInString(str)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
str = str[s:]
c, s = utf8.DecodeRuneInString(str)
}
return r, combc, size
}
// CharacterCount returns the number of characters in a byte array
// Similar to utf8.RuneCount but for unicode characters
func CharacterCount(b []byte) int {
s := 0
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
if !isMark(r) {
s++
}
b = b[size:]
}
return s
}
// CharacterCount returns the number of characters in a string
// Similar to utf8.RuneCountInString but for unicode characters
func CharacterCountInString(str string) int {
s := 0
for _, r := range str {
if !isMark(r) {
s++
}
}
return s
}

View File

@@ -1,6 +1,7 @@
package util
import (
"bytes"
"errors"
"fmt"
"os"
@@ -12,7 +13,6 @@ import (
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/blang/semver"
runewidth "github.com/mattn/go-runewidth"
@@ -34,6 +34,9 @@ var (
// FakeCursor is used to disable the terminal cursor and have micro
// draw its own (enabled for windows consoles where the cursor is slow)
FakeCursor = false
// Stdout is a buffer that is written to stdout when micro closes
Stdout *bytes.Buffer
)
func init() {
@@ -46,6 +49,7 @@ func init() {
if runtime.GOOS == "windows" {
FakeCursor = true
}
Stdout = new(bytes.Buffer)
}
// SliceEnd returns a byte slice where the index is a rune index
@@ -59,7 +63,7 @@ func SliceEnd(slc []byte, index int) []byte {
return slc[totalSize:]
}
_, size := utf8.DecodeRune(slc[totalSize:])
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
@@ -77,7 +81,7 @@ func SliceEndStr(str string, index int) string {
return str[totalSize:]
}
_, size := utf8.DecodeRuneInString(str[totalSize:])
_, _, size := DecodeCharacterInString(str[totalSize:])
totalSize += size
i++
}
@@ -96,7 +100,7 @@ func SliceStart(slc []byte, index int) []byte {
return slc[:totalSize]
}
_, size := utf8.DecodeRune(slc[totalSize:])
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
@@ -114,7 +118,7 @@ func SliceStartStr(str string, index int) string {
return str[:totalSize]
}
_, size := utf8.DecodeRuneInString(str[totalSize:])
_, _, size := DecodeCharacterInString(str[totalSize:])
totalSize += size
i++
}
@@ -130,7 +134,7 @@ func SliceVisualEnd(b []byte, n, tabsize int) ([]byte, int, int) {
width := 0
i := 0
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
r, _, size := DecodeCharacter(b)
w := 0
switch r {
@@ -167,7 +171,7 @@ func StringWidth(b []byte, n, tabsize int) int {
i := 0
width := 0
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
r, _, size := DecodeCharacter(b)
b = b[size:]
switch r {
@@ -260,7 +264,7 @@ func IsBytesWhitespace(b []byte) bool {
// RunePos returns the rune index of a given byte index
// Make sure the byte index is not between code points
func RunePos(b []byte, i int) int {
return utf8.RuneCount(b[:i])
return CharacterCount(b[:i])
}
// MakeRelative will attempt to make a relative path between path and base
@@ -332,6 +336,10 @@ func GetModTime(path string) (time.Time, error) {
// EscapePath replaces every path separator in a given path with a %
func EscapePath(path string) string {
path = filepath.ToSlash(path)
if runtime.GOOS == "windows" {
// ':' is not valid in a path name on Windows but is ok on Unix
path = strings.Replace(path, ":", "%", -1)
}
return strings.Replace(path, "/", "%", -1)
}
@@ -339,7 +347,7 @@ func EscapePath(path string) string {
func GetLeadingWhitespace(b []byte) []byte {
ws := []byte{}
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
r, _, size := DecodeCharacter(b)
if r == ' ' || r == '\t' {
ws = append(ws, byte(r))
} else {
@@ -365,7 +373,7 @@ func GetCharPosInLine(b []byte, visualPos int, tabsize int) int {
i := 0 // char pos
width := 0 // string visual width
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
r, _, size := DecodeCharacter(b)
b = b[size:]
switch r {
@@ -411,7 +419,11 @@ func Clamp(val, min, max int) int {
}
func IsNonAlphaNumeric(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
return !unicode.IsLetter(c) && !unicode.IsNumber(c) && c != '_'
}
func IsAutocomplete(c rune) bool {
return c == '.' || !IsNonAlphaNumeric(c)
}
func ParseSpecial(s string) string {

View File

@@ -3,7 +3,6 @@ package highlight
import (
"regexp"
"strings"
"unicode/utf8"
)
func sliceStart(slc []byte, index int) []byte {
@@ -15,7 +14,7 @@ func sliceStart(slc []byte, index int) []byte {
return slc[totalSize:]
}
_, size := utf8.DecodeRune(slc[totalSize:])
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
@@ -32,7 +31,7 @@ func sliceEnd(slc []byte, index int) []byte {
return slc[:totalSize]
}
_, size := utf8.DecodeRune(slc[totalSize:])
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
@@ -47,9 +46,9 @@ func runePos(p int, str []byte) int {
return 0
}
if p >= len(str) {
return utf8.RuneCount(str)
return CharacterCount(str)
}
return utf8.RuneCount(str[:p])
return CharacterCount(str[:p])
}
func combineLineMatch(src, dst LineMatch) LineMatch {
@@ -112,7 +111,7 @@ func findIndex(regex *regexp.Regexp, skip *regexp.Regexp, str []byte, canMatchSt
var strbytes []byte
if skip != nil {
strbytes = skip.ReplaceAllFunc(str, func(match []byte) []byte {
res := make([]byte, utf8.RuneCount(match))
res := make([]byte, CharacterCount(match))
return res
})
} else {
@@ -148,7 +147,7 @@ func findAllIndex(regex *regexp.Regexp, str []byte, canMatchStart, canMatchEnd b
}
func (h *Highlighter) highlightRegion(highlights LineMatch, start int, canMatchEnd bool, lineNum int, line []byte, curRegion *region, statesOnly bool) LineMatch {
lineLen := utf8.RuneCount(line)
lineLen := CharacterCount(line)
if start == 0 {
if !statesOnly {
if _, ok := highlights[0]; !ok {
@@ -236,7 +235,7 @@ func (h *Highlighter) highlightRegion(highlights LineMatch, start int, canMatchE
}
func (h *Highlighter) highlightEmptyRegion(highlights LineMatch, start int, canMatchEnd bool, lineNum int, line []byte, statesOnly bool) LineMatch {
lineLen := utf8.RuneCount(line)
lineLen := CharacterCount(line)
if lineLen == 0 {
if canMatchEnd {
h.lastRegion = nil
@@ -336,11 +335,11 @@ func (h *Highlighter) HighlightStates(input LineStates) {
}
}
// HighlightMatches sets the matches for each line in between startline and endline
// HighlightMatches sets the matches for each line from startline to endline
// It sets all other matches in the buffer to nil to conserve memory
// This assumes that all the states are set correctly
func (h *Highlighter) HighlightMatches(input LineStates, startline, endline int) {
for i := startline; i < endline; i++ {
for i := startline; i <= endline; i++ {
if i >= input.LinesNum() {
break
}

85
pkg/highlight/unicode.go Normal file
View File

@@ -0,0 +1,85 @@
package highlight
import (
"unicode"
"unicode/utf8"
)
var minMark = rune(unicode.Mark.R16[0].Lo)
func isMark(r rune) bool {
// Fast path
if r < minMark {
return false
}
return unicode.In(r, unicode.Mark)
}
// DecodeCharacter returns the next character from an array of bytes
// A character is a rune along with any accompanying combining runes
func DecodeCharacter(b []byte) (rune, []rune, int) {
r, size := utf8.DecodeRune(b)
b = b[size:]
c, s := utf8.DecodeRune(b)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
b = b[s:]
c, s = utf8.DecodeRune(b)
}
return r, combc, size
}
// DecodeCharacterInString returns the next character from a string
// A character is a rune along with any accompanying combining runes
func DecodeCharacterInString(str string) (rune, []rune, int) {
r, size := utf8.DecodeRuneInString(str)
str = str[size:]
c, s := utf8.DecodeRuneInString(str)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
str = str[s:]
c, s = utf8.DecodeRuneInString(str)
}
return r, combc, size
}
// CharacterCount returns the number of characters in a byte array
// Similar to utf8.RuneCount but for unicode characters
func CharacterCount(b []byte) int {
s := 0
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
if !isMark(r) {
s++
}
b = b[size:]
}
return s
}
// CharacterCount returns the number of characters in a string
// Similar to utf8.RuneCountInString but for unicode characters
func CharacterCountInString(str string) int {
s := 0
for _, r := range str {
if !isMark(r) {
s++
}
}
return s
}

View File

@@ -0,0 +1,34 @@
color-link color-column "#001e28"
color-link comment "#608b4e,#001e28"
color-link constant.bool "#fd971f,#001e28"
color-link constant "#fd971f,#001e28"
color-link constant.string "#a0f000,#001e28"
color-link constant.string.char "#a0f000,#001e28"
color-link constant.string.url "#a0f000,#001e28"
color-link current-line-number "bold #fd971f,#001e28"
color-link cursor-line "#001923"
color-link default "#ffffff,#001e28"
color-link diff-added "#00c8a0,#001e28"
color-link diff-modified "#fd971f,#001e28"
color-link diff-deleted "#cb4b16,#001e28"
color-link divider "#001e28,#d0d0d0"
color-link error "#cb4b16,#001e28"
color-link gutter-error "#cb4b16,#001e28"
color-link gutter-warning "#fce94f,#001e28"
color-link identifier "#00c8a0,#001e28"
color-link identifier.class "#00c8a0,#001e28"
color-link indent-char "#a0a0a0,#001e28"
color-link line-number "#a0a0a0,#001923"
color-link preproc "bold #5aaae6,#001e28"
color-link special "#a6e22e,#001e28"
color-link statement "bold #5aaae6,#001e28"
color-link statusline "#ffffff,#0078c8"
color-link symbol "#00c8a0,#001e28"
color-link symbol.brackets "#ffffff,#001e28"
color-link symbol.tag "bold #5aaae6,#001e28"
color-link tabbar "#001e28,#ffffff"
color-link todo "#fce94f,#001e28"
color-link type "bold #3cc83c,#001e28"
color-link type.keyword "bold #5aaae6,#001e28"
color-link type.extended "#ffffff,#001e28"
color-link underlined "#608b4e,#001e28"

View File

@@ -0,0 +1,34 @@
color-link color-column "#f0f0f0"
color-link comment "#3f7f5f,#f0f0f0"
color-link constant.bool "#641e00,#f0f0f0"
color-link constant "#641e00,#f0f0f0"
color-link constant.string "#0000ff,#f0f0f0"
color-link constant.string.char "#0000ff,#f0f0f0"
color-link constant.string.url "#0000ff,#f0f0f0"
color-link current-line-number "bold #004080,#f0f0f0"
color-link cursor-line "#e6e6e6"
color-link default "#000000,#f0f0f0"
color-link diff-added "#008040,#f0f0f0"
color-link diff-modified "#641e00,#f0f0f0"
color-link diff-deleted "#500000,#f0f0f0"
color-link divider "#f0f0f0,#004080"
color-link error "#500000,#f0f0f0"
color-link gutter-error "#500000,#f0f0f0"
color-link gutter-warning "#dcc800,#f0f0f0"
color-link identifier "bold #0078a0,#f0f0f0"
color-link identifier.class "bold #0078a0,#f0f0f0"
color-link indent-char "#404040,#f0f0f0"
color-link line-number "#404040,#e6e6e6"
color-link preproc "bold #780050,#f0f0f0"
color-link special "bold #0078a0,#f0f0f0"
color-link statement "bold #780050,#f0f0f0"
color-link statusline "#ffffff,#0078c8"
color-link symbol "bold #0078a0,#f0f0f0"
color-link symbol.brackets "#000000,#f0f0f0"
color-link symbol.tag "bold #780050,#f0f0f0"
color-link tabbar "#f0f0f0,#004080"
color-link todo "#dcc800,#f0f0f0"
color-link type "bold #004080,#f0f0f0"
color-link type.keyword "bold #780050,#f0f0f0"
color-link type.extended "#000000,#f0f0f0"
color-link underlined "#3f7f5f,#f0f0f0"

View File

@@ -0,0 +1,34 @@
color-link color-column "#2d0023"
color-link comment "#886484,#2d0023"
color-link constant.bool "#fd971f,#2d0023"
color-link constant "#fd971f,#2d0023"
color-link constant.string "#a0f000,#2d0023"
color-link constant.string.char "#a0f000,#2d0023"
color-link constant.string.url "#a0f000,#2d0023"
color-link current-line-number "bold #fd971f,#2d0023"
color-link cursor-line "#230019"
color-link default "#ffffff,#2d0023"
color-link diff-added "#00c8a0,#2d0023"
color-link diff-modified "#fd971f,#2d0023"
color-link diff-deleted "#cb4b16,#2d0023"
color-link divider "#2d0023,#d0d0d0"
color-link error "#cb4b16,#2d0023"
color-link gutter-error "#cb4b16,#2d0023"
color-link gutter-warning "#fce94f,#2d0023"
color-link identifier "#00c8a0,#2d0023"
color-link identifier.class "#00c8a0,#2d0023"
color-link indent-char "#a0a0a0,#2d0023"
color-link line-number "#a0a0a0,#230019"
color-link preproc "bold #5aaae6,#2d0023"
color-link special "#a6e22e,#2d0023"
color-link statement "bold #5aaae6,#2d0023"
color-link statusline "#ffffff,#0078c8"
color-link symbol "#00c8a0,#2d0023"
color-link symbol.brackets "#ffffff,#2d0023"
color-link symbol.tag "bold #5aaae6,#2d0023"
color-link tabbar "#2d0023,#ffffff"
color-link todo "#fce94f,#2d0023"
color-link type "bold #3cc83c,#2d0023"
color-link type.keyword "bold #5aaae6,#2d0023"
color-link type.extended "#ffffff,#2d0023"
color-link underlined "#886484,#2d0023"

View File

@@ -11,7 +11,7 @@ color-link todo "bold #cc7833,#2b2b2b"
color-link error "bold #cc7833,#2b2b2b"
color-link gutter-error "#cc7833,#11151C"
color-link indent-char "#414141,#2b2b2b"
color-link line-number "#a1a1a1,#353535"
color-link line-number "#a1a1a1,#232323"
color-link current-line-number "#e6e1dc,#2b2b2b"
color-link diff-added "#00AF00"
color-link diff-modified "#FFAF00"
@@ -19,8 +19,8 @@ color-link diff-deleted "#D70000"
color-link gutter-warning "#a5c261,#11151C"
color-link symbol "#edb753,#2b2b2b"
color-link identifier "#edb753,#2b2b2b"
color-link statusline "#a1a1a1,#414141"
color-link tabbar "bold #a1a1a1,#414141"
color-link statusline "#b1b1b1,#232323"
color-link tabbar "bold #b1b1b1,#232323"
color-link cursor-line "#353535"
color-link color-column "#353535"
color-link space "underline #e6e1dc,#2b2b2b"

View File

@@ -8,7 +8,7 @@ This help page aims to cover two aspects of micro's syntax highlighting engine:
## Colorschemes
To change your colorscheme, press CtrlE in micro to bring up the command
To change your colorscheme, press Ctrl-e in micro to bring up the command
prompt, and type:
```
@@ -132,7 +132,7 @@ If you would like no foreground you can just use a comma with nothing in front:
color-link comment ",blue"
```
You can also put bold, or underline in front of the color:
You can also put bold, italic, or underline in front of the color:
```
color-link comment "bold red"

View File

@@ -1,6 +1,6 @@
# Command bar
The command bar is opened by pressing CtrlE. It is a single-line buffer,
The command bar is opened by pressing Ctrl-e. It is a single-line buffer,
meaning that all keybindings from a normal buffer are supported (as well
as mouse and selection).
@@ -13,7 +13,7 @@ does not look up environment variables.
# Commands
Micro provides the following commands that can be executed at the command-bar
by pressing `CtrlE` and entering the command. Arguments are placed in single
by pressing `Ctrl-e` and entering the command. Arguments are placed in single
quotes here but these are not necessary when entering the command in micro.
* `bind 'key' 'action'`: creates a keybinding from key to action. See the
@@ -62,6 +62,11 @@ quotes here but these are not necessary when entering the command in micro.
* `tab 'filename'`: opens the given file in a new tab.
* `tabmove '[-+]?n'`: Moves the active tab to another slot. `n` is an integer.
If `n` is prefixed with `-` or `+`, then it represents a relative position
(e.g. `tabmove +2` moves the tab to the right by `2`). If `n` has no prefix,
it represents an absolute position (e.g. `tabmove 2` moves the tab to slot `2`).
* `tabswitch 'tab'`: This command will switch to the specified tab. The `tab`
can either be a tab number, or a name of a tab.
@@ -104,7 +109,7 @@ quotes here but these are not necessary when entering the command in micro.
is most useful for debugging keybindings.
* `showkey`: Show the action(s) bound to a given key. For example
running `> showkey CtrlC` will display `Copy`.
running `> showkey Ctrl-c` will display `Copy`.
* `term exec?`: Open a terminal emulator running the given executable. If no
executable is given, this will open the default shell in the terminal

View File

@@ -4,8 +4,52 @@ because there are multiple methods. This help document will explain
the various methods for copying and pasting, how they work,
and the best methods for doing so over SSH.
# OSC 52 (terminal clipboard)
If possible, setting the `clipboard` option to `terminal` will give
best results because it will work over SSH and locally. However, there
is limited support among terminal emulators for the terminal clipboard
(which uses the OSC 52 protocol to communicate clipboard contents).
Here is a list of terminal emulators and their status:
* Kitty: supported, but only writing is enabled by default. To enable
reading, add `read-primary` and `read-clipboard` to the
`clipboard_control` option.
* iTerm2: only copying (writing to clipboard) is supported. Must be enabled in
`Preferences->General-> Selection->Applications in terminal may access clipboard`.
You can use Command-v to paste.
* `st`: supported.
* `rxvt-unicode`: not natively supported, but there is a Perl extension
[here](http://anti.teamidiot.de/static/nei/*/Code/urxvt/).
* `xterm`: supported, but disabled by default. It can be enabled by putting
the following in `.Xresources` or `.Xdefaults`:
`XTerm*disallowedWindowOps: 20,21,SetXprop`.
* `gnome-terminal`: does not support OSC 52.
**Summary:** If you want copy and paste to work over SSH, then you
should set `clipboard` to `terminal`, and make sure your terminal
supports OSC 52.
# Pasting
## Recommendations (TL;DR)
The recommended method of pasting is the following:
* If you are not working over SSH, use the micro keybinding (Ctrl-v
by default) to perform pastes. If on Linux, install `xclip` or
`xsel` beforehand.
* If you are working over SSH, use the terminal keybinding
(Ctrl-Shift-v or Command-v) to perform pastes. If your terminal
does not support bracketed paste, when performing a paste first
enable the `paste` option, and when finished disable the option.
## Micro paste events
Micro is an application that runs within the terminal. This means
@@ -56,20 +100,23 @@ machine's clipboard. On the other hand, the terminal keybinding
for paste will access your local clipboard and send the text over
the network as a paste event, which is what you want.
## Recommendations
# Copying
The recommended method of pasting is the following:
# Recommendations (TL;DR)
* If you are not working over SSH, use the micro keybinding (Ctrl-v
by default) to perform pastes. If on Linux, install `xclip` or
`xsel` beforehand.
The recommended method of copying is the following:
* If you are not working over SSH, use the micro keybinding (Ctrl-c by
default) to perform copies. If on Linux, install `xclip` or `xsel`
beforehand.
* If you are working over SSH, use the terminal keybinding
(Ctrl-Shift-v or Command-v) to perform pastes. If your terminal
does not support bracketed paste, when performing a paste first
enable the `paste` option, and when finished disable the option.
# Copying
(Ctrl-Shift-c or Command-c) to perform copies. You must first disable
the `mouse` option to perform a terminal selection, and you may wish
to disable line numbers and diff indicators (`ruler` and `diffgutter`
options) and close other splits. This method will only be able to copy
characters that are displayed on the screen (you will not be able to
copy more than one page's worth of characters).
Copying follows a similar discussion to the one above about pasting.
The primary difference is before performing a copy, the application
@@ -92,19 +139,3 @@ means that for copying multiple lines using the terminal selection, you
should first disable line numbers and diff indicators (turn off the `ruler`
and `diffgutter` options), otherwise they might be part of your selection
and copied.
## Recommendations
The recommended method of copying is the following:
* If you are not working over SSH, use the micro keybinding (Ctrl-c by
default) to perform copies. If on Linux, install `xclip` or `xsel`
beforehand.
* If you are working over SSH, use the terminal keybinding
(Ctrl-Shift-c or Command-c) to perform copies. You must first disable
the `mouse` option to perform a terminal selection, and you may wish
to disable line numbers and diff indicators (`ruler` and `diffgutter`
options) and close other splits. This method will only be able to copy
characters that are displayed on the screen (you will not be able to
copy more than one page's worth of characters).

View File

@@ -11,115 +11,115 @@ can change it!
| Key | Description of function |
|---------- |-------------------------------------------------------------------------------------------------- |
| Ctrl+E | Open a command prompt for running commands (see `> help commands` for a list of valid commands). |
| Ctrl-e | Open a command prompt for running commands (see `> help commands` for a list of valid commands). |
| Tab | In command prompt, it will autocomplete if possible. |
| Ctrl+B | Run a shell command (this will close micro while your command executes). |
| Ctrl-b | Run a shell command (this will close micro while your command executes). |
### Navigation
| Key | Description of function |
|---------------------------- |------------------------------------------------------------------------------------------ |
| Arrows | Move the cursor around |
| Shift+arrows | Move and select text |
| Alt(Ctrl on Mac)+LeftArrow | Move to the beginning of the current line |
| Alt(Ctrl on Mac)+RightArrow | Move to the end of the current line |
| Home | Move to the beginning of the current line |
| Shift-arrows | Move and select text |
| Alt(Ctrl on Mac)-LeftArrow | Move to the beginning of the current line |
| Alt(Ctrl on Mac)-RightArrow | Move to the end of the current line |
| Home | Move to the beginning of text on the current line |
| End | Move to the end of the current line |
| Ctrl(Alt on Mac)+LeftArrow | Move cursor one word left |
| Ctrl(Alt on Mac)+RightArrow | Move cursor one word right |
| Alt+{ | Move cursor to previous empty line, or beginning of document |
| Alt+} | Move cursor to next empty line, or end of document |
| Ctrl(Alt on Mac)-LeftArrow | Move cursor one word left |
| Ctrl(Alt on Mac)-RightArrow | Move cursor one word right |
| Alt-{ | Move cursor to previous empty line, or beginning of document |
| Alt-} | Move cursor to next empty line, or end of document |
| PageUp | Move cursor up one page |
| PageDown | Move cursor down one page |
| Ctrl+Home or Ctrl+UpArrow | Move cursor to start of document |
| Ctrl+End or Ctrl+DownArrow | Move cursor to end of document |
| Ctrl+L | Jump to a line in the file (prompts with #) |
| Ctrl+W | Cycle between splits in the current tab (use `> vsplit` or `> hsplit` to create a split) |
| Ctrl-Home or Ctrl-UpArrow | Move cursor to start of document |
| Ctrl-End or Ctrl-DownArrow | Move cursor to end of document |
| Ctrl-l | Jump to a line in the file (prompts with #) |
| Ctrl-w | Cycle between splits in the current tab (use `> vsplit` or `> hsplit` to create a split) |
### Tabs
| Key | Description of function |
|-------- |------------------------- |
| Ctrl+T | Open a new tab |
| Alt+, | Previous tab |
| Alt+. | Next tab |
| Ctrl-t | Open a new tab |
| Alt-, | Previous tab |
| Alt-. | Next tab |
### Find Operations
| Key | Description of function |
|---------- |------------------------------------------ |
| Ctrl+F | Find (opens prompt) |
| Ctrl+N | Find next instance of current search |
| Ctrl+P | Find previous instance of current search |
| Ctrl-f | Find (opens prompt) |
| Ctrl-n | Find next instance of current search |
| Ctrl-p | Find previous instance of current search |
### File Operations
| Key | Description of function |
|---------- |------------------------------------------------------------------ |
| Ctrl+Q | Close current file (quits micro if this is the last file open) |
| Ctrl+O | Open a file (prompts for filename) |
| Ctrl+S | Save current file |
| Ctrl-q | Close current file (quits micro if this is the last file open) |
| Ctrl-o | Open a file (prompts for filename) |
| Ctrl-s | Save current file |
### Text operations
| Key | Description of function |
|------------------------------------ |------------------------------------------ |
| Ctrl(Alt on Mac)+Shift+RightArrow | Select word right |
| Ctrl(Alt on Mac)+Shift+LeftArrow | Select word left |
| Alt(Ctrl on Mac)+Shift+LeftArrow | Select to start of current line |
| Alt(Ctrl on Mac)+Shift+RightArrow | Select to end of current line |
| Shift+Home | Select to start of current line |
| Shift+End | Select to end of current line |
| Ctrl+Shift+UpArrow | Select to start of file |
| Ctrl+Shift+DownArrow | Select to end of file |
| Ctrl+X | Cut selected text |
| Ctrl+C | Copy selected text |
| Ctrl+V | Paste |
| Ctrl+K | Cut current line |
| Ctrl+D | Duplicate current line |
| Ctrl+Z | Undo |
| Ctrl+Y | Redo |
| Alt+UpArrow | Move current line or selected lines up |
| Alt+DownArrow | Move current line of selected lines down |
| Alt+Backspace or Alt+Ctrl+H | Delete word left |
| Ctrl+A | Select all |
| Ctrl(Alt on Mac)-Shift-RightArrow | Select word right |
| Ctrl(Alt on Mac)-Shift-LeftArrow | Select word left |
| Alt(Ctrl on Mac)-Shift-LeftArrow | Select to start of current line |
| Alt(Ctrl on Mac)-Shift-RightArrow | Select to end of current line |
| Shift-Home | Select to start of current line |
| Shift-End | Select to end of current line |
| Ctrl-Shift-UpArrow | Select to start of file |
| Ctrl-Shift-DownArrow | Select to end of file |
| Ctrl-x | Cut selected text |
| Ctrl-c | Copy selected text |
| Ctrl-v | Paste |
| Ctrl-k | Cut current line |
| Ctrl-d | Duplicate current line |
| Ctrl-z | Undo |
| Ctrl-y | Redo |
| Alt-UpArrow | Move current line or selected lines up |
| Alt-DownArrow | Move current line or selected lines down |
| Alt-Backspace or Alt-Ctrl-h | Delete word left |
| Ctrl-a | Select all |
### Macros
| Key | Description of function |
|---------- |---------------------------------------------------------------------------------- |
| Ctrl+U | Toggle macro recording (press Ctrl+U to start recording and press again to stop) |
| Ctrl+J | Run latest recorded macro |
| Ctrl-u | Toggle macro recording (press Ctrl-u to start recording and press again to stop) |
| Ctrl-j | Run latest recorded macro |
### Multiple cursors
| Key | Description of function |
|------------------ |---------------------------------------------------------------------------------------------- |
| Alt+N | Create new multiple cursor from selection (will select current word if no current selection) |
| AltShiftUp | Spawn a new cursor on the line above the current one |
| AltShiftDown | Spawn a new cursor on the line below the current one |
| Alt+P | Remove latest multiple cursor |
| Alt+C | Remove all multiple cursors (cancel) |
| Alt+X | Skip multiple cursor selection |
| Alt+M | Spawn a new cursor at the beginning of every line in the current selection |
| Ctrl+MouseLeft | Place a multiple cursor at any location |
| Alt-n | Create new multiple cursor from selection (will select current word if no current selection) |
| Alt-Shift-Up | Spawn a new cursor on the line above the current one |
| Alt-Shift-Down | Spawn a new cursor on the line below the current one |
| Alt-p | Remove latest multiple cursor |
| Alt-c | Remove all multiple cursors (cancel) |
| Alt-x | Skip multiple cursor selection |
| Alt-m | Spawn a new cursor at the beginning of every line in the current selection |
| Ctrl-MouseLeft | Place a multiple cursor at any location |
### Other
| Key | Description of function |
|---------- |-------------------------------------------------------------------------------------- |
| Ctrl+G | Open help file |
| Ctrl+H | Backspace (old terminals do not support the backspace key and use Ctrl+H instead) |
| Ctrl+R | Toggle the line number ruler |
| Ctrl-g | Open help file |
| Ctrl-h | Backspace (old terminals do not support the backspace key and use Ctrl+H instead) |
| Ctrl-r | Toggle the line number ruler |
### Emacs style actions
| Key | Description of function |
|---------- |-------------------------- |
| Alt+F | Next word |
| Alt+B | Previous word |
| Alt+A | Move to start of line |
| Alt+E | Move to end of line |
| Alt-f | Next word |
| Alt-b | Previous word |
| Alt-a | Move to start of line |
| Alt-e | Move to end of line |
### Function keys.

View File

@@ -4,9 +4,9 @@ Micro is a terminal-based text editor that aims to be easy to use and
intuitive, while also taking advantage of the full capabilities of modern
terminals.
To open the command bar, press CtrlE. This enables a `>` prompt for typing
To open the command bar, press Ctrl-e. This enables a `>` prompt for typing
commands. From now on when the documentation says to run a command such as `>
help`, this means press CtrlE and type `help` (and press enter to execute the
help`, this means press Ctrl-e and type `help` (and press enter to execute the
command).
For a list of the default keybindings run `> help defaultkeys`.
@@ -14,7 +14,7 @@ For more information on keybindings see `> help keybindings`.
## Quick-start
Press Ctrl-q to quit, and Ctrl-s to save. Press CtrlE to start typing commands
Press Ctrl-q to quit, and Ctrl-s to save. Press Ctrl-e to start typing commands
and you can see which commands are available by pressing tab, or by viewing the
help topic `> help commands`.
@@ -34,7 +34,7 @@ Press Ctrl-w to move between splits, and type `> vsplit filename` or
Micro has a built-in help system which can be accessed with the `help` command.
To use it, press CtrlE to access command mode and type in `help` followed by a
To use it, press Ctrl-e to access command mode and type in `help` followed by a
topic. Typing `help` followed by nothing will open this page.
Here are the possible help topics that you can read:

View File

@@ -30,11 +30,17 @@ following in the `bindings.json` file.
```json
{
"CtrlY": "Undo",
"CtrlZ": "Redo"
"Ctrl-y": "Undo",
"Ctrl-z": "Redo"
}
```
**Note:** The syntax `<Modifier><key>` is equivalent to `<Modifier>-<key>`. In
addition, Ctrl-Shift bindings are not supported by terminals, and are the same
as simply Ctrl bindings. This means that `CtrlG`, `Ctrl-G`, and `Ctrl-g` all
mean the same thing. However, for Alt this is not the case: `AltG` and `Alt-G`
mean `Alt-Shift-g`, while `Alt-g` does not require the Shift modifier.
In addition to editing your `~/.config/micro/bindings.json`, you can run
`>bind <keycombo> <action>` For a list of bindable actions, see below.
@@ -73,21 +79,27 @@ You can also bind a key to execute a command in command mode (see
}
```
**Note for macOS**: By default, macOS terminals do not forward alt events and
instead insert unicode characters. To fix this, do the following:
* iTerm2: select `Esc+` for `Left Option Key` in `Preferences->Profiles->Keys`.
* Terminal.app: Enable `Use Option key as Meta key` in `Preferences->Profiles->Keyboard`.
Now when you press `Alt-p` the `pwd` command will be executed which will show
your working directory in the infobar.
You can also bind an "editable" command with `command-edit:`. This means that
micro won't immediately execute the command when you press the binding, but
instead just place the string in the infobar in command mode. For example,
you could rebind `CtrlG` to `> help`:
you could rebind `Ctrl-g` to `> help`:
```json
{
"CtrlG": "command-edit:help "
"Ctrl-g": "command-edit:help "
}
```
Now when you press `CtrlG`, `help` will appear in the command bar and your
Now when you press `Ctrl-g`, `help` will appear in the command bar and your
cursor will be placed after it (note the space in the json that controls the
cursor placement).
@@ -162,6 +174,8 @@ SelectUp
SelectDown
SelectLeft
SelectRight
SelectToStartOfText
SelectToStartOfTextToggle
WordRight
WordLeft
SelectWordRight
@@ -183,11 +197,13 @@ Save
SaveAll
SaveAs
Find
FindLiteral
FindNext
FindPrevious
Undo
Redo
Copy
CopyLine
Cut
CutLine
DuplicateLine
@@ -209,6 +225,8 @@ HalfPageUp
HalfPageDown
StartOfLine
EndOfLine
StartOfText
StartOfTextToggle
ParagraphPrevious
ParagraphNext
ToggleHelp
@@ -245,6 +263,9 @@ JumpToMatchingBrace
Autocomplete
```
The `StartOfTextToggle` and `SelectToStartOfTextToggle` actions toggle between
jumping to the start of the text (first) and start of the line.
You can also bind some mouse actions (these must be bound to mouse buttons)
```
@@ -342,32 +363,32 @@ F62
F63
F64
CtrlSpace
CtrlA
CtrlB
CtrlC
CtrlD
CtrlE
CtrlF
CtrlG
CtrlH
CtrlI
CtrlJ
CtrlK
CtrlL
CtrlM
CtrlN
CtrlO
CtrlP
CtrlQ
CtrlR
CtrlS
CtrlT
CtrlU
CtrlV
CtrlW
CtrlX
CtrlY
CtrlZ
Ctrl-a
Ctrl-b
Ctrl-c
Ctrl-d
Ctrl-e
Ctrl-f
Ctrl-g
Ctrl-h
Ctrl-i
Ctrl-j
Ctrl-k
Ctrl-l
Ctrl-m
Ctrl-n
Ctrl-o
Ctrl-p
Ctrl-q
Ctrl-r
Ctrl-s
Ctrl-t
Ctrl-u
Ctrl-v
Ctrl-w
Ctrl-x
Ctrl-y
Ctrl-z
CtrlLeftSq
CtrlBackslash
CtrlRightSq
@@ -410,21 +431,21 @@ conventions for text editing defaults.
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "WordLeft",
"AltRight": "WordRight",
"AltLeft": "WordLeft", (Mac)
"AltRight": "WordRight", (Mac)
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"CtrlShiftRight": "SelectWordRight",
"CtrlShiftLeft": "SelectWordLeft",
"AltLeft": "StartOfLine",
"AltLeft": "StartOfTextToggle",
"AltRight": "EndOfLine",
"AltShiftRight": "SelectWordRight", (Mac)
"AltShiftLeft": "SelectWordLeft", (Mac)
"CtrlLeft": "StartOfText", (Mac)
"CtrlRight": "EndOfLine", (Mac)
"AltShiftLeft": "SelectToStartOfLine",
"CtrlShiftLeft": "SelectToStartOfText", (Mac)
"ShiftHome": "SelectToStartOfLine",
"AltShiftLeft": "SelectToStartOfTextToggle",
"CtrlShiftLeft": "SelectToStartOfTextToggle", (Mac)
"ShiftHome": "SelectToStartOfTextToggle",
"AltShiftRight": "SelectToEndOfLine",
"CtrlShiftRight": "SelectToEndOfLine", (Mac)
"ShiftEnd": "SelectToEndOfLine",
@@ -435,29 +456,29 @@ conventions for text editing defaults.
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Ctrl-h": "Backspace",
"Backspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "OutdentSelection|OutdentLine",
"CtrlO": "OpenFile",
"CtrlS": "Save",
"CtrlF": "Find",
"CtrlN": "FindNext",
"CtrlP": "FindPrevious",
"CtrlZ": "Undo",
"CtrlY": "Redo",
"CtrlC": "Copy",
"CtrlX": "Cut",
"CtrlK": "CutLine",
"CtrlD": "DuplicateLine",
"CtrlV": "Paste",
"CtrlA": "SelectAll",
"CtrlT": "AddTab",
"Alt,": "PreviousTab",
"Alt.": "NextTab",
"Home": "StartOfLine",
"Ctrl-o": "OpenFile",
"Ctrl-s": "Save",
"Ctrl-f": "Find",
"Ctrl-n": "FindNext",
"Ctrl-p": "FindPrevious",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-d": "DuplicateLine",
"Ctrl-v": "Paste",
"Ctrl-a": "SelectAll",
"Ctrl-t": "AddTab",
"Alt-,": "PreviousTab",
"Alt-.": "NextTab",
"Home": "StartOfText",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
@@ -465,17 +486,17 @@ conventions for text editing defaults.
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"CtrlG": "ToggleHelp",
"Ctrl-g": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"CtrlR": "ToggleRuler",
"CtrlL": "command-edit:goto ",
"Ctrl-r": "ToggleRuler",
"Ctrl-l": "command-edit:goto ",
"Delete": "Delete",
"CtrlB": "ShellMode",
"CtrlQ": "Quit",
"CtrlE": "CommandMode",
"CtrlW": "NextSplit",
"CtrlU": "ToggleMacro",
"CtrlJ": "PlayMacro",
"Ctrl-b": "ShellMode",
"Ctrl-q": "Quit",
"Ctrl-e": "CommandMode",
"Ctrl-w": "NextSplit",
"Ctrl-u": "ToggleMacro",
"Ctrl-j": "PlayMacro",
"Insert": "ToggleOverwriteMode",
// Emacs-style keybindings
@@ -511,7 +532,7 @@ conventions for text editing defaults.
## Final notes
Note: On some old terminal emulators and on Windows machines, `CtrlH` should be
Note: On some old terminal emulators and on Windows machines, `Ctrl-h` should be
used for backspace.
Additionally, alt keys can be bound by using `Alt-key`. For example `Alt-a` or

View File

@@ -37,21 +37,45 @@ Here are the available options:
closed cleanly. In the case of a system crash or a micro crash, the contents
of the buffer can be recovered automatically by opening the file that was
being edited before the crash, or manually by searching for the backup in
the backup directory. Backups are made in the background when a buffer is
modified and the latest backup is more than 8 seconds old, or when micro
detects a crash. It is highly recommended that you leave this feature
enabled.
the backup directory. Backups are made in the background for newly modified
buffers every 8 seconds, or when micro detects a crash.
default value: `true`
* `backupdir`: the directory micro should place backups in. For the default
value of `""` (empty string), the backup directory will be
`ConfigDir/backups`, which is `~/.config/micro/backups` by default. The
directory specified for backups will be created if it does not exist.
default value: `""` (empty string)
* `basename`: in the infobar and tabbar, show only the basename of the file
being edited rather than the full path.
default value: `false`
* `clipboard`: specifies how micro should access the system clipboard.
Possible values are:
* `external`: accesses clipboard via an external tool, such as xclip/xsel
or wl-clipboard on Linux, pbcopy/pbpaste on MacOS, and system calls on
Windows. On Linux, if you do not have one of the tools installed, or if
they are not working, micro will throw an error and use an internal
clipboard.
* `terminal`: accesses the clipboard via your terminal emulator. Note that
there is limited support among terminal emulators for this feature
(called OSC 52). Terminals that are known to work are Kitty (enable
reading with `clipboard_control` setting), iTerm2 (only copying),
st, rxvt-unicode and xterm if enabled (see `> help copypaste` for
details). Note that Gnome-terminal does not support this feature. With
this setting, copy-paste **will** work over ssh. See `> help copypaste`
for details.
* `internal`: micro will use an internal clipboard.
default value: `external`
* `colorcolumn`: if this is not set to 0, it will display a column at the
specified column. This is useful if you want column 80 to be highlighted
special for example.
specified column. This is useful if you want column 80 to be highlighted
special for example.
default value: `0`
@@ -80,6 +104,21 @@ Here are the available options:
default value: `false`
* `divchars`: specifies the "divider" characters used for the dividing line
between vertical/horizontal splits. The first character is for vertical
dividers, and the second is for horizontal dividers. By default, for
horizontal splits the statusline serves as a divider, but if the statusline
is disabled the horizontal divider character will be used.
default value: `|-`
* `divreverse`: colorschemes provide the color (foreground and background) for
the characters displayed in split dividers. With this option enabled, the
colors specified by the colorscheme will be reversed (foreground and
background colors swapped).
default value: `true`
* `encoding`: the encoding to open and save files with. Supported encodings
are listed at https://www.w3.org/TR/encoding/.
@@ -102,12 +141,15 @@ Here are the available options:
default value: `false`
* `fileformat`: this determines what kind of line endings micro will use for
the file. UNIX line endings are just `\n` (linefeed) whereas dos line
the file. Unix line endings are just `\n` (linefeed) whereas dos line
endings are `\r\n` (carriage return + linefeed). The two possible values for
this option are `unix` and `dos`. The fileformat will be automatically
detected (when you open an existing file) and displayed on the statusline,
but this option is useful if you would like to change the line endings or if
you are starting a new file.
you are starting a new file. Changing this option while editing a file will
change its line endings. Opening a file with this option set will only have
an effect if the file is empty/newly created, because otherwise the fileformat
will be automatically detected from the existing line endings.
default value: `unix`
@@ -163,7 +205,7 @@ Here are the available options:
default value: `true`
* `paste`: Treat characters sent from the terminal in a single chunk as a paste
* `paste`: treat characters sent from the terminal in a single chunk as a paste
event rather than a series of manual key presses. If you are pasting using
the terminal keybinding (not Ctrl-v, which is micro's default paste
keybinding) then it is a good idea to enable this option during the paste
@@ -172,6 +214,23 @@ Here are the available options:
default value: `false`
* `parsecursor`: if enabled, this will cause micro to parse filenames such as
file.txt:10:5 as requesting to open `file.txt` with the cursor at line 10
and column 5. The column number can also be dropped to open the file at a
given line and column 0. Note that with this option enabled it is not possible
to open a file such as `file.txt:10:5`, where `:10:5` is part of the filename.
It is also possible to open a file with a certain cursor location by using the
`+LINE,COL` flag syntax. See `micro -help` for the command line options.
default value: `false`
* `permbackup`: this option causes backups (see `backup` option) to be
permanently saved. With permanent backups, micro will not remove backups when
files are closed and will never apply them to existing files. Use this option
if you are interested in manually managing your backup files.
default value: `false`
* `pluginchannels`: list of URLs pointing to plugin channels for downloading and
installing plugins. A plugin channel consists of a json file with links to
plugin repos, which store information about plugin versions and download URLs.
@@ -199,6 +258,12 @@ Here are the available options:
default value: `true`
* `relativeruler`: make line numbers display relatively. If set to true, all lines except
for the line that the cursor is located will display the distance from the
cursor's line.
default value: `false`
* `savecursor`: remember where the cursor was last time the file was opened and
put it there when you open the file again. Information is saved to
`~/.config/micro/buffers/`

View File

@@ -43,6 +43,12 @@ are called when certain events happen. Here is the list of callbacks
which micro defines:
* `init()`: this function should be used for your plugin initialization.
This function is called after buffers have been initialized.
* `preinit()`: initialization function called before buffers have been
initialized.
* `postinit()`: initialization function called after `init()`.
* `onBufferOpen(buf)`: runs when a buffer is opened. The input contains
the buffer object.
@@ -359,6 +365,12 @@ library documentation at https://golang.org/pkg/ (for the packages
exposed to micro plugins). The Lua standard library is also available
to plugins though it is rather small.
The following functions are also available from the go-humanize package:
The `humanize` package exposes:
* `Bytes`
* `Ordinal`
## Adding help files, syntax files, or colorschemes in your plugin
You can use the `AddRuntimeFile(name string, type config.RTFiletype,

View File

@@ -16,8 +16,8 @@ the settings and their values. To change an option, you can either change the
value in the `settings.json` file, or you can type it in directly while using
micro.
Press CtrlE to go to command mode, and type `set option value` (in the
future, I will use `> set option value` to indicate pressing CtrlE). The change
Press Ctrl-e to go to command mode, and type `set option value` (in the
future, I will use `> set option value` to indicate pressing Ctrl-e). The change
will take effect immediately and will also be saved to the `settings.json` file
so that the setting will stick even after you close micro.
@@ -48,12 +48,12 @@ If you would like to know more about all the available options, see the
Keybindings work in much the same way as options. You configure them using the
`~/.config/micro/bindings.json` file.
For example if you would like to bind `CtrlR` to redo you could put the
For example if you would like to bind `Ctrl-r` to redo you could put the
following in `bindings.json`:
```json
{
"CtrlR": "redo"
"Ctrl-r": "redo"
}
```
@@ -74,7 +74,7 @@ micro starts and is essentially a one-file plugin. The plugin name is
`initlua`.
This example will show you how to use the `init.lua` file by creating a binding
to `CtrlR` which will execute the bash command `go run` on the current file,
to `Ctrl-r` which will execute the bash command `go run` on the current file,
given that the current file is a Go file.
You can do that by putting the following in `init.lua`:
@@ -84,9 +84,9 @@ local config = import("micro/config")
local shell = import("micro/shell")
function init()
-- true means overwrite any existing binding to CtrlR
-- true means overwrite any existing binding to Ctrl-r
-- this will modify the bindings.json file
config.TryBindKey("CtrlR", "lua:initlua.gorun", true)
config.TryBindKey("Ctrl-r", "lua:initlua.gorun", true)
end
function gorun(bp)
@@ -104,7 +104,7 @@ the `bindings.json` file:
```json
{
"CtrlR": "lua:initlua.gorun"
"Ctrl-r": "lua:initlua.gorun"
}
```

View File

@@ -28,7 +28,7 @@ function onRune(bp, r)
if r == charAt(autoclosePairs[i], 1) then
local curLine = bp.Buf:Line(bp.Cursor.Y)
if bp.Cursor.X == utf8.RuneCountInString(curLine) or not uutil.IsWordChar(charAt(curLine, bp.Cursor.X+1)) then
if bp.Cursor.X == uutil.CharacterCountInString(curLine) or not uutil.IsWordChar(charAt(curLine, bp.Cursor.X+1)) then
-- the '-' here is to derefence the pointer to bp.Cursor.Loc which is automatically made
-- when converting go structs to lua
-- It needs to be dereferenced because the function expects a non pointer struct

View File

@@ -6,23 +6,59 @@ local buffer = import("micro/buffer")
local ft = {}
ft["apacheconf"] = "# %s"
ft["bat"] = ":: %s"
ft["c"] = "// %s"
ft["c++"] = "// %s"
ft["cmake"] = "# %s"
ft["conf"] = "# %s"
ft["crystal"] = "# %s"
ft["css"] = "/* %s */"
ft["d"] = "// %s"
ft["dart"] = "// %s"
ft["dockerfile"] = "# %s"
ft["elm"] = "-- %s"
ft["fish"] = "# %s"
ft["gdscript"] = "# %s"
ft["glsl"] = "// %s"
ft["go"] = "// %s"
ft["python"] = "# %s"
ft["python3"] = "# %s"
ft["haskell"] = "-- %s"
ft["html"] = "<!-- %s -->"
ft["ini"] = "; %s"
ft["java"] = "// %s"
ft["javascript"] = "// %s"
ft["jinja2"] = "{# %s #}"
ft["julia"] = "# %s"
ft["kotlin"] = "// %s"
ft["lua"] = "-- %s"
ft["markdown"] = "<!-- %s -->"
ft["nginx"] = "# %s"
ft["nim"] = "# %s"
ft["objc"] = "// %s"
ft["ocaml"] = "(* %s *)"
ft["pascal"] = "{ %s }"
ft["perl"] = "# %s"
ft["php"] = "// %s"
ft["rust"] = "// %s"
ft["shell"] = "# %s"
ft["lua"] = "-- %s"
ft["javascript"] = "// %s"
ft["pony"] = "// %s"
ft["powershell"] = "# %s"
ft["proto"] = "// %s"
ft["python"] = "# %s"
ft["python3"] = "# %s"
ft["ruby"] = "# %s"
ft["d"] = "// %s"
ft["rust"] = "// %s"
ft["scala"] = "// %s"
ft["shell"] = "# %s"
ft["sql"] = "-- %s"
ft["swift"] = "// %s"
ft["tex"] = "% %s"
ft["toml"] = "# %s"
ft["twig"] = "{# %s #}"
ft["v"] = "// %s"
ft["xml"] = "<!-- %s -->"
ft["yaml"] = "# %s"
ft["zig"] = "// %s"
ft["zscript"] = "// %s"
ft["zsh"] = "# %s"
function onBufferOpen(buf)
if buf.Settings["commenttype"] == nil then
@@ -34,10 +70,38 @@ function onBufferOpen(buf)
end
end
function isCommented(bp, lineN, commentRegex)
local line = bp.Buf:Line(lineN)
if string.match(line, commentRegex) then
return true
end
return false
end
function commentLine(bp, lineN)
local line = bp.Buf:Line(lineN)
local commentType = bp.Buf.Settings["commenttype"]
local commentRegex = "^%s*" .. commentType:gsub("%*", "%*"):gsub("%-", "%-"):gsub("%.", "%."):gsub("%+", "%+"):gsub("%]", "%]"):gsub("%[", "%["):gsub("%%s", "(.*)")
local sel = -bp.Cursor.CurSelection
local curpos = -bp.Cursor.Loc
local index = string.find(commentType, "%%s") - 1
local commentedLine = commentType:gsub("%%s", trim(line))
bp.Buf:Replace(buffer.Loc(0, lineN), buffer.Loc(#line, lineN), util.GetLeadingWhitespace(line) .. commentedLine)
if bp.Cursor:HasSelection() then
bp.Cursor.CurSelection[1].Y = sel[1].Y
bp.Cursor.CurSelection[2].Y = sel[2].Y
bp.Cursor.CurSelection[1].X = sel[1].X
bp.Cursor.CurSelection[2].X = sel[2].X
else
bp.Cursor.X = curpos.X + index
bp.Cursor.Y = curpos.Y
end
bp.Cursor:Relocate()
bp.Cursor.LastVisualX = bp.Cursor:GetVisualX()
end
function uncommentLine(bp, lineN, commentRegex)
local line = bp.Buf:Line(lineN)
local commentType = bp.Buf.Settings["commenttype"]
local sel = -bp.Cursor.CurSelection
local curpos = -bp.Cursor.Loc
local index = string.find(commentType, "%%s") - 1
@@ -53,51 +117,63 @@ function commentLine(bp, lineN)
bp.Cursor.X = curpos.X - index
bp.Cursor.Y = curpos.Y
end
else
local commentedLine = commentType:gsub("%%s", trim(line))
bp.Buf:Replace(buffer.Loc(0, lineN), buffer.Loc(#line, lineN), util.GetLeadingWhitespace(line) .. commentedLine)
if bp.Cursor:HasSelection() then
bp.Cursor.CurSelection[1].Y = sel[1].Y
bp.Cursor.CurSelection[2].Y = sel[2].Y
bp.Cursor.CurSelection[1].X = sel[1].X
bp.Cursor.CurSelection[2].X = sel[2].X
else
bp.Cursor.X = curpos.X + index
bp.Cursor.Y = curpos.Y
end
end
bp.Cursor:Relocate()
bp.Cursor.LastVisualX = bp.Cursor:GetVisualX()
end
function commentSelection(bp, startLine, endLine)
function toggleCommentLine(bp, lineN, commentRegex)
if isCommented(bp, lineN, commentRegex) then
uncommentLine(bp, lineN, commentRegex)
else
commentLine(bp, lineN)
end
end
function toggleCommentSelection(bp, startLine, endLine, commentRegex)
local allComments = true
for line = startLine, endLine do
commentLine(bp, line)
if not isCommented(bp, line, commentRegex) then
allComments = false
break
end
end
for line = startLine, endLine do
if allComments then
uncommentLine(bp, line, commentRegex)
else
commentLine(bp, line)
end
end
end
function comment(bp, args)
local commentType = bp.Buf.Settings["commenttype"]
local commentRegex = "^%s*" .. commentType:gsub("%%","%%%%"):gsub("%$","%$"):gsub("%)","%)"):gsub("%(","%("):gsub("%?","%?"):gsub("%*", "%*"):gsub("%-", "%-"):gsub("%.", "%."):gsub("%+", "%+"):gsub("%]", "%]"):gsub("%[", "%["):gsub("%%%%s", "(.*)"):gsub("%s+", "%s*")
if bp.Cursor:HasSelection() then
if bp.Cursor.CurSelection[1]:GreaterThan(-bp.Cursor.CurSelection[2]) then
local endLine = bp.Cursor.CurSelection[1].Y
if bp.Cursor.CurSelection[1].X == 0 then
endLine = endLine - 1
end
commentSelection(bp, bp.Cursor.CurSelection[2].Y, endLine)
toggleCommentSelection(bp, bp.Cursor.CurSelection[2].Y, endLine, commentRegex)
else
local endLine = bp.Cursor.CurSelection[2].Y
if bp.Cursor.CurSelection[2].X == 0 then
endLine = endLine - 1
end
commentSelection(bp, bp.Cursor.CurSelection[1].Y, endLine)
toggleCommentSelection(bp, bp.Cursor.CurSelection[1].Y, endLine, commentRegex)
end
else
commentLine(bp, bp.Cursor.Y)
toggleCommentLine(bp, bp.Cursor.Y, commentRegex)
end
end
function trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
local trimmed = s:gsub("^%s*(.-)%s*$", "%1"):gsub("%%","%%%%")
return trimmed
end
function string.starts(String,Start)
@@ -107,5 +183,6 @@ end
function init()
config.MakeCommand("comment", comment, config.NoComplete)
config.TryBindKey("Alt-/", "lua:comment.comment", false)
config.TryBindKey("CtrlUnderscore", "lua:comment.comment", false)
config.AddRuntimeFile("comment", config.RTHelp, "help/comment.md")
end

View File

@@ -1,8 +1,10 @@
# Comment Plugin
The comment plugin provides auto commenting/uncommenting.
The default binding to comment/uncomment a line is `Alt-/`,
but you can easily modify that in your `bindings.json` file:
The default binding to comment/uncomment a line is `Alt-/`
and `CtrlUnderscore`, which is equivalent in most terminals
to `Ctrl-/`. You can easily modify that in your `bindings.json`
file:
```json
{
@@ -23,23 +25,58 @@ selected.
The comment type will be auto detected based on the filetype,
but it is only available for certain filetypes:
* apacheconf: `# %s`
* bat: `:: %s`
* c: `// %s`
* c++: `// %s`
* cmake: `# %s`
* conf: `# %s`
* crystal: `# %s`
* css: `/* %s */`
* d: `// %s`
* dart: `// %s`
* dockerfile: `# %s`
* elm: `-- %s`
* fish: `# %s`
* gdscript: `# %s`
* glsl: `// %s`
* go: `// %s`
* haskell: `-- %s`
* html: `<!-- %s -->`
* ini: `; %s`
* java: `// %s`
* javascript: `// %s`
* jinja2: `{# %s #}`
* julia: `# %s`
* kotlin: `// %s`
* lua: `-- %s`
* markdown: `<!-- %s -->`
* nginx: `# %s`
* nim: `# %s`
* objc: `// %s`
* pascal: `{ %s }`
* perl: `# %s`
* php: `// %s`
* pony: `// %s`
* powershell: `# %s`
* proto: `// %s`
* python: `# %s`
* python3: `# %s`
* ruby: `# %s`
* rust: `// %s`
* scala: `// %s`
* shell: `# %s`
* sql: `-- %s`
* swift: `// %s`
* tex: `% %s`
* toml: `# %s`
* twig: `{# %s #}`
* v: `// %s`
* xml: `<!-- %s -->`
* yaml: `# %s`
* zig: `// %s`
* zscript: `// %s`
* zsh: `# %s`
If your filetype is not available here, you can simply modify
the `commenttype` option:
@@ -57,4 +94,3 @@ Or in your `settings.json`:
}
}
```

View File

@@ -9,8 +9,10 @@ following filetypes and linters:
* c++: g++
* d: dmd
* go: go build
* haskell: hlint
* java: javac
* javascript: jshint
* javascript: eslint
* literate: lit
* lua: luacheck
* nim: nim
@@ -19,7 +21,7 @@ following filetypes and linters:
* python: mypy
* python: pylint
* shell: shfmt
* swift: swiftc
* swift: swiftc (MacOS and Linux only)
* yaml: yamllint
If the linter plugin is enabled and the file corresponds to one of
@@ -64,17 +66,17 @@ Below is an example for including a linter for any filetype using
the `misspell` linter which checks for misspelled words in a file.
```lua
local config = import("micro/config")
config.RegisterCommonOption("misspell", true)
function init()
-- uses the default linter plugin
-- matches any filetype
linter.makeLinter("misspell", "", "misspell", {"%f"}, "%f:%l:%c: %m", {}, false, true, 0, 0, hasMisspell)
end
function hasMisspell(buf)
return buf.Settings["misspell"]
linter.makeLinter("misspell", "", "misspell", {"%f"}, "%f:%l:%c: %m", {}, false, true)
end
```
Here is an example for a more typical use-case, where the linter will only match one filetype (C in this case):
```lua
function init()
linter.makeLinter("gcc", "c", "gcc", {"-fsyntax-only", "-Wall", "-Wextra", "%f"}, "%f:%l:%c:.+: %m")
end
```

View File

@@ -59,17 +59,19 @@ function removeLinter(name)
linters[name] = nil
end
function init()
function preinit()
local devnull = "/dev/null"
if runtime.GOOS == "windows" then
devnull = "NUL"
end
makeLinter("gcc", "c", "gcc", {"-fsyntax-only", "-Wall", "-Wextra", "%f"}, "%f:%l:%c:.+: %m")
makeLinter("gcc", "c++", "gcc", {"-fsyntax-only","-std=c++14", "-Wall", "-Wextra", "%f"}, "%f:%l:%c:.+: %m")
makeLinter("g++", "c++", "gcc", {"-fsyntax-only","-std=c++14", "-Wall", "-Wextra", "%f"}, "%f:%l:%c:.+: %m")
makeLinter("dmd", "d", "dmd", {"-color=off", "-o-", "-w", "-wi", "-c", "%f"}, "%f%(%l%):.+: %m")
makeLinter("eslint", "javascript", "eslint", {"-f","compact","%f"}, "%f: line %l, col %c, %m")
makeLinter("gobuild", "go", "go", {"build", "-o", devnull, "%d"}, "%f:%l:%c:? %m")
-- makeLinter("golint", "go", "golint", {"%f"}, "%f:%l:%c: %m")
makeLinter("hlint", "haskell", "hlint", {"%f"}, "%f:%l:%c.-: %m")
makeLinter("javac", "java", "javac", {"-d", "%d", "%f"}, "%f:%l: error: %m")
makeLinter("jshint", "javascript", "jshint", {"%f"}, "%f: line %l,.+, %m")
makeLinter("literate", "literate", "lit", {"-c", "%f"}, "%f:%l:%m", {}, false, true)
@@ -79,9 +81,10 @@ function init()
makeLinter("pyflakes", "python", "pyflakes", {"%f"}, "%f:%l:.-:? %m")
makeLinter("mypy", "python", "mypy", {"%f"}, "%f:%l: %m")
makeLinter("pylint", "python", "pylint", {"--output-format=parseable", "--reports=no", "%f"}, "%f:%l: %m")
makeLinter("flake8", "python", "flake8", {"%f"}, "%f:%l:%c: %m")
makeLinter("shfmt", "shell", "shfmt", {"%f"}, "%f:%l:%c: %m")
makeLinter("swiftc", "swift", "xcrun", {"swiftc", "%f"}, "%f:%l:%c:.+: %m", {"darwin"}, true)
makeLinter("swiftc", "swiftc", {"%f"}, "%f:%l:%c:.+: %m", {"linux"}, true)
makeLinter("swiftc", "swift", "swiftc", {"%f"}, "%f:%l:%c:.+: %m", {"linux"}, true)
makeLinter("yaml", "yaml", "yamllint", {"--format", "parsable", "%f"}, "%f:%l:%c:.+ %m")
config.MakeCommand("lint", function(bp, args)
@@ -165,7 +168,6 @@ function onExit(output, args)
elseif col == nil then
hascol = false
end
micro.Log(basename(buf.Path), basename(file))
if basename(buf.Path) == basename(file) then
local bmsg = nil
if hascol then

View File

@@ -6,10 +6,14 @@ Using the `statusformatl` and `statusformatr` options, the exact contents
of the status line can be modified. Please see the documentation for
those options (`> help options`) for more information.
This plugin provides the three functions that can be used in the status
line format:
This plugin provides functions that can be used in the status line format:
* `status.branch`: returns the name of the current git branch.
* `status.hash`: returns the hash of the current git commit.
* `status.paste`: returns "" if the paste option is disabled and "PASTE"
if it is enabled.
* `status.lines`: returns the number of lines in the buffer.
* `status.vcol`: returns the visual column number of the cursor.
* `status.bytes`: returns the number of bytes in the current buffer.
* `status.size`: returns the size of the current buffer in a human-readable
format.

View File

@@ -3,14 +3,35 @@ VERSION = "1.0.0"
local micro = import("micro")
local buffer = import("micro/buffer")
local config = import("micro/config")
local humanize = import("humanize")
function init()
micro.SetStatusInfoFn("status.branch")
micro.SetStatusInfoFn("status.hash")
micro.SetStatusInfoFn("status.paste")
micro.SetStatusInfoFn("status.vcol")
micro.SetStatusInfoFn("status.lines")
micro.SetStatusInfoFn("status.bytes")
micro.SetStatusInfoFn("status.size")
config.AddRuntimeFile("status", config.RTHelp, "help/status.md")
end
function lines(b)
return tostring(b:LinesNum())
end
function vcol(b)
return tostring(b:GetActiveCursor():GetVisualX())
end
function bytes(b)
return tostring(b:Size())
end
function size(b)
return humanize.Bytes(b:Size())
end
function branch(b)
if b.Type.Kind ~= buffer.BTInfo then
local shell = import("micro/shell")

View File

@@ -1,28 +0,0 @@
filetype: c++
detect:
filename: "\\.c(c|pp|xx)$|\\.h(h|pp|xx)$|\\.ii?$|\\.(def)$"
rules:
- identifier: "\\b[A-Z_][0-9A-Z_]+\\b"
- type: "\\b(auto|float|double|bool|char|int|short|long|sizeof|enum|void|static|const|constexpr|struct|union|typedef|extern|(un)?signed|inline)\\b"
- type: "\\b((s?size)|((u_?)?int(8|16|32|64|ptr)))_t\\b"
- statement: "\\b(class|namespace|template|public|protected|private|typename|this|friend|virtual|using|mutable|volatile|register|explicit)\\b"
- statement: "\\b(for|if|while|do|else|case|default|switch)\\b"
- statement: "\\b(try|throw|catch|operator|new|delete)\\b"
- special: "\\b(goto|continue|break|return)\\b"
- preproc: "^[[:space:]]*#[[:space:]]*(define|pragma|include|(un|ifn?)def|endif|el(if|se)|if|warning|error)"
- constant: "'([^'\\\\]|(\\\\[\"'abfnrtv\\\\]))'|'\\\\(([0-3]?[0-7]{1,2}))'|'\\\\x[0-9A-Fa-f]{1,2}'"
- statement: "__attribute__[[:space:]]*\\(\\([^)]*\\)\\)|__(aligned|asm|builtin|hidden|inline|packed|restrict|section|typeof|weak)__"
- symbol.operator: "[.:;,+*|=!\\%]|<|>|/|-|&"
- symbol.brackets: "[(){}]|\\[|\\]"
- constant.number: "\\b[0-9]+\\b|\\b0x[0-9A-Fa-f]+\\b"
- constant.bool: "\\b(true|false)\\b|NULL"
- constant.string: "\"(\\\\.|[^\"])*\""
- comment: "//.*"
- comment:
start: "/\\*"
end: "\\*/"
rules: []
- indent-char.whitespace: "[[:space:]]+$"

View File

@@ -12,9 +12,6 @@ rules:
- statement: "\\b(for|if|while|do|else|case|default|switch)\\b"
- statement: "\\b(goto|continue|break|return)\\b"
- preproc: "^[[:space:]]*#[[:space:]]*(define|pragma|include|(un|ifn?)def|endif|el(if|se)|if|warning|error)"
- constant: "'([^'\\\\]|(\\\\[\"'abfnrtv\\\\]))'"
- constant: "'\\\\(([0-3]?[0-7]{1,2}))'"
- constant: "'\\\\x[0-9A-Fa-f]{1,2}'"
# GCC builtins
- statement: "__attribute__[[:space:]]*\\(\\([^)]*\\)\\)"
- statement: "__(aligned|asm|builtin|hidden|inline|packed|restrict|section|typeof|weak)__"
@@ -29,15 +26,15 @@ rules:
end: "\""
skip: "\\\\."
rules:
- constant.specialChar: "\\\\."
- constant.specialChar: "\\\\([\"'abfnrtv\\\\]|[0-3]?[0-7]{1,2}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})"
- constant.string:
start: "'"
end: "'"
skip: "\\\\."
rules:
- preproc: "..+"
- constant.specialChar: "\\\\."
- error: "..+"
- constant.specialChar: "\\\\([\"'abfnrtv\\\\]|[0-3]?[0-7]{1,2}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})"
- comment:
start: "//"

View File

@@ -12,6 +12,9 @@ rules:
- statement: "\\b(debugger|switch|while|do|class|extends|super)\\b"
- statement: "\\b(undefined|then|unless|until|loop|of|by|when)\\b"
- constant.bool: "\\b(true|false|yes|no|on|off)\\b"
- constant.number: "\\b[-+]?([1-9][0-9]*|0[0-7]*|0x[0-9a-fA-F]+)([uU][lL]?|[lL][uU]?)?\\b"
- constant.number: "\\b[-+]?([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+)([EePp][+-]?[0-9]+)?[fFlL]?"
- constant.number: "\\b[-+]?([0-9]+[EePp][+-]?[0-9]+)[fFlL]?"
- identifier: "@[A-Za-z0-9_]*"
- constant.string:
@@ -20,10 +23,23 @@ rules:
skip: "\\\\."
rules:
- constant.specialChar: "\\\\."
- constant.string:
start: "'"
end: "'"
skip: "\\\\."
rules:
- constant.specialChar: "\\\\."
- comment:
start: "#"
end: "$"
rules:
- todo: "(TODO|XXX|FIXME):?"
- comment:
start: "###"
end: "###"
rules:
- todo: "(TODO|XXX|FIXME)"

View File

@@ -4,8 +4,7 @@ detect:
filename: "(\\.c(c|pp|xx)$|\\.h(h|pp|xx)$|\\.ii?$|\\.(def)$)"
rules:
- identifier: "\\b[A-Z_][0-9A-Z_]+\\b"
- identifier: "\\b[A-Z_][0-9A-Z_]+\\b"
- type: "\\b(auto|float|double|bool|char|int|short|long|sizeof|enum|void|static|const|constexpr|struct|union|typedef|extern|(un)?signed|inline)\\b"
- type: "\\b((s?size)|((u_?)?int(8|16|32|64|ptr)))_t\\b"
- statement: "\\b(class|namespace|template|public|protected|private|typename|this|friend|virtual|using|mutable|volatile|register|explicit)\\b"
@@ -13,13 +12,12 @@ rules:
- statement: "\\b(try|throw|catch|operator|new|delete)\\b"
- statement: "\\b(goto|continue|break|return)\\b"
- preproc: "^[[:space:]]*#[[:space:]]*(define|pragma|include|(un|ifn?)def|endif|el(if|se)|if|warning|error)"
- constant: "('([^'\\\\]|(\\\\[\"'abfnrtv\\\\]))'|'\\\\(([0-3]?[0-7]{1,2}))'|'\\\\x[0-9A-Fa-f]{1,2}')"
# GCC builtins
- statement: "(__attribute__[[:space:]]*\\(\\([^)]*\\)\\)|__(aligned|asm|builtin|hidden|inline|packed|restrict|section|typeof|weak)__)"
# Operator Color
- symbol.operator: "([.:;,+*|=!\\%]|<|>|/|-|&)"
- symbol.operator: "([.:;,+*|=!\\%]|<|>|/|-|&)"
# Parenthetical Color
- symbol.brackets: "[(){}]|\\[|\\]"
@@ -31,15 +29,15 @@ rules:
end: "\""
skip: "\\\\."
rules:
- constant.specialChar: "\\\\."
- constant.specialChar: "\\\\([\"'abfnrtv\\\\]|[0-3]?[0-7]{1,2}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})"
- constant.string:
start: "'"
end: "'"
skip: "\\\\."
rules:
- preproc: "..+"
- constant.specialChar: "\\\\."
- error: "..+"
- constant.specialChar: "\\\\([\"'abfnrtv\\\\]|[0-3]?[0-7]{1,2}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})"
- comment:
start: "//"

View File

@@ -14,16 +14,16 @@ rules:
# month 0-12 (or names, see below)
# day of week 0-7 (0 or 7 is Sun, or use names)
- statement: "^([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+(.*)$\\n?"
- constant: "^([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)"
- statement: "^([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+(([\\*0-9,\\-\\/]+)|(\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\b))\\s+(([\\*0-9,\\-\\/]+)|(\\b(sun|mon|tue|wed|thu|fri|sat)\\b))\\s+(.*)$\\n?"
- constant: "^([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+([\\*0-9,\\-\\/]+)\\s+(([\\*0-9,\\-\\/]+)|(\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\b))\\s+(([\\*0-9,\\-\\/]+)|(\\b(sun|mon|tue|wed|thu|fri|sat)\\b))"
# Shell Values
- type: "^[A-Z]+\\="
# Months and weekday keywords
- type: "jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec"
- constant: "sun|mon|tue|wed|thu|fri|sat"
- type: "\\@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)"
- constant: "\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\b"
- constant: "\\b(sun|mon|tue|wed|thu|fri|sat)\\b"
- type: "\\@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)\\b"
# Conditionals
- special: "(\\{|\\}|\\(|\\)|\\;|\\]|\\[|`|\\\\|\\$|<|>|^|!|=|&|\\|)"

Some files were not shown because too many files have changed in this diff Show More